Skip to content

Instantly share code, notes, and snippets.

@digitalconceptvisuals
Created July 29, 2020 23:18
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 digitalconceptvisuals/cc3c72aefb39cf831bcb50b9a050ce64 to your computer and use it in GitHub Desktop.
Save digitalconceptvisuals/cc3c72aefb39cf831bcb50b9a050ce64 to your computer and use it in GitHub Desktop.
// Memoize is a Proxy to the actual function
const memoize = (fn, mfu = 10) => new Proxy(fn,
// Handler with traps
{
cache: new MFUMap(mfu),
max: mfu, // Our cache limit
// Our "magic" property
get(object, property, receiver) {
if (property == "cache")
return this.cache;
return Reflect.get(object, property, receiver);
},
// Intercept call to the wrapped function
apply(target, thisArg, args) {
let result = this.cache.get(args.toString());
if (result)
return result;
result = Reflect.apply(target, thisArg, args);
this.cache.set(args.toString(), result);
return result;
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment