Skip to main content

unary()

unary<Result>(func): (arg) => Result

Creates a function that accepts up to one argument, ignoring any additional arguments.

๐Ÿ’Ž Why is this a Hidden Gem?

Restrict a function to its first argument โ€” the classic fix for ['1','2','3'].map(parseInt).

DEPRECATED

Use an inline arrow function instead.


Type Parametersโ€‹

Result: Resultโ€‹

The return type of the function.


Parametersโ€‹

func: (arg) => Resultโ€‹

The function to cap arguments for.


Returnsโ€‹

The new capped function.


See Alsoโ€‹

Arrow functions - MDN


Sinceโ€‹

2.0.0


Also known asโ€‹

unary (Lodash, es-toolkit, Ramda) ยท โŒ (Remeda, Radashi, Effect, Modern Dash, Antfu)


Exampleโ€‹

// โŒ Deprecated approach
['6', '8', '10'].map(unary(parseInt));
// => [6, 8, 10]

// โœ… Recommended approach
['6', '8', '10'].map(x => parseInt(x, 10));
// => [6, 8, 10]

How it works?โ€‹

Creates a function that accepts up to one argument. Deprecated: Use an arrow function.

Native Equivalentโ€‹

// โŒ arr.map(unary(parseInt))
// โœ… arr.map(x => parseInt(x))

Use Casesโ€‹

Limit to one argument ๐Ÿ“Œโ€‹

Create function that only accepts one argument.

const toInt = s => parseInt(s, 10);
["1", "2", "3"].map(toInt);
// => [1, 2, 3]

Fix map callbackโ€‹

Prevent extra arguments from affecting result.

// Problem: parseInt gets index as radix
["1", "2", "3"].map(parseInt); // => [1, NaN, NaN]

// Solution: wrap to use only first arg
["1", "2", "3"].map(s => parseInt(s, 10)); // => [1, 2, 3]

Ignore extra argumentsโ€‹

Adapter to ignore additional parameters.

const first = (a) => a;
[1, 2, 3].map(first); // Only uses value, ignores index