Created
February 20, 2019 14:36
-
-
Save rauschma/72e1d51d1a2d948aa1bd6681c7c9f4ae 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
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