user487743
user487743

Reputation: 2235

Javascript Fibonacci using Closures

I am to write up some code using Javascript. Here is what we are to do:

"Implement a javascript Fibonacci numbers using closures. Specifically, write an function that stores two consecuitive Fibonacci numbers, initially 0 and 1. The function also defines and returns a nested function getNext(). The getNext() function updates the two stored Fibonacci numbers to the next two Fibonacci numbers and returns the current one. E.g. on the first call to getNext() the return value is 0, on the next call it is 1, then 1 again, then 2, etc."

I kind of understand this but not really. Could someone maybe help clarify? Thanks!

Upvotes: 2

Views: 5643

Answers (4)

A. Newbie
A. Newbie

Reputation: 187

fibonacci = ([f0, f1] = [0, 1]) => () => ([f0, f1] = [f1, f0 + f1])[0];

I just wanted to give a more up to date answer written using modern JavaScript.

Upvotes: 0

Greg
Greg

Reputation: 1931

I just wanted to post a little bit more up to date answer - the fibonacci closure is more readable written using modern JavaScript

function fibonacci() {
    let x = 0;
    let y = 1;
    let z = 0;
    return function getNext() {
        [z, x, y] = [x, y, x + y];
        return z;
    };
}

let fun = fibonacci();

for (let i = 0; i < 10; i++) {
    console.log(fun());
}

Upvotes: 7

Sarath
Sarath

Reputation: 9156

    var fibonacci = (function () {
        var arr = [0, 1];
        return function () {
            var num = arr[arr.length - 1],
                len = arr.length;
            arr.push(arr[len - 1] + arr[len - 2]);
            return num;
        };
    }());

    //test
    var i;
    for (i = 0; i < 10; i++) {
        console.log(fibonacci());
    }
   //1,1,2,3,5,8,13,21,34,55

See the description in http://sarathsaleem.github.com/JavaScriptTasks/

I did this as an answer to this question Write a function which will return you first two times 1, then 2, then 3, then 5 and so on (Fibonacci numbers). Don’t use any global variables.

Upvotes: 1

Platinum Azure
Platinum Azure

Reputation: 46193

The basic idea behind closures is that, since closers bind all local data by value, you can use them to initialize and then modify variables that are only local to that "instance" of the generated function.

Since this seems like homework, I'm going to answer a different question using closures: Use closures to get perfect squares (1, 4, 9, etc.), one at a time.

function makeSquareIteratorFunction() {
  var squareRoot = 1;

  var getNext = function() {
    // Calculate the number you need to return
    var square = squareRoot * squareRoot;

    // Apply side effects. In this case just incrementing the counter, but with
    // Fibonacci you will need to be a little more creative :-)
    // You might also prefer to do this first. Depends on your approach.
    squareRoot = squareRoot + 1;

    // Return the value
    return square;
  };

  // Return the function object, which can then be called later
  return getNext;
}

// Usage
var getNextSquare = makeSquareIteratorFunction();
alert(getNextSquare()); // 1
alert(getNextSquare()); // 4
alert(getNextSquare()); // 9

Now, it's worth pointing out that the local variables defined in the outer function (makeSquareIteratorFunction) are localized and bound to the closure. So if you call makeSquareIteratorFunction() multiple times, the later ones will be independent of the first one:

var getNextSquare1 = makeSquareIteratorFunction();
alert(getNextSquare1()); // 1
alert(getNextSquare1()); // 4
var getNextSquare2 = makeSquareIteratorFunction();
alert(getNextSquare2()); // 1 (!) because it's a new closure, initialized the same way
alert(getNextSquare1()); // 9 (!) because it was "on" 4 last time

Hopefully that helps explain it a little? If not, leave a comment. :-)

Upvotes: 10

Related Questions