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โ
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