Review my code for (Sum All Numbers in a Range)

It’s interesting to see all the different solutions to the same problem.

Here is my first attempt -

function sumAll(arr) {
    let accum = 0;
    let a = arr[0];
    let b = arr[1];
    
    if(a > b) {
        let c = a;
        a = b;
        b = c;
    }

    for(let i = a; i <= b; i++) {
        accum += i;
    }

    return accum;
}

and my second attempt where I was determined to use reduce just for the sake of it -

function sumAll(arr) {
    const initialValue = 0;

    const sumWithInitial = spreadArr(arr).reduce(
        (accumulator, currentValue) => accumulator + currentValue,
        initialValue
 );    

    return sumWithInitial;
}

function spreadArr(arr) {
    let newArr = [];

    if(arr[0] > arr[1]) {
        for(let i = arr[0]; arr[1] <= i; i--) {
            newArr.push(i);    
        }
    } else {
        for(let i = arr[0]; arr[1] >= i; i++) {
            newArr.push(i);
        }
    }

    return newArr;
}

they both pass. Criticism most welcome :upside_down_face:

Please post a link to the challenge.

Consider adding comments to your code to explain the algorithm progression as well.

1 Like

Good work getting 2 working solutions!

I would use more descriptive variable names here.

This works since you wanted to be able to use reduce, but generally an array holding a range of numbers is to be discouraged.

1 Like