AniUI Academy

Flip the first two arguments

easyFunctions & Closures+150 XPPractice

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); // 5
const triple = flip((a, b, c) => [a, b, c]);

triple(1, 2, 3); // [2, 1, 3] — only the first two swap

Flipping 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 0 and 1 only when args.length > 1, then spread back — padding to a fixed arity would break the arguments.length test.
  • Not the same as _.flip in Lodash, which reverses *all* arguments. Read the spec before importing a lookalike.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.