我正努力解决一个大前端的问题,链接。任务是实现一个通用的回忆录功能。我偶然发现了这个解决方案,但是我很难理解解析器是/做什么。我第一次遇到这个词,搜索谷歌是没有帮助的。
function memo(func, resolver = (...args) => args.join('_')) {
const cache = new Map();
return function(...args) {
const cacheKey = resolver(...args);
if (cache.has(cacheKey)) {
return cache.get(cacheKey);
}
const value = func.apply(this, args);
cache.set(cacheKey, value);
return value;
}
}发布于 2021-09-24 05:47:29
假设你有一个函数需要一些参数.
var underlyingFunction = function(arg1, arg2, arg3){
return arg1+arg2+arg3;
};您希望创建此函数的一个版本,它缓存传入的特定值的返回值,这样它就可以跳过计算,只返回上次传入相同的arg时返回的值。
而且真的..。与其编写这一个函数来进行具体操作,不如创建一个可以从任何底层函数创建这样一个缓存函数的函数.
要做到这一点,您需要一个函数:
重新编写示例代码,以便更全面地解释它。
const underlyingFunction = function(arg1, arg2, arg3) {
return arg1 + arg2 + arg3;
};
const serializingFunction = function(...args) {
/*
creates a '_' delimited string to use as unique id
for that particular function call
*/
return args.join('_');
};
var cachingFunctionCreator = function(func, serializer) {
// if serializer wasnt passed in, have it be serializingFunction
serializer = serializer || serializingFunction;
// to store all function call ids and their result values
const cache = new Map();
// return the new function
return function(...args) {
// call serializing function to get the function call id
const cacheKey = serializer(...args);
// check to see if we've seen this id before
// if so, dont call the underlying function...
// just return the previously stored result for that id
if (cache.has(cacheKey)) {
console.log(cacheKey + ' was passed in previously');
return cache.get(cacheKey);
}
// otherwise, call the underlying function with the current args
// store the id and result value into the map
// and return the current result
console.log('first time seeing: ' + cacheKey);
const value = func.apply(this, args);
cache.set(cacheKey, value);
return value;
};
};
var cachingFunction = cachingFunctionCreator(underlyingFunction);
console.log('Calling underlying function');
console.log(underlyingFunction('a', 'b', 'c'));
console.log('Calling cached function');
console.log(cachingFunction('a', 'b', 'c'));
console.log('Calling cached function');
console.log(cachingFunction('d', 'e', 'f'));
console.log('Calling cached function');
console.log(cachingFunction('g', 'h', 'i'));
console.log('Calling cached function');
console.log(cachingFunction('a', 'b', 'c'));
发布于 2021-09-24 05:06:52
它不是“解析器”,而是更像“参数有她”--一个返回给定一组参数的唯一散列的函数。
这里的想法是缓存使用给定参数集调用回忆录函数的结果,方法是使用“参数散列”作为键将结果存储在映射中。
(它可能被称为“解析器”,因为它允许回忆器解析缓存条目。)
(代码片段中的默认“解析器”天真地将参数值与"_"分隔符连接起来。这很天真,因为它没有考虑到参数本身可能包含"_"的情况。)
https://stackoverflow.com/questions/69309752
复制相似问题