Flip function arguments

OSCC · JavaScript, Function · Jun 13, 2021

Takes a function as an argument, then makes the first argument the last.

  • Use argument destructuring and a closure with variadic arguments.
  • Splice the first argument, using the spread operator (...), to make it the last before applying the rest.
const flip = fn => (first, ...rest) => fn(...rest, first);
let a = { name: 'John Smith' };
let b = {};
const mergeFrom = flip(Object.assign);
let mergePerson = mergeFrom.bind(null, a);
mergePerson(b); // == b
b = {};
Object.assign(b, a); // == b

Recommended snippets

  • Convert function from variadic

    JavaScript, Function

    Takes a variadic function and returns a function that accepts an array of arguments.

  • Juxtapose functions

    JavaScript, Function

    Takes several functions as argument and returns a function that is the juxtaposition of those functions.

  • Argument coalescing factory

    JavaScript, Function

    Customizes a coalesce function that returns the first argument which is true based on the given validator.