JavaScript fun: Fibonacci sequence generator

Source: Internet
Author: User
Create a function generator genfib (), which returns a function. Each time this function is executed, the next item in the Fibonacci series is returned, and the first item 0 is returned during the first execution. Example: Create a function generator genfib (), which returns a function. Each time this function is executed, the next item in the Fibonacci series is returned, and the first item 0 is returned during the first execution.

Example:

var fib = genfib();  fib(); // -> returns 0  fib(); // -> returns 1  fib(); // -> returns 1  fib(); // -> returns 2

When I got this question, I first thought it was done in genfib (), because it had to return a function, so I first returned a closure function in it, and there was something in render manager.

Then, based on the meaning of the question, we define an internal function in genfib () to evaluate the nth Fibonacci series. Here I use the divide recursion.

So how can we combine the closure function and this private function to achieve the effect of returning the next Fibonacci series for every execution?

You can use an internal pointer variable point, which starts to point to 0. Every time you call the closure function, we execute a private function and pass the pointer variable as a parameter, returns the Fibonacci number of the current item, and the pointer variable is auto-incrementing.

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 JavaScript interesting question: the content of the Fibonacci series generator. For more information, see the PHP Chinese website (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.