Memoize in JavaScript

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.)

Wow, that’s eerie… I was explaining memoization to a co-worker today and I used that exact example.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

Captcha
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
6 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
Syndicate content