Fibonacci function

Fri, 18 Apr 2008

I have requests to publish answers to my JavaScript questions. And surprisingly most requested was Fibonacci function, so here we go. My vision of this function:

function fibonacci() {
    if (!("numbers" in arguments.callee)) {
        arguments.callee.numbers = [0, 1];
        return 0;
    }
    var len = arguments.callee.numbers.length;
    arguments.callee.numbers.push(arguments.callee.numbers[len - 1] +
        arguments.callee.numbers[len - 2]);
    return arguments.callee.numbers[len - 1];
}

The most important thing is to remember that function could be anonymous.