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 */ }
Create a free account and build your private vault. Share publicly whenever you want.