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:
[0,1].concat([...Array(n-1)])
n=4
[0, 1, undefined, undefined, undefined]
i<=1
a[i-1] + a[i-2]
n
A few guards had to be added to handle n=0 and n=1 input:
n=0
n=1
concat
[0, 1].concat([...''])
[0, 1]
.pop()
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
How about some ugly oneliner in JS?
It works like that:
[0,1].concat([...Array(n-1)])
will build the following array withn=4
:[0, 1, undefined, undefined, undefined]
i<=1
), or add up the two last values (a[i-1] + a[i-2]
)n
th index)A few guards had to be added to handle
n=0
andn=1
input:concat
step ([0, 1].concat([...''])
will return[0, 1]
).pop()
), but the one stored on then
th index