Last active
February 21, 2024 11:53
-
-
Save shawndumas/0c502179a73b4472d54f to your computer and use it in GitHub Desktop.
Generator as a Method
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
class Range { | |
constructor(start, stop=start) { | |
if (start === undefined && stop === undefined) { | |
throw 'usage: range(start, stop) or range(stop)'; | |
} | |
if (stop === start) { | |
start = 0; | |
} | |
if (stop < start) { | |
throw 'usage: range(start, stop)'; | |
} | |
this.start = start; | |
this.stop = stop; | |
} | |
*[Symbol.iterator]() { | |
for (let i = this.start; i <= this.stop; i += 1) { | |
yield i; | |
} | |
} | |
} | |
const oneToTen = new Range(1, 10); | |
for (let n of oneToTen) { | |
console.log(n); | |
} | |
/* | |
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment