Skip to content

Instantly share code, notes, and snippets.

@joelburton
Created May 4, 2020 23:56
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 joelburton/35ec131d85615df19f62ed808fe77061 to your computer and use it in GitHub Desktop.
Save joelburton/35ec131d85615df19f62ed808fe77061 to your computer and use it in GitHub Desktop.
// makes a "lazy array" of all even numbers 2...infinity
function * evens(n = 0) { // "Generator function"
while (true) {
n += 2
yield n;
}
}
let allEvens = evens() // allEvens is a "generator"
// manually get a few
console.log(allEvens.next())
console.log(allEvens.next())
// loop until some random thing cuts us off... but laZily!
for (num of allEvens) {
console.log(num);
if (Math.random() < 0.05) break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment