I would like to propose another solution to the Intermediate Algorithm Scripting: Sum All Odd Fibonacci Numbers.
This solution uses Array.push
, Array.filter
, and Array.reduce
to get the needed values.
Solution
const sumFibs = (num) => {
const fibonacci = [0,1,1];
while ( fibonacci[fibonacci.length - 1] < num ) {
fibonacci.push( fibonacci[fibonacci.length - 2] + fibonacci[fibonacci.length - 1] );
}
return fibonacci.filter(fibNum => fibNum % 2 === 1 && fibNum <= num).reduce(((sum,curVal) => sum + curVal), 0);
}
Explanation
- Create an array which holds the first three values of the Fibonacci sequence: 0, 1, and 1.
- Use a
while
loop to check the condition: is the last number in the Fibonacci array less than thenum
argument? - If not, then add a new number to the array, which is the sum of the second-to-last and the last number in the array.
- Once the
while
loop is completed, Return the combined result of filtering and reducing the Fibonacci array: filter by odd numbers that are less than or equal tonum
, then reduce the array to the sum of all remaining values.
Tests
/**
* Tests for sumFibs
*/
let testArr = [];
testArr.push(
[1000, 1785],
[4000000, 4613732],
[4, 5],
[75024, 60696],
[75025, 135721],
[0, 0],
[1, 2],
[2, 2],
[3, 5],
[undefined, 0],
)
testArr.forEach(arr => {
console.log(sumFibs(arr[0]) === arr[1] ? `PASS: The fib sum of ${arr[0]} == ${sumFibs(arr[0])} == ${arr[1]}` : `FAIL; ${arr[0]} got ${sumFibs(arr[0])}, expected ${arr[1]}`);
})