Home > Article > Web Front-end > JavaScript Fun Question: Fibonacci Sequence Generator
Create a function generator genfib(), which can return a function. Each time this function is executed, it returns the next item in the Fibonacci sequence. The first item 0 is returned the first time it is executed.
The example is as follows:
var fib = genfib(); fib(); // -> returns 0 fib(); // -> returns 1 fib(); // -> returns 1 fib(); // -> returns 2
When I got this question, my first thought was to make a fuss in genfib(). Because it returns a function, I first return a closure in it. Function, no matter what is in it.
Then, according to the meaning of the question, how can we define an internal function in genfib() to find the Nth term of the Fibonacci sequence. Here I use divide and conquer recursion.
So how to combine the closure function and this private function to achieve the effect of returning the next Fibonacci sequence every time it is executed?
You can use an internal pointer variable point, which starts to point to 0. Every time the closure function is called, we execute the private function, pass the pointer variable as a parameter, and return the Fibonacci of the current item. number, and then the pointer variable is incremented.
This achieves the goal.
function genfib(){ var point = 0; var getFib = function(num){ if(num == 0){ return 0; } if(num == 1){ return 1; } return getFib(num-1) + getFib(num-2); }; return function fib(){ return getFib(point++); } }
The above is the content of JavaScript Fun Question: Fibonacci Sequence Generator. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!