TypeScript

range — Lazy Number Iterator

admin by @admin ADMIN
4d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A generator-based numeric range: `[start, end)` with an optional step. Lazy so it doesn't allocate a huge array up front; consume with for…of or Array.from.
TypeScript
Raw
export function* range(start: number, end?: number, step = 1): Generator<number> {
  const [from, to] = end === undefined ? [0, start] : [start, end];
  if (step === 0) throw new Error('step must be non-zero');
  if (step > 0) for (let i = from; i < to;  i += step) yield i;
  else          for (let i = from; i > to;  i += step) yield i;
}

Array.from(range(5));            // [0, 1, 2, 3, 4]
Array.from(range(2, 10, 2));     // [2, 4, 6, 8]
Array.from(range(10, 0, -2));    // [10, 8, 6, 4, 2]

for (const i of range(1_000_000)) { /* lazy — no array allocation */ }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.