simple underscore.js projects, walk through, & tutorial



Fibonacci Sequence

function fibonacci(f){
    if (f < 2){
        return f;
    } else {
        return fibonacci(f-1) + fibonacci(f-2);
    }
// recursively defined, takes a lot of computing power

var outputTextOne = _.map(_.range(0, 20, 1), function(n){return ' ' + fibonacci(n);});
_.range feeds the function the starting values

Output:
Nada Yet


function fib(f){
    return f<2?f: fib(f-1) + fib(f-2);
} // as per above, only more succinctly

var outputTextTwo = _.map(_.range(0, 20, 1), function(n){return ' ' + fib(n);});

Output:
Nada Yet


var outputTextThree = fib(20) + ", " + fib(21) + ", " + fib(22);
And here, rather than feeding a range, individual Fibonacci numbers are selected.  The three in question being the next three in the sequence from where we left off.

Output:
Nada Yet




_.moreUnderscoreProjects

© Copyright 2013 Brett Paufler