Skip to content

Instantly share code, notes, and snippets.

@sminutoli
Forked from m3g4p0p/bind-once.js
Last active November 13, 2017 19:31
Show Gist options
  • Save sminutoli/83fd73721cfb40de392f7348e9e61412 to your computer and use it in GitHub Desktop.
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
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