JavaScript中的回忆功能
因此,当我试图了解纪念的真正起作用时,我遇到了一个Momoize功能,解决方案确实让我思考下面的代码
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)
我的问题是,如果添加函数仅接受2个参数,则MOMOIZE变量如何将添加函数作为参数作为参数,而Memoizeadd也需要广泛的参数?拜托,这个问题来自一个好奇的地方。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
add
作为参数传递给remoize
函数。如果仔细观察,您会注意到fn
(指的是add
)始终仅使用两个参数调用。这是因为
Memoize
函数与fn
参数一起调用redaim
(即使没有定义的长度,也旨在处理数组)。有效地,使用只需添加两个参数的函数应用
REDAL
将返回所有元素的总和,这是memoizeadd
的预期结果。我认为检查如何减少工作 可能会帮助您
add
is passed as the argument to thememoize
function. If you look closely, you will notice thatfn
(which is referring toadd
) is always called with two arguments only.This is because the
memoize
function calls thefn
argument along withreduce
(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 ofmemoizeAdd
.I think checking how reduce works might help you
有两件事。
当您创建和分配Memoizeadd时,CLOSURE会为添加功能创建其范围。并返回另一个获得许多(... args)参数的函数。
现在,您将该返回的方法(memoizeadd)带有参数。
变量
chache
将用于此add
方法范围。现在,如果您现在创建另一个记忆,
它将创建另一个范围,并将高速缓存与
add
版本分开。Two things are there.
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 thisadd
method scope.Now if you creates another memoize
Now it creates another scope and keep cache separate from the
add
version.