Skip to content

Instantly share code, notes, and snippets.

@siberex
Last active December 23, 2025 15:39
Show Gist options
  • Select an option

  • Save siberex/788f8fb718a1bf10be489fdb49d551e1 to your computer and use it in GitHub Desktop.

Select an option

Save siberex/788f8fb718a1bf10be489fdb49d551e1 to your computer and use it in GitHub Desktop.
Mimic Python range() for JS
// Mimic Python range:
// [...range(10)] → [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
// [...range(3, 6)] → [3, 4, 5]
// [...range(3, 20, 2)] → [3, 5, 7, 9, 11, 13, 15, 17, 19]
// for (const i of range(1, 6)) console.log(i);
function* range(from, upTo, step = 1) {
if (upTo == undefined) {
upTo = from;
from = 0;
}
while (from < upTo) {
yield from;
from += step;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment