How Lodash endsWith Handles Truncated Lengths
This article provides an in-depth technical overview of how the
Lodash utility library’s _.endsWith function processes
custom string boundaries. Specifically, it details the internal
normalization pipeline—from type casting and boundary clamping to index
offset calculation—that determines whether a target substring matches
when the reference length is constrained or truncated.
The _.endsWith
Implementation
Lodash defines _.endsWith to check whether a string
terminates with a specified target substring. The function accepts three
arguments: the source string, the target substring, and an optional
search position (position), which defaults to the string's
full length.
Under the hood, the matching logic operates as follows:
function endsWith(string, target, position) {
string = toString(string);
target = baseToString(target);
var length = string.length;
position = position === undefined
? length
: baseClamp(toInteger(position), 0, length);
var end = position;
position -= target.length;
return position >= 0 && string.slice(position, end) == target;
}Parameter Normalization and Clamping
When an evaluation boundary is derived from a truncated numerical value or an array length, Lodash executes a strict sanitization process before running any substring checks:
- Integer Coercion (
toInteger): If a truncated number or object (such as an array length calculation) is passed toposition, it is processed viatoInteger(). Non-integer floats are truncated toward zero, and values likeNaNdefault to0. - Range Clamping (
baseClamp): The calculated integer is constrained usingbaseClamp(position, 0, length). If the provided length is negative, it is normalized to0. If it exceeds the maximum string length, it is locked tostring.length.
Functional Offsetting Logic
Once the boundary (position) is clamped, Lodash offsets
the indices to isolate the segment being tested:
- Anchor Assignment: The variable
endis assigned to the clampedposition. This sets the rightmost boundary of the search window. - Leftward Offset: Lodash decrements
positionbytarget.length(position -= target.length), shifting the starting pointer backward to where the substring match must begin.
Behavior Under Heavy Truncation
When the supplied length is heavily truncated—meaning the value of
position is less than the length of target—the
subtraction position -= target.length produces a negative
value.
Lodash utilizes short-circuit evaluation with the condition
position >= 0. If the truncated boundary provides fewer
available characters than the target itself, the expression immediately
evaluates to false. This avoids redundant substring
extraction via string.slice(position, end) and prevents
out-of-bounds indexing. When the truncated boundary equals or exceeds
target.length, string.slice(position, end)
extracts the exact window and compares it directly to
target.