Created
December 6, 2018 06:58
-
-
Save desnor/314210bcdd63a4e60a77e656e7bf3238 to your computer and use it in GitHub Desktop.
Giving the JavaScript number a range method
This file contains hidden or 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
// Give the humble javascript number the ability to generate an (ascending) range, like in ruby | |
Object.defineProperty(Number.prototype, '..', { | |
value: function *getDots(n) { | |
let i = this | |
while(i <= n) { | |
yield i++ | |
} | |
} | |
}) | |
const range = 1['..'](10) | |
// range.next() => { value: 1, done: false } | |
// The best part is you can then do this: | |
const infiniteRange = 1['..'](Infinity) | |
/* infiniteRange.next() => { value: 1, done: false } | |
infiniteRange.next() => { value: 2, done: false } | |
infiniteRange.next() => { value: 3, done: false } | |
... | |
towards infinity! | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment