30秒学会 JavaScript 片段 · 2023年9月6日

30秒学会 JavaScript 片段 – Rearrange function arguments

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]));

let rearged = rearg(
  function(a, b, c) {
    return [a, b, c];
  },
  [2, 0, 1]
);
rearged('b', 'c', 'a'); // ['a', 'b', 'c']

翻译自:https://www.30secondsofcode.org/js/s/rearrange-function-arguments