here is a simple worker object and a caching decorator that add caching behaves to the object method(worker.slow) and hash used to make key for cache Map in cachingDecorator(func, hash).
let worker = {
slow(min, max) {
alert(`Called with ${min},${max}`);
return min + max;
}
};
function cachingDecorator(func, hash) { //here
let cache = new Map();
return function() {
let key = hash(arguments); // (*)
if (cache.has(key)) {
return cache.get(key);
}
let result = func.call(this, ...arguments);
cache.set(key, result);
return result;
};
}
function hash(args) {
return args[0] + ',' + args[1];
}
worker.slow = cachingDecorator(worker.slow, hash); / *
here why did we passed hash without useing it dirctly ? */
alert( worker.slow(3, 5) );
alert( "Again " + worker.slow(3, 5) );
i used it from outside like this and no different.
so i don't understand what is the different between these two codes if anyone can
explain it or give me a reference to understand.. thx in advanced.
let worker = {
slow(min, max) {
alert(`Called with ${min},${max}`);
return min + max;
}
};
function hash(args) {
return args[0] + ',' + args[1];
}
function cachingDecorator(func) { // here
let cache = new Map();
return function() {
let key = hash(arguments); // (*)
if (cache.has(key)) {
return cache.get(key);
}
let result = func.call(this, ...arguments);
cache.set(key, result);
return result;
};
}
worker.slow = cachingDecorator(worker.slow); // here
alert( worker.slow(3, 5) );
alert( "Again " + worker.slow(3, 5) );