Created
September 15, 2024 23:14
-
-
Save alaindet/b1ddf7b216f487dead7c415bcf97d8cf to your computer and use it in GitHub Desktop.
Python's `range` in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is a generator function | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator | |
function* range(minOrMax: number, max?: number) { | |
const maxExists = max !== undefined; | |
const inf = maxExists ? minOrMax : 0; | |
const sup = maxExists ? max : minOrMax; | |
for (let i = inf; i < sup; i++) { | |
yield i; | |
} | |
} | |
for (const i of range(10)) { | |
console.log(i); | |
} | |
// Prints: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 | |
for (const j of range(10, 20)) { | |
console.log(j); | |
} | |
// Prints: 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment