Numeric Range Generator With Step Validation

Build inclusive numeric ranges with positive or negative steps, validate inputs and stream large ranges lazily through a generator.

JavascriptData Integrity

Code

javascriptsnippet
29 lines
function assertNumber(name, value) {
  if (!Number.isFinite(value)) throw new TypeError(name + " must be a finite number");
}

export function range(start, end, step = 1) {
  assertNumber("start", start);
  assertNumber("end", end);
  assertNumber("step", step);
  if (step === 0) throw new RangeError("step must not be zero");
  const result = [];
  if (step > 0) {
    for (let value = start; value <= end; value += step) result.push(value);
  } else {
    for (let value = start; value >= end; value += step) result.push(value);
  }
  return result;
}

export function* rangeIter(start, end, step = 1) {
  assertNumber("start", start);
  assertNumber("end", end);
  assertNumber("step", step);
  if (step === 0) throw new RangeError("step must not be zero");
  if (step > 0) {
    for (let value = start; value <= end; value += step) yield value;
  } else {
    for (let value = start; value >= end; value += step) yield value;
  }
}

How it works

Count the functions assertNumber and range as the entire surface area of Numeric Range Generator With Step Validation.

The structure is a loop within a loop: for (let value = start; value <= end; value += step) result.push(value); outside, for (let value = start; value >= end; value += step) result.push(value); inside. The failure path is explicit — TypeError and RangeError is raised when the guard condition holds.

What to watch for

  • The guard step === 0 short-circuits the flow with an early throw when its condition holds.

Using it

The main signature reads export function range(start, end, step = 1)

The surface worth importing is range; the helpers around it are private to the snippet.

Key statements

for (let value = start; value <= end; value += step) yield value;
for (let value = start; value >= end; value += step) yield value;
if (!Number.isFinite(value)) throw new TypeError(name + " must be a finite number");

Interactive Tools for This Topic

FAQ

What happens on invalid input?
The code throws `TypeError` and `RangeError` — the guard `step === 0` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `assertNumber`, `range` at load time.