DEV Community

Discussion on: Challenge: Write the recursive Fibonacci algorithm in a different language.

Collapse
 
stereobooster profile image
stereobooster • Edited

No worries @avalander . You all did right, it is just JS doesn't support TCO there were some attempts (as far as I remember it is hold back by Microsoft member or committee or something like that). There is still way around - you can use trampoline

const trampoline = (fn) => {
  let newFn = eval(fn.toString().replace(new RegExp(fn.name + '\\(([^\\)]*)\\)'), '[$1]'))
  return function() {
    let result = newFn.apply(null, arguments)
    while (result instanceof Array) result = newFn.apply(null, result)
    return result
  }
};

const _fibonacciIter = (n, i, curr, prev) =>
    (i >= n ? curr : _fibonacciIter(n, i + 1, curr + prev, curr));

const fibonacciIter = trampoline(_fibonacciIter);

const fibonacci = n => fibonacciIter(n, 0, 1, 0);

I doubt you would want to use this in production, but just to make a point.

TCO - stands for tail call optimisation, to prevent Maximum call stack error
Trampoline is the way how some compilers implement TCO, they convert recursion to a loop

UPD: read about TCO status in Chrome here stackoverflow.com/questions/427881...

Thread Thread
 
avalander profile image
Avalander

Wow, that's great, I didn't know this trick, thank you!