To create a Python-style range() array in JavaScript without mutating external inputs, write a helper function that accepts start, stop, and step (supporting range(stop) as well as range(start, stop, step)), validates finite numbers and non-zero step, checks direction (step > 0 for ascending start < stop, step < 0 for descending start > stop), and builds the sequence without floating-point drift. Unlike Python’s lazy range object, JavaScript returns a materialized Array of numbers.


1. Python-Style range() with Full Argument Signatures and Guards

Support both single-argument range(stop) (defaulting start = 0, step = 1) and two/three-argument range(start, stop, step), guarding against non-finite numbers, step === 0, or mismatched signs:

// Create a Python-style range array supporting range(stop), range(start, stop), and range(start, stop, step)
function pyRange(startOrStop, stopArg, stepArg = 1) {
  let start;
  let stop;
  let step;

  if (stopArg === undefined) {
    start = 0;
    stop = startOrStop;
    step = 1;
  } else {
    start = startOrStop;
    stop = stopArg;
    step = stepArg;
  }

  if (
    typeof start !== "number" ||
    typeof stop !== "number" ||
    typeof step !== "number" ||
    !Number.isFinite(start) ||
    !Number.isFinite(stop) ||
    !Number.isFinite(step)
  ) {
    throw new TypeError("start, stop, and step must be finite numbers.");
  }

  if (step === 0) {
    throw new RangeError("range() step argument must not be zero.");
  }

  if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
    return [];
  }

  const count = Math.max(0, Math.ceil((stop - start) / step));
  const result = new Array(count);

  for (let i = 0; i < count; i += 1) {
    result[i] = start + i * step;
  }

  return result;
}

// Example usage:
console.log(pyRange(5));           // [0, 1, 2, 3, 4]
console.log(pyRange(2, 7));        // [2, 3, 4, 5, 6]
console.log(pyRange(10, 0, -2));   // [10, 8, 6, 4, 2]
console.log(pyRange(5, 2));        // []
  • Exact Python semantics: stop is exclusive, range(stop) starts at 0, and negative step counts downward when start > stop.
  • Pre-sized array & non-mutating: Allocates a fresh Array(count) directly without mutating any caller values.

2. Avoiding Floating-Point Drift with Decimal Steps

When generating ranges with fractional steps (such as 0.1 or 0.25), repeated addition (current += step) accumulates binary floating-point rounding error (0.30000000000000004); rounding each computed element (start + i * step) keeps values clean:

// Build a range array with safe rounding for fractional steps
function pyRangeDecimal(start, stop, step = 1, decimals = 6) {
  if (
    typeof start !== "number" ||
    typeof stop !== "number" ||
    typeof step !== "number" ||
    !Number.isFinite(start) ||
    !Number.isFinite(stop) ||
    !Number.isFinite(step)
  ) {
    throw new TypeError("start, stop, and step must be finite numbers.");
  }

  if (step === 0 || (step > 0 && start >= stop) || (step < 0 && start <= stop)) {
    return [];
  }

  const factor = 10 ** Math.min(Math.max(Math.trunc(decimals), 0), 12);
  const count = Math.ceil((stop - start) / step);
  const output = [];

  for (let i = 0; i < count; i += 1) {
    const value = Math.round((start + i * step) * factor) / factor;
    if ((step > 0 && value < stop) || (step < 0 && value > stop)) {
      output.push(value);
    }
  }

  return output;
}

// Example usage:
console.log(pyRangeDecimal(0, 0.6, 0.2, 2)); // [0, 0.2, 0.4]
  • Prevents 0.30000000000000004 noise: Computes start + i * step and rounds cleanly to the requested decimal precision.
  • Strict boundary check: Ensures floating-point rounding never accidentally includes stop.

3. Common Traps to Avoid

Creating a Python-style range() helper in JavaScript often runs into a few pitfalls:

  • Passing step === 0 or a wrong sign (pyRange(1, 5, -1)): A zero step causes an infinite loop if unchecked, and a negative step when start < stop (or positive step when start > stop) should return [] just like Python’s range().
  • Using [...Array(n).keys()] on large values: While [...Array(5).keys()] is a quick shorthand for 0..n-1, it only starts at 0 with step 1 and materializes a full array in memory—avoid huge ranges in hot paths when a for loop or generator suffices.
  • Accumulating current += step with floats: Repeatedly adding fractional steps drifts over time; multiplying by i (start + i * step) keeps each step independent.

TL;DR: Implement a guarded pyRange(startOrStop, stopArg, stepArg = 1) function that rejects step === 0 and non-finite numbers, returns [] when start and stop oppose step, and computes start + i * step into a fresh array excluding stop.