I was attempting an algorithm with the following prompt:
Define a function
fastCache
that takes one argument, a function, and returns a function. WhenfastCache
is invoked it creates an object that tracks calls to the returned function, where each input to the returned function is associated with its output. Every subsequent call to that returned function with the same argument will return the output directly from the object, instead of invoking the original function again. WritefastCache
so it can handle array or object input, and any number of arguments.
Below is the solution to this with an object using JSON.stringify on the object keys to store objects as keys:
const fastCache = (func) => {
const cache = {};
return (...args) => {
if (cache.hasOwnProperty(JSON.stringify(args)))
return cache[JSON.stringify(args)];
cache[JSON.stringify(args)] = func(...args);
return cache[JSON.stringify(args)];
};
};
This solution makes sense to me since we are passing values as keys to the object and then returning that key's respective value. I attempted to write a solution to this problem using a JS Map and am unclear on why my solution below does not perform in the same way as the solution above:
const fastCache = (func) => {
const cache = new Map();
return (...args) => {
if (cache.has(args)) return cache.get(args);
cache.set(args, func(...args));
return cache.get(args);
};
};
This function ends up adding multiple keys to the Map with the same key when objects are passed in as keys on successive function calls for the same object being passed in as an argument. My understanding is that this is because objects are passed by reference as opposed to strings being passed by value, but given that, I am struggling to understand the benefits of a Map over an Object if a get/set does not match for different object references. Is a Map only used when we are passing in the same reference to an object vs an object for when we need to make checks on the same value? This seems counterintuitive to the purpose of a Map in JS. Any clarification on when a Map is preferred over an object and vice verse would be greatly appreciated. Thanks.