Closure, Memorization and the Fibonacci Sequence
A Fibonacci sequence is the series of numbers where the nth number is the result of the (n-1) number + (n-2) number. The sequence is:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
So, fib(4) = fib(3)+fib(2) = 2 + 1 = 3,
and fib(10) = fib(9) + fib(8) = 34 + 21 = 55, and so on
Let’s try writing a JavaScript function to generate a Fibonacci sequence. The algorithm logic we’ll follow is:
fib(n) is:
if(n is 0) then fib(0) = 0;
if(n is 1) then fib(1) = 1;
otherwise fib(n) = fib(n-1) + fib(n+2)
In case you’ve not noticed it yet, we are going to write a recursive function which will call itself to get the Fibonacci values for (n-1) and (n-2). 😃
The function should like like this.
Running the above code will result in the following (P.S. I’m using Visual Studio Code to write my code and node.js to run JavaScript codes.)