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