Lodash flip Method Explained
The _.flip method in the Lodash JavaScript library
creates a wrapper function that invokes the provided function with its
arguments reversed. This article explains how _.flip alters
argument sequencing, demonstrates its behavior through practical code
examples, and details the scenarios where it is most effectively used in
functional programming.
What _.flip Does to Argument Order
When you pass a function to Lodash's _.flip(func), it
returns a new function. When this new function is called, it takes all
supplied arguments and reverses their positional order before handing
them to the original underlying function.
If an original function accepts arguments in the order of
(a, b, c, d), calling its flipped version with those same
values results in the original function receiving them as
(d, c, b, a).
Code Example
const _ = require('lodash');
function listArguments(first, second, third) {
return [first, second, third];
}
// Normal invocation
listArguments('first', 'second', 'third');
// => ['first', 'second', 'third']
// Create a flipped version of listArguments
const flippedList = _.flip(listArguments);
// Flipped invocation
flippedList('first', 'second', 'third');
// => ['third', 'second', 'first']How It Works with Variable Arguments
The _.flip method is not restricted to fixed-arity
functions. It captures all arguments provided at call time, applies an
array reversal operation to them, and spreads them into the target
function invocation.
const gatherAll = (...args) => args;
const flippedGather = _.flip(gatherAll);
flippedGather(1, 2, 3, 4, 5);
// => [5, 4, 3, 2, 1]Common Use Cases
- Adapting Third-Party Callbacks: Some libraries
supply callback arguments in an order incompatible with utility
functions you already have. Instead of writing an anonymous arrow
function to rearrange them,
_.flipoffers a clean point-free way to invert the order. - Higher-Order Function Composition: In functional
programming pipelines, currying often operates on arguments from left to
right. Flipping arguments allows you to change which argument is applied
first when combining
_.curryand_.flip.
Key Characteristics
- Non-destructive: It does not mutate or alter the original function; it returns a new, wrapped function.
- Preserves
thisBinding: The returned function retains the execution context (this) when it is invoked.