I am feeling very stupid today. I keep looking at this code, trying to trace it, but I just cannot figure out:
- What it's actually meant to do
- How it works
As far as I can see, the very first time it's called it's the only time action
is the same as callFn
. 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 actually 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.
I hate getting lost in code, but this is a little beyond me. Anybody smarter than me able to "get it"?
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);
};
};