Javascript 如何记忆函数以便从缓存返回相同的参数
我的功能很慢Javascript 如何记忆函数以便从缓存返回相同的参数,javascript,node.js,caching,Javascript,Node.js,Caching,我的功能很慢 function f(a, b, c) { } 我有时用相同的参数调用这个函数,它将返回相同的结果。 我想用参数缓存这个函数调用,所以使用相同参数的第二个调用将从缓存返回 我试过了,但没用 export function memoize(fn) { let cache; let res; return function(...args) { if (!cache) { cache = args; res = fn(...args);
function f(a, b, c) {
}
我有时用相同的参数调用这个函数,它将返回相同的结果。
我想用参数缓存这个函数调用,所以使用相同参数的第二个调用将从缓存返回
我试过了,但没用
export function memoize(fn) {
let cache;
let res;
return function(...args) {
if (!cache) {
cache = args;
res = fn(...args); return res;
}
if (objectCompare(args, cache)) {
return res; }
return res = fn(...args);
};
}
为了使用
缓存
,我们需要将参数映射到结果。因为您有多个参数,所以需要为这些参数生成一个唯一的键。例如,如果您有3个参数:a、b、c-您可以创建一个键:\
${a}-${b}-${c}``(这只是一个示例,唯一重要的是这个键是唯一的!)
演示(有关其他说明,请参见代码注释):
向我们展示调用此函数的代码。它到底是如何工作的?使用or对象,将参数序列化为JSON,将参数用作键,将输出用作值,然后查找键。您有没有看过这个问题:这对单参数@ninascholzy有效?您可以先使用curry函数,然后使用memory函数。您应该使用
if(cache.hasOwnProperty(key))
而不是if(缓存[键])
。您当前的代码从不记忆错误的值(false、undefined、null、0、“,等等)。
function f(a, b, c) {
return a + b + c; // for example
}
const memoized = (function(fn) { // we'll wrap the original function
const cache = {}; // init a cache
return (a, b, c) => {
const key = `${a}-${b}-${c}`; // create a key
if (cache.hasOwnProperty(key)) { // search if it's already saved in the cache
console.log('in memory');
return cache[key];
}
console.log('calculating...');
const res = fn.apply(this, [a, b, c]); // since it's not in the cash - calculate the result
cache[key] = res; // now before we'll return the result - save it in the cache for next calls
return res;
};
})(f); // apply the memoization to the original function
memoized(1, 2, 3); // will print "calculating..." and return the result
memoized(1, 2, 3); // will print "in memory" and return the result