Skip to content

Instantly share code, notes, and snippets.

@gabefinch
Created April 11, 2020 18:05
Show Gist options
  • Save gabefinch/feb9cbe88c903959746d942aa070a0f7 to your computer and use it in GitHub Desktop.
Save gabefinch/feb9cbe88c903959746d942aa070a0f7 to your computer and use it in GitHub Desktop.
// from this excellent tutorial on decorators:
// https://javascript.info/call-apply-decorators
let worker = {
slow(min, max) {
alert(`Called with ${min},${max}`);
return min + max;
}
};
function cachingDecorator(func, hash) {
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);
alert( worker.slow(3, 5) ); // works
alert( "Again " + worker.slow(3, 5) ); // same (cached)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment