diff options
author | (quasar) nebula <qznebula@protonmail.com> | 2022-09-15 15:20:17 -0300 |
---|---|---|
committer | (quasar) nebula <qznebula@protonmail.com> | 2022-09-15 15:20:17 -0300 |
commit | 28b1a728f429c4c04ee3a16584f8433a1d312c7c (patch) | |
tree | eba35a248bcba03e221faa3634eb59c3735eb685 /src/util/sugar.js | |
parent | 2a575201526063d48c1292ae6bb66d55fbe808c9 (diff) |
update some misc-templates and refactor things
Diffstat (limited to 'src/util/sugar.js')
-rw-r--r-- | src/util/sugar.js | 16 |
1 files changed, 15 insertions, 1 deletions
diff --git a/src/util/sugar.js b/src/util/sugar.js index 754f1991..8b59deef 100644 --- a/src/util/sugar.js +++ b/src/util/sugar.js @@ -107,12 +107,26 @@ export function escapeRegex(string) { return string.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); } +// Binds default values for arguments in a {key: value} type function argument +// (typically the second argument, but may be overridden by providing a +// [bindOpts.bindIndex] argument). Typically useful for preparing a function for +// reuse within one or multiple other contexts, which may not be aware of +// required or relevant values provided in the initial context. +// +// This function also passes the identity of `this` through (the returned value +// is not an arrow function), though note it's not a true bound function either +// (since Function.prototype.bind only supports positional arguments, not +// "options" specified via key/value). +// export function bindOpts(fn, bind) { const bindIndex = bind[bindOpts.bindIndex] ?? 1; const bound = function (...args) { const opts = args[bindIndex] ?? {}; - return fn(...args.slice(0, bindIndex), {...bind, ...opts}); + return Reflect.apply(fn, this, [ + ...args.slice(0, bindIndex), + {...bind, ...opts} + ]); }; Object.defineProperty(bound, 'name', { |