-
-
Save sminutoli/83fd73721cfb40de392f7348e9e61412 to your computer and use it in GitHub Desktop.
Bind functions to instances in a way that maintains strict equality when done multiple times
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 bindings = new WeakMap() | |
const getFns = context => { | |
if (!bindings.has(context)) { | |
bindings.set(context, {}) | |
} | |
return bindings.get(context) | |
} | |
const bindOnce = (fn, context, ...args) => { | |
const fns = getFns(context) | |
const key = fn.toString() | |
if (!fns[key]) { | |
fns[key] = []; | |
} | |
const sameArg = (arg, index) => arg == args[index]; | |
const withArgs = fns[key].find(fnInfo => fnInfo.args && fnInfo.args.every(sameArg)); | |
return withArgs ? withArgs.fn : fns[key].push({ | |
fn: fn.bind(context, ...args), | |
args | |
}).fn; | |
} | |
export default bindOnce |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment