AniUI Academy

Restrict a function to one argument

easyFunctions & Closures+150 XPPractice

Array.prototype.map calls its callback with the element, the index and the whole array. Most of the time the extra two are harmless, but hand it a function that accepts a second parameter — parseInt(string, radix) is the famous one — and you get nonsense: parseInt("7", 1) is NaN and parseInt("11", 2) is 3.

Implement unary(fn). It returns a new function that calls fn with exactly one argument, whatever else it was given: the wrapper's first argument. If the wrapper is called with no arguments it still calls fn with exactly one argument, whose value is undefined, so arguments.length inside fn is always 1. Return whatever fn returns.

Arguments

fnFunction
The function whose argument list should be clamped to one.

Returns

Function — A wrapper that forwards exactly one argument to fn and returns fn's result.

Examples

["1", "7", "11"].map(parseInt);
// [1, NaN, 3] — map passes (value, index, array), so parseInt sees a radix

["1", "7", "11"].map(unary(parseInt));
// [1, 7, 11] — the extra two arguments are dropped

The canonical use case. parseInt(string, radix) was never meant to be fed an index.

const log = unary((...args) => args.length);
log(1, 2, 3); // 1 — fn always sees exactly one argument

What it has to do

  • Pass only the first argument through to fn, dropping any others.
  • Call fn with exactly one argument every time, even when the wrapper receives none.
  • Return fn's return value unchanged.

Notes

  • The simplest implementation names a single parameter and forwards it: (first) => fn(first). Using fn(...args.slice(0, 1)) works too but is overkill.
  • unary is one of a family — nAry(fn, n) generalises it and binary(fn) is the two-argument version. All three solve the same "callback receives too many arguments" problem.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
4 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.