HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Change the order of arguments in a JavaScript function

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptchangeargumentsorderthefunction

Problem

While JavaScript's APIs have come a long way, they're often not as flexible as we'd like. Sometimes, you need to change the order of arguments in a function to fit your needs. This is also a fairly common problem when working with libraries or APIs that don't provide the exact signature you need. Luckily, rearranging function arguments is easy with a few lines of code.
A very common need is to make the first argument the last. This is particularly useful when currying a function or when you need to partially apply a function.
You can easily achieve this by using a higher-order function that takes a function as an argument and returns a new function that flips the arguments before calling the original function. In order to do so, you can use argument destructuring and a closure with variadic arguments.
> [!NOTE]
>

Solution

const flip = fn => (first, ...rest) => fn(...rest, first);

const parseInteger = flip(Number.parseInt);
parseInteger(8, '10'); // 8 (10 in base 8)

const parseIntegerBase16 = parseInteger.bind(null, 16);
parseIntegerBase16('10'); // 16 (10 in base 16)


You can easily achieve this by using a higher-order function that takes a function as an argument and returns a new function that flips the arguments before calling the original function. In order to do so, you can use argument destructuring and a closure with variadic arguments.
> [!NOTE]
>
> Number.parseInt() is a very clear example of how JavaScript's APIs might be ill-optimized for currying and functional programming. It takes the base as the second argument, which is not very convenient when partially applying the function. Flipping the arguments makes it easier to use in a curried context.
If you need yet more control over the order of a function's arguments, you can arrange them based on a specific order. This is particularly useful when you have a function with a large number of arguments and you want to make it more readable by rearranging them.
> [!TIP]

Code Snippets

const flip = fn => (first, ...rest) => fn(...rest, first);

const parseInteger = flip(Number.parseInt);
parseInteger(8, '10'); // 8 (10 in base 8)

const parseIntegerBase16 = parseInteger.bind(null, 16);
parseIntegerBase16('10'); // 16 (10 in base 16)
const rearg =
  (fn, indexes) =>
  (...args) =>
    fn(...indexes.map(i => args[i]));

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

Context

From 30-seconds-of-code: reorder-function-arguments

Revisions (0)

No revisions yet.