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:

  1. Integer Coercion (toInteger): If a truncated number or object (such as an array length calculation) is passed to position, it is processed via toInteger(). Non-integer floats are truncated toward zero, and values like NaN default to 0.
  2. Range Clamping (baseClamp): The calculated integer is constrained using baseClamp(position, 0, length). If the provided length is negative, it is normalized to 0. If it exceeds the maximum string length, it is locked to string.length.

Functional Offsetting Logic

Once the boundary (position) is clamped, Lodash offsets the indices to isolate the segment being tested:

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.