Skip to content

Instantly share code, notes, and snippets.

@jonaskuske
Last active September 28, 2020 21:20
Show Gist options
  • Save jonaskuske/1be8f0359400c57d8d28957be4a1ffbc to your computer and use it in GitHub Desktop.
Save jonaskuske/1be8f0359400c57d8d28957be4a1ffbc to your computer and use it in GitHub Desktop.
How to make Numbers iterable as quick as possible
// Shortest (96 chars):
Number.prototype[Symbol.iterator]=function(){let i=0;return{next:()=>({done:i>this,value:i++})}}
// Only return value if not done yet (112 chars):
Number.prototype[Symbol.iterator]=function(){let i=0;return{next:()=>({done:i>this,...!(i>this)&&{value:i++}})}}
// Readable:
Number.prototype[Symbol.iterator] = function() {
let i = 0;
const isDone = i > this;
const nextValue = i++;
const getNext = () => ({ value: nextValue, done: isDone });
return { next: getNext }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment