Skip to content

Instantly share code, notes, and snippets.

@kepta

kepta/block5.js Secret

Created April 11, 2018 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kepta/d29efe26b9468a0f7620c2bc8dde781c to your computer and use it in GitHub Desktop.
Save kepta/d29efe26b9468a0f7620c2bc8dde781c to your computer and use it in GitHub Desktop.
function weakCache(fn) {
var cache = new WeakMap(); // <-- Behold the Weak!
return (arg) => {
if (cache.has(arg)) {
return cache.get(arg);
}
var computed = fn(arg);
cache.set(arg, computed);
return computed;
}
}
cachedCalcArea = weakCache(calcArea);
cachedCalcArea(USSR); // cache miss
cachedCalcArea(USSR); // cache hit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment