有没有办法从 Cache
类链接以下方法
cache = cache.getKey(key) ||缓存.setKey(键).get(键);
//cache = cache.getKey(key) ||缓存.setKey(键).getKey(键);
我知道我们有本地方法 Map.prototype .set()
和 Map.prototype .get()
但我想以这种方式实现它。如果您有任何建议,请告诉我。
function isObject(arg) {
const typeOfObj = typeof arg;
return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}
class Cache {
constructor() {
this.map = new Map();
this.weakmap = new WeakMap();
}
setKey(key) {
const map = this[isObject(key) ? 'weakmap' : 'map'];
return map.set(key, new Cache());
}
getKey(key) {
const map = this[isObject(key) ? 'weakmap' : 'map'];
return map.get(key);
}
}
function getCache(args, cache) {
for (const key of args) {
cache = cache.getKey(key) || cache.setKey(key).get(key);
// cache = cache.getKey(key) || cache.setKey(key).getKey(key);
}
return cache;
}
function memoize(fn) {
const cache = new Cache();
return (...args) => {
const item = getCache(args, cache);
if (Reflect.has(item, 'value')) {
return item.value;
}
return (item.value = fn(args));
};
}
let counter = 1;
function foo() {
counter += 1;
return counter;
}
const id1 = Symbol('id');
const id2 = Symbol('id');
const memoizedFoo = memoize(foo);
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(id2)); // 3
非常感谢任何帮助。
最佳答案
不幸的是,如果您试图“获取”一个 key ,您不能返回 map ,因为您正在请求 key ,所以它必须返回 key 。所以你不能链接那个方法。但是任何默认情况下不应该返回某些东西的方法(IE 将是无效的),我们可以这样做:
cache = cache.getKey(key) || cache.setKey(key).get(key);
这将返回一个 bool 值,因为 ||符号表示如果其中一个为真则返回真。
但是,如果您想进行 JQuery 所做的那种链接,那很容易实现!您要做的是返回 this
或每个方法中的对象。
像这样:
function isObject(arg) {
const typeOfObj = typeof arg;
return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}
class Cache {
constructor() {
this.map = new Map();
this.weakmap = new WeakMap();
}
setKey(key) {
const map = this[isObject(key) ? 'weakmap' : 'map'];
map.set(key, new Cache());
return this; // HERE'S THE IMPORTANT PART
}
}
let counter = 1;
function foo() {
counter += 1;
return counter;
}
const id1 = Symbol('id');
const id2 = Symbol('id');
const memoizedFoo = memoize(foo);
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id1)); // 2
console.log(memoizedFoo(id2)); // 3
console.log(memoizedFoo(id2)); // 3
关于javascript - 如何实现方法链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56397448/