Flip the first two arguments
Utility functions disagree about argument order — some take the collection first, some the callback. Rather than writing an adapter by hand every time, flip the one that does not fit.
Implement flip(fn). It returns a new function that forwards exactly as many arguments as it received, with the first two swapped, and returns fn's return value. If it receives fewer than two arguments, nothing is swapped and the arguments are forwarded unchanged — the wrapper never pads the call with undefined, so arguments.length inside fn always matches the number of arguments the wrapper was given.
Arguments
fnFunction- The function whose first two arguments should be swapped.
Returns
Function — A wrapper that calls fn with the first two arguments reversed and the rest in place.
Examples
const divide = (a, b) => a / b;
const divideFlipped = flip(divide);
divide(10, 2); // 5
divideFlipped(2, 10); // 5const triple = flip((a, b, c) => [a, b, c]);
triple(1, 2, 3); // [2, 1, 3] — only the first two swapFlipping twice is identity: flip(flip(fn)) behaves exactly like fn.
What it has to do
- Swap the first two arguments and forward the rest in their original order.
- Forward exactly as many arguments as the wrapper received, never padding with
undefined. - Leave a single-argument call untouched.
- Return
fn's return value unchanged.
Notes
- Collect with a rest parameter, swap indexes
0and1only whenargs.length > 1, then spread back — padding to a fixed arity would break thearguments.lengthtest. - Not the same as
_.flipin Lodash, which reverses *all* arguments. Read the spec before importing a lookalike.
Stuck? The javascript course covers everything this challenge needs.
- 1.swaps the first two arguments
- 2.keeps the remaining arguments in order
- 3.forwards the same number of arguments
- 4.flipping twice restores the original order
- 5.turns subtract into its mirror
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.