Quantcast
Channel: hyperstruct » JavaScript
Viewing all articles
Browse latest Browse all 10

Memoize in JavaScript

$
0
0

In JavaScript, functions are objects. No big deal, until you expand that to functions can have state, and realize that things like this become possible:


function fact(n) {
    var memo = arguments.callee.memo;
    if(!(n in memo))
        if(n == 0)
            memo[n] = 1;
        else
            memo[n] = n * fact(n - 1);

    return memo[n];
}
fact.memo = {};

(arguments.callee is how you reference a function from within the function itself.)


Viewing all articles
Browse latest Browse all 10

Trending Articles