How does this code work?
if (!(args in pad)) {
pad[args] = self.apply(obj, arguments);
}
args is array, but shouldn’t it be a string because it’s a key of JS object?
How would check work? array in object?
Full context here:
Function.prototype.memoize = function() {
var pad = {};
var self = this;
var obj = arguments.length > 0 ? arguments[i] : null;
var memoizedFn = function() {
// Copy the arguments object into an array: allows it to be used as
// a cache key.
var args = [];
for (var i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
// Evaluate the memoized function if it hasn't been evaluated with
// these arguments before.
if (!(args in pad)) {
pad[args] = self.apply(obj, arguments);
}
return pad[args];
}
memoizedFn.unmemoize = function() {
return self;
}
return memoizedFn;
}
args is converted to a string which for arrays means:
It is automatically converted to a string when used in
in:This happens because the
inoperator only accepts strings on the left side.When you use
pad[args], the same conversion happens again because object keys can only be strings. For example, when you are usingarray[1], what actually happens isarray["1"]because the number is converted to a string.