I'm trying to solve a challenge at FreeCodeCamp. but I'm trying to code in a more functional way. so the challenge is to sum all of the odd fibonacci numbers less than or equal a given number. I tried to avoid for loops and tried to use the accepted answer from this topic: How do I replace while loops with a functional programming alternative without tail call optimization?
But I cant figure out why this doesn't work. what am I missing? I'm very new at this so sorry if the answer is too easy.
const sumFibs = num => {
const repeat = n => f => x => {
let m = n
while (m > num - x.length) {
if (m === 0)
return x
else
(m = m - 1, x = f(x))
}
}
const gadzillionTimes = repeat(num)
const add1 = x => {
return x[0] + x[1] <= num ? [x[0] + x[1]].concat(x) : x;
}
const allFibonaci = gadzillionTimes(add1)([1, 1]);
return allFibonaci.filter(x => x % 2 !== 0).reduce((a, b) => a + b);
}
sumFibs(4000000);