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);
};
};
It does not only memoize the result of
fn, it also ensured that there is only one active call tofnat a time. Everycallbackthat is provided during an active call (whenactionis that anon function from line 5) is pushed on the stack, and oncefncalls back the stack (it’s a queue actually) is processed and the result is published to all callbacks.The confusing “
actionis set to eithercallFnor…” happens based on theerrcondition. This parameter indicates that an error happened and is falsy otherwise. So whenfncalls back with an error, the stack is processed as usual but also theactionis reset to the originalcallFn(you remember, it had that value at the beginning as well) so subsequent calls will retry to get a value fromfn. If there was no error, theactionis just set to a function that always calls back with the resultvalthat came back once.