Home > Web Front-end > JS Tutorial > body text

JavaScript Fun Question: Fibonacci Sequence Generator

黄舟
Release: 2017-01-22 14:54:31
Original
1683 people have browsed it

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
Copy after login

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++);  
    }  
}
Copy after login

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)!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template