Lodash _.range with Negative Step Sequences

This article examines how the Lodash utility library computes mathematical sequences when supplied with negative step parameters in _.range. It defines the exact mathematical sequence produced—a finite decreasing arithmetic progression—details the underlying formula, illustrates typical implementations, and outlines the precise boundary constraints governing these outputs.

The Mathematical Sequence: Decreasing Arithmetic Progression

The exact mathematical sequence uniquely evaluated by _.range(start, end, step) with a negative step is a finite, strictly decreasing arithmetic progression (or arithmetic sequence) defined over a half-open interval.

In classical mathematics, an arithmetic sequence is governed by the recurrence relation:

\[a_n = a_{n-1} + d\]

Or in explicit form:

\[a_k = a_0 + k \cdot d\]

Where:

Lodash Boundary Evaluation

Lodash produces values strictly on the half-open interval \((\text{end}, \text{start}]\) when the step is negative. The sequence terminates before reaching or surpassing the end value. Formally, the generated set \(S\) is:

\[S = \{ \text{start} + k \cdot \text{step} \mid k \in \mathbb{N}_0 \text{ and } \text{start} + k \cdot \text{step} > \text{end} \}\]

The total number of terms \(N\) generated in the array is:

\[N = \max\left(0, \left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil\right)\]

Because both \((\text{end} - \text{start})\) and \(\text{step}\) are negative when \(\text{start} > \text{end}\) and \(\text{step} < 0\), the quotient is positive, resulting in a strictly positive integer term count.

Code Examples and Execution

Standard Decrement Sequence

When stepping down toward a negative or lower boundary:

const _ = require('lodash');

// Generates: [0, -1, -2, -3]
const seq1 = _.range(0, -4, -1);

// Generates: [20, 15, 10, 5]
const seq2 = _.range(20, 0, -5);

In seq2, the parameters correspond to:

Empty Progression Scenarios

If the direction of the step conflicts with the direction of the interval, Lodash returns an empty array []:

// start < end with a negative step yields an empty array
const emptySeq = _.range(0, 5, -1); // []

Here, \(\text{start} + (0 \cdot -1) = 0\), which is not greater than the specified end of \(5\) given the decrement vector, satisfying \(N = 0\).