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