Last active
October 25, 2017 14:28
-
-
Save danakt/edd8b1036095eea928b19ece4132cf2a to your computer and use it in GitHub Desktop.
Make number iterable
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
Number.prototype[Symbol.iterator] = function* () { | |
if (isNaN(this) || !isFinite(this)) { | |
throw new ReferenceError('Non-iterable number') | |
} | |
const abs = Math.abs(this) | |
const isNegative = this < 0 | |
for (let i = 0; i < abs; i++) { | |
yield isNegative ? -i : i | |
} | |
} | |
[...10] // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
for (let i of 5) { | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment