Reputation: 11
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.
Upvotes: 0
Views: 821
Reputation: 476
Two things are there.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).
When you created and assigned memoizeAdd, closure creates its scope for add function. and returns another function that takes many(...args) arguments.
now you called that returned method(memoizeAdd) with arguments.
the variable chache
will be available for this add
method scope.
Now if you creates another memoize
const mul = (a, b) => a + b;
const memoizeMul = memoize(add)
memoizeMul(1, 2, 3, 4)
Now it creates another scope and keep cache separate from the add
version.
Upvotes: 0
Reputation: 1010
add
is passed as the argument to the memoize
function. If you look closely, you will notice that fn
(which is referring to add
) is always called with two arguments only.
This is because the memoize
function calls the fn
argument along with reduce
(which is meant to process an array, even without a defined length).
Effectively, applying reduce
with a function that just adds two parameters will return the sum of all the elements, which is the expected result of memoizeAdd
.
I think checking how reduce works might help you
Upvotes: 1