Aller au contenu principal

flip()

flip<First, Second, Rest, Result>(fn): (b, a, ...rest) => Result

Creates a function with its first two arguments reversed.


Type Parameters

First: First

The first argument type.

Second: Second

The second argument type.

Rest: Rest extends unknown[]

The remaining argument types.

Result: Result

The return type.


Parameters

fn: (a, b, ...rest) => Result

The function to flip.


Returns

The flipped function.


Since

2.0.0


Also known as

flip (Lodash, es-toolkit, Remeda, Radashi, Ramda, Effect) · ❌ (Modern Dash, Antfu)


Example

const divide = (a: number, b: number) => a / b;
const divideBy = flip(divide);

divide(10, 2); // => 5
divideBy(2, 10); // => 5

How it works?

Creates a function with its first two arguments reversed.

Argument Swap


Use Cases

Create natural APIs 📌

Reverse function parameters to create more intuitive and readable function interfaces. Essential for API design and improving code readability.

const greet = (name, greeting) => `${greeting}, ${name}!`;
const greetReverse = flip(greet);

greetReverse("Hello", "World"); // "Hello, World!" (flipped)

Enable currying patterns

Reverse parameters to enable currying and partial application for functional programming. Critical for functional programming and creating reusable function components.

const map = (fn, array) => array.map(fn);
const mapFlipped = flip(map);

// Now data comes last, easier to curry or pipe
const doubleAll = (arr) => mapFlipped(arr, n => n * 2);