Safe Integer Array Parsing with Lodash _.unary
Parsing integer arrays dynamically in JavaScript often introduces
subtle bugs when pairing standard iteration methods with functions like
parseInt. Lodash's _.unary utility solves this
problem by strictly capping the arity of an invoked function to a single
argument. By preventing secondary parameters—such as array indices—from
inadvertently being passed as the numerical radix, _.unary
ensures predictable and safe integer parsing across dynamic data
sets.
The fundamental hazard of parsing string arrays to integers stems
from how JavaScript's native iteration methods interact with
multi-argument functions. When using
Array.prototype.map(parseInt) or dynamic pipeline
transformations, the iteration callback typically supplies three
arguments: the current value, the index of the element, and the full
array. Because parseInt accepts two parameters—the string
to parse and the mathematical radix (base)—the array index is passed as
the radix parameter.
This mismatch causes unexpected outputs:
['10', '10', '10', '10'].map(parseInt);
// Output: [10, NaN, 2, 3]In this scenario, index 0 defaults to base 10, index
1 evaluates radix 1 (which is invalid,
producing NaN), index 2 evaluates
'10' in binary (producing 2), and index
3 evaluates '10' in ternary (producing
3).
Lodash’s _.unary utility eliminates this safety
vulnerability by wrapping a target function and ensuring it ignores all
arguments beyond the first. It returns a function that accepts exactly
one argument:
const _ = require('lodash');
const safeParseInt = _.unary(parseInt);
['10', '10', '10', '10'].map(safeParseInt);
// Output: [10, 10, 10, 10]Under the hood, _.unary(fn) acts as an arity adapter
equivalent to:
function unary(fn) {
return function(value) {
return fn(value);
};
}In dynamic environments where array contents and transformation
pipelines are composed at runtime, relying on developers to manually
write closures like (val) => parseInt(val, 10) can lead
to oversights and repetitive code. Using _.unary(parseInt)
enforces functional safety declaratively, preventing runtime radix
corruption while maintaining a clean, point-free programming style.