Files
30-seconds-of-code/snippets/js/s/rearrange-function-arguments.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

655 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Rearrange function arguments snippet javascript
function
island-corridor 2020-10-22T20:24:04+03:00

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']