DEV Community

Discussion on: Let's Get Clever #1: Fibonacci Sequence

Collapse
 
ynndvn profile image
La blatte • Edited

How about some ugly oneliner in JS?

f=(n)=>[0,1].concat([...n>1?Array(n-1):'']).map((v,i,a)=>a[i]=i>1?a[i-1]+a[i-2]:v)[n];

It works like that:

  • First, build a prefilled array. [0,1].concat([...Array(n-1)]) will build the following array with n=4: [0, 1, undefined, undefined, undefined]
  • Loop (sorry) through this array and either use the prefilled value (if i<=1), or add up the two last values (a[i-1] + a[i-2])
  • Finally, return the correct value from the array (at nth index)

A few guards had to be added to handle n=0 and n=1 input:

  • Do not add any Array on the concat step ([0, 1].concat([...'']) will return [0, 1])
  • Do not return the last value of the array (.pop()), but the one stored on the nth index