dragi
dragi

Reputation: 1512

Sum every element in a range in Javascript

I'm trying to make my small function work which adds every number together in a range.

For example when I call the method like: sumAll(3,10) it should do 3+4+5+6+7+8+9+10

It works if I give the function positive integers but if it receives a negative number or a string or an array for example, it doesn't work properly.. I just want to return "ERROR" if the supplied parameter is not a positive integer.

Can I have some help with this please? Is there a more elegant (better) way?

My code:

const sumAll = (...args) => {
    let max = Math.max(...args);
    let min = Math.min(...args);

    if ((min < 0) || (!Number.isInteger(min)) || (!Number.isInteger(max)) || (Array.isArray(...args))) {
        return "ERROR";
    }

    let n = (max - min) + 1;

    return ((max + min) * n) / 2;
}

Upvotes: 3

Views: 92

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386610

You could use a gaussian formular for getting a count from 1 ... n and subtract the sub count.

For getting only a result if possible, you could add a check for positive integers.

const
    isPositiveInt = v => Number.isInteger(v) && v > 0,
    sumN = n => n * (n + 1) / 2,
    range = (m, n) => isPositiveInt(m) && isPositiveInt(n)
        ? sumN(Math.max(m, n)) - sumN(Math.min(m, n) - 1)
        : 'ERROR';

console.log(range(3, 10));
console.log(range(10, 3));
console.log(range());
console.log(range(3));
console.log(range('', 10));
console.log(range(0.2, 0.3));

Upvotes: 2

Related Questions