Sum All Odd Fibonacci Numbers solution not passing all tests

Sum All Odd Fibonacci Numbers solution not passing all tests


Tell us what’s happening:

Hi everybody!

It’s my first post on here so let me know if there are things I’ve missed about posting or if this is in the wrong place to start this thread.

The issue is that one of the offered solutions (Intermediate solution) for Intermediate Algorithm Scripting > Sum All Odd Fibonacci Numbers challenge is not passing all the tests and should probably be adjusted. Unfortunately I can’t figure out where the problem might lay exactly.

The code below is the offered provided found under ‘Get a Hint’ button.

Your code so far

function sumFibs(num) {
    // Perform checks for the validity of the input
    if (num < 0) return -1;
    if (num === 0 || num === 1) return 1;

    // Create an array of fib numbers till num
    const arrFib = [1, 1];
    let nextFib = 0;
    // We put the new Fibonacci numbers to the front so we
    // don't need to calculate the length of the array on each
    // iteration
    while((nextFib = arrFib[0] + arrFib[1]) <= num) {

    // Sum only the odd numbers and return the value
    return arrFib.reduce((acc, curr) => {
        return acc + curr * (curr % 2);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:

Use the Rest Operator with Function Parameters - A zero required?

Nice catch. What’s happening is that reduce, when not giving an initial value, uses the first element of the array as the acc. In some scenarios, that initial value is odd, so it skips our validation that checks if it is odd.

The solution then is pretty simple, we just supply an initial value of 0 to the reduce function.

return arrFib.reduce((acc, curr) => {
    return acc + curr * (curr % 2);
}, 0);

EDIT: I’ve created a PR to fix this.


Thanks for replying and making a PR!

Yeah, with the initial value for reduce provided it makes a lot more sense, thanks for figuring it out.