Skip to content

Instantly share code, notes, and snippets.

@kraftwerk28
Created February 25, 2019 23:02
Show Gist options
  • Save kraftwerk28/b75713f3996ac4bb31b09f4f496a9627 to your computer and use it in GitHub Desktop.
Save kraftwerk28/b75713f3996ac4bb31b09f4f496a9627 to your computer and use it in GitHub Desktop.
'use strict';
/**
* Binds function to positioned arguments
* posargs must be like { 2: one_arg, 100: another_arg, 0: another_arg }
* @param {Function} fn
* @param {Object} posargs
*/
const positionalBind = (fn, posargs) => (...args) => {
const indexes = Object.keys(posargs).map(_ => +_).sort();
const realArgs = [];
while (indexes.length) {
realArgs.push(
indexes[0] === realArgs.length
? posargs[indexes.shift()]
: args.shift());
}
return fn(...realArgs, ...args);
};
function fun(a, b, c, d, e) {
console.log(arguments);
};
const bnd = positionalBind(fun, { 1: 12, 3: 21, 0: 33 });
bnd(44, 55); // [33, 12, 44, 21, 55]
@a-kuharenko
Copy link

while (indexes.length) {
realArgs.push(
indexes[0] === realArgs.length
? posargs[indexes.shift()]
: args.shift());
}

Without "While() {}"

indexes.concat(args)
    .forEach((value, index) => {
      value = posargs[index];
      realArgs.push(
        !value ? args.shift() : value);
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment