Created
April 11, 2020 18:05
-
-
Save gabefinch/feb9cbe88c903959746d942aa070a0f7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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