Skip to content

unary

Creates a function that calls fn with only its first argument, discarding any others.

Prevents the classic footgun where a callback expecting extra positional arguments is passed directly to Array.prototype.map: ['1', '2', '3'].map(parseInt) silently passes the array index as parseInt’s radix argument, producing [1, NaN, NaN].

Available since v3.0.0

import { unary } from '@helpers4/function';
// or, from the all-in-one package (same code, one install):
import { unary } from 'helpers4/function';
unary<F extends function>(fn: F): function
ParameterTypeDescription
fnFThe function to restrict to one argument

function — A new function that calls fn with only its first argument

Array.prototype.map passes (value, index, array) — parseInt reads index as its radix argument.

['1', '2', '3'].map(parseInt)
// => [1, NaN, NaN]  (bug: index used as radix)

['1', '2', '3'].map(unary(parseInt))
// => [1, 2, 3]

Restrict any multi-argument function to one argument

Section titled “Restrict any multi-argument function to one argument”

Useful whenever a callback slot passes more arguments than the function should see.

const double = unary((n: number, factor?: number) => n * (factor ?? 2));
double(21)
// => 42

View source on GitHub