Skip to content

Instantly share code, notes, and snippets.

@danakt
Last active October 25, 2017 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danakt/edd8b1036095eea928b19ece4132cf2a to your computer and use it in GitHub Desktop.
Save danakt/edd8b1036095eea928b19ece4132cf2a to your computer and use it in GitHub Desktop.
Make number iterable
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