DEV Community

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

Collapse
 
avalander profile image
Avalander • Edited

I'll continue with javascript.

const fibonacci = (n, i=0, curr=1, prev=0) =>
    (i >= n ? curr : fibonacci(n, i + 1, curr + prev, curr))

(Look mum, with a single expression function!)

Collapse
 
gypsydave5 profile image
David Wickes

I like this! Don't think you need the outer parens though :D

Collapse
 
avalander profile image
Avalander

Should work without, I'm just used to wrapping ternary expressions between them for some reason and I find it weird without :)

Collapse
 
gypsydave5 profile image
David Wickes • Edited

To be absolutely pedantic, this code is valid and will work with large numbers because it is written in EcmaScript 6. Part of the ES6 standard is for the language interpreter to implement tail call optimization (TCO). EcmaScript is a language defined by a standard, not by an implementation.

Now, at present, barely any interpreters implement TCO - here's a fun comparison table to see which do or don't. This makes me sad, but there we are.

But, as I say, the function above will work just fine according to the language standard. Whether this code blows the call stack of your interpreter is dependent on whether your interpreter implements the full ES6 standard. Which it probably doesn't.

To put it strongly, complaining that this code doesn't run on an JS interpreter without TCO is like complaining that it can't run by a Ruby interpreter. The fault is with the interpreter, not the code.