I’m learning different implementations of the memoize function, and something is confusing me. Here is one version of the code:
_.memoize = function(func) {
let cache = {};
return function() {
let arg = JSON.stringify(arguments); //arg is an stringified array
if(!(arg in cache)) {
cache[arg] = func.apply(this, arguments);
}
return cache[arg];
};
};
My understanding of cahce[arg]
is that the cache
object has a key of arg
, or if it doesn’t, the function call of func.apply(this, arguments)
becomes the property at an arg
key. If arg
is already a key in cache
, than the function returns the property at cache[arg]
.
Ok, but isn’t arg
an array with a string in it? Assigned to a stringified version of arguments
? Or is it a super long, single string formed by JSON.stringify
?
How are the different arguments accessed? To me, this seems like the cache
has a single key of either an array or a long string. Which means the identity of the individual arguments would be lost in a single piece of data, and I don’t see how they are being accessed. I guess I would assume a for loop or forEach would loop through to access each argument, but that’s not happening, so I don’t really know how to read this.