DEV Community

Discussion on: Solving "Sum All Odd Fibonacci Numbers" / freeCodeCamp Algorithm Challenges

Collapse
ttatsf profile image
tatsuo fukuchi

Oh yes, I think so!
How do you like this?:

const memoizer = inits => rule =>{
  const memo = [...inits]
  const elem = n =>
    n >= memo.length ? memo[n] = rule(elem)(n)
    : memo[n]
  return elem
}

const fib = 
  memoizer( [0, 1] )( a => n => a(n-1) + a(n-2) )

const oddFibG = function*(){
  let i = 0
  let value 
  while (true){
    value = fib(i)
    if (value % 2 === 1) yield value
    i = i + 1
  }
}

const sumFibs = n => {
  let sum = 0
  for ( const i of oddFibG() ) {
    if ( i > n ) return sum
    sum = sum + i
  }
}

It's a little more complex, but very much faster than the above.