Files
odin-javascript-exercises/05_sumAll/solution/sumAll-solution.js
T

22 lines
614 B
JavaScript
Raw Normal View History

2022-02-20 14:07:44 -05:00
const sumAll = function (min, max) {
2023-01-21 12:53:41 -05:00
if (!Number.isInteger(min) || !Number.isInteger(max)) return "ERROR";
if (min < 0 || max < 0) return "ERROR";
2023-07-29 15:40:07 -05:00
if (min > max) {
2023-07-29 15:39:33 -05:00
const temp = min;
min = max;
max = temp;
}
2023-07-03 22:52:46 -05:00
2023-07-29 15:39:33 -05: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 12:53:41 -05:00
let sum = 0;
2023-07-03 22:58:19 -05:00
for (let i = min; i <= max; i++) {
2023-01-21 12:53:41 -05:00
sum += i;
}
return sum;
2022-02-20 14:07:44 -05:00
};
module.exports = sumAll;