How does this memoize function work?
<p>I am feeling very stupid today.
I keep looking at this code, trying to trace it, but I just cannot figure out:</p>

<ol>
<li>What it's actually meant to do</li>
<li>How it works</li>
</ol>

<p>As far as I can see, the very first time it's called it's the only time <code>action</code> is the same as <code>callFn</code>. So, the very first time it's run, it creates the stack array. Then I lose it. Action is assigned a function that just adds the passed callback to the stack. Then fn is <em>actually</em> called and based on its result, "action" is set to either callFn (?!?) or to a function that calls the callback... And then, all the calls in the stack are called.</p>

<p>I hate getting lost in code, but this is a little beyond me. Anybody smarter than me able to "get it"?</p>

<pre><code>var memoize = function(fn) {
    var callFn = function(callback) {
        var stack = [callback];

        action = function(callback) {
            stack.push(callback);
        };

        fn(function(err, val) {
            action = err ? callFn : function(callback) {
                callback(null, val);
            };

            while (stack.length) stack.shift()(err, val);
        });
    };

    var action = callFn;

    return function(callback) {
        action(callback);
    };
};
</code></pre>
