odin-default-js-exercises/05_sumAll/solution/sumAll-solution.js

22 lines
614 B
JavaScript
Raw Permalink Normal View History

2022-02-20 19:07:44 +00:00
const sumAll = function (min, max) {
2023-01-21 17:53:41 +00:00
if (!Number.isInteger(min) || !Number.isInteger(max)) return "ERROR";
if (min < 0 || max < 0) return "ERROR";
2023-07-29 20:40:07 +00:00
if (min > max) {
2023-07-29 20:39:33 +00:00
const temp = min;
min = max;
max = temp;
}
2023-07-29 20:39:33 +00:00
// An alternative way to swap the values of min and max like above is to use the array destructuring syntax.
// Here's an optional article on it: https://www.freecodecamp.org/news/array-destructuring-in-es6-30e398f21d10/
// if (min > max) [min, max] = [max, min];
2023-01-21 17:53:41 +00:00
let sum = 0;
2023-07-04 03:58:19 +00:00
for (let i = min; i <= max; i++) {
2023-01-21 17:53:41 +00:00
sum += i;
}
return sum;
2022-02-20 19:07:44 +00:00
};
module.exports = sumAll;