Restrict a function to one argument
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 droppedThe 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 argumentWhat it has to do
- Pass only the first argument through to
fn, dropping any others. - Call
fnwith 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). Usingfn(...args.slice(0, 1))works too but is overkill. unaryis one of a family —nAry(fn, n)generalises it andbinary(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.
- 1.drops the extra arguments
- 2.fixes map(parseInt)
- 3.returns the wrapped function's value
- 4.always passes exactly one argument
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.