Rearrange function arguments

JavaScript, Function · Oct 22, 2020

Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.

  • Use Array.prototype.map() to reorder arguments based on indexes.
  • Use the spread operator (...) to pass the transformed arguments to fn.
const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i]));
var rearged = rearg(
  function(a, b, c) {
    return [a, b, c];
  },
  [2, 0, 1]
);
rearged('b', 'c', 'a'); // ['a', 'b', 'c']

More like this

  • Transform function arguments

    Creates a function that invokes the provided function with its arguments transformed.

    JavaScript, Function · Oct 21, 2020

  • Invoke functions on arguments

    Creates a function that invokes each provided function with the arguments it receives and returns the results.

    JavaScript, Function · Oct 21, 2020

  • Prepend function arguments

    Creates a function that invokes fn with partials prepended to the arguments it receives.

    JavaScript, Function · Sep 15, 2020