So I came across a momoize function when I was trying to understand how memoization really works, the solution has really had me thinking, the code below
const memoize = (fn) => {
const cache = {};
return (...args) => {
let cacheKey = args.map(n => n.toString() + '+').join('');
if (cacheKey in cache) {
console.log(cache[cacheKey])
return cache[cacheKey];
}else {
let result = args.reduce((acc, curr) => fn(acc, curr), 0);
cache[cacheKey] = result;
console.log(result)
return result;
}
}
}
const add = (a, b) => a + b;
const memoizeAdd = memoize(add)
memoizeAdd(1, 2, 3, 4)
My question is how the momoize variable takes the add function as an argument and memoizeAdd also takes a wide range of argument, If add function only accepts 2 arguments? please, this question comes from a place of curiosity.