Skip to content

Instantly share code, notes, and snippets.

@rauschma
Created February 20, 2019 14:36
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 rauschma/72e1d51d1a2d948aa1bd6681c7c9f4ae to your computer and use it in GitHub Desktop.
Save rauschma/72e1d51d1a2d948aa1bd6681c7c9f4ae to your computer and use it in GitHub Desktop.
const cache = new WeakMap();
const extract = (receiver, method) => {
let cacheEntry = cache.get(receiver);
if (!cacheEntry) {
cacheEntry = new Map();
cache.set(receiver, cacheEntry);
}
let boundMethod = cacheEntry.get(method);
if (!boundMethod) {
boundMethod = method.bind(receiver);
cacheEntry.set(method, boundMethod);
}
return boundMethod;
};
// ==================================
class Person {
constructor(name) {
this.name = name;
}
describe() {
return 'Person named ' + this.name;
}
}
const jane = new Person('Jane');
const func = extract(jane, jane.describe);
assert.equal(func(), 'Person named Jane');
// Extract again: same value
assert.equal(extract(jane, jane.describe), func);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment