I am trying to solve the following problem: (Not a homework question, just interview practice).
Create a function "fastCache" that takes one argument (a function) and returns a function. When fastCache 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.
I was able to solve this when the input is just one argument. But for the following example, I have no idea how to go about it: L
// // MULTIPLE ARGUMENTS CASE
const sumMultiplyBy2 = (num1, num2) => 2 * (num1 + num2);
const cachedSumMultiplyBy2 = fastCacheMult(sumMultiplyBy2);
console.log(cachedSumMultiplyBy2(5, 10)); // -> 30
console.log(cachedSumMultiplyBy2(1, 2)); // -> 6
console.log(cachedSumMultiplyBy2(5, 10)); // -> 30 // from the cache object
// */
This is the code I wrote for the single argument case:
const fastCache = (callback) => {
const obj = {};
return (input) => {
if (input in obj) {
console.log("from cache");
console.log(obj);
return obj[input];
}
else {
obj[input] = callback(input);
return callback(input);
}
}
}
iplyBy2 = num => num * 2;
const cachedMultiplyBy2 = fastCache(multiplyBy2);
console.log(cachedMultiplyBy2(100)); // -> 200
console.log(cachedMultiplyBy2(150)); // -> 300
console.log(
I guess this is what you are looking for:
function add(...numbers) {
return numbers.reduce((accumulator, current) => {
return accumulator += current;
});
};
function sumMultiplyBy2(numbers){
return add(numbers) * 2
}
sumMultiplyBy2(200) //400
sumMultiplyBy2(100,50) //300
So I tried joining the arguments as suggested in the comments and got a working code:
const fastCacheMult = (callback) => {
const obj = {};
return (...inputs) => {
if (inputs.join('') in obj) {
console.log("from cache");
return obj[inputs.join('')];
}
obj[inputs.join('')] = callback(...inputs);
return callback(...inputs);
}
}
const sumMultiplyBy2 = (num1, num2) => 2 * (num1 + num2);
const cachedSumMultiplyBy2 = fastCacheMult(sumMultiplyBy2);
console.log(cachedSumMultiplyBy2(5, 10)); //30
console.log(cachedSumMultiplyBy2(1, 2)); //6
console.log(cachedSumMultiplyBy2(5, 10)); //30
However, I also found that I can just use the rest parameter and it works for both single and multiple arguments:
function fastCacheMult(callback) {
let obj = {};
return function (...inputs) {
if (obj[inputs]) {
console.log("from cache");
return obj[inputs];
}
obj[inputs] = callback(...inputs);
return obj[inputs];
}
}
const sumMultiplyBy2 = (num1, num2) => 2 * (num1 + num2);
const cachedSumMultiplyBy2 = fastCacheMult(sumMultiplyBy2);
console.log(cachedSumMultiplyBy2(5, 10)); // -> 30
console.log(cachedSumMultiplyBy2(1, 2)); // -> 6
console.log(cachedSumMultiplyBy2(5, 10)); // -> 30 // from the cache object