Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jamiebuilds/5ca3b8f52055556b6df135efd0b7f5df to your computer and use it in GitHub Desktop.
Save jamiebuilds/5ca3b8f52055556b6df135efd0b7f5df to your computer and use it in GitHub Desktop.
// Builds array of everything ahead of time
function collectAllItems() {
return [calculateFirst(), calculateSecond(), ...]
}
// This loop will end as soon as `isMatch(item)` is truthy.
// If the very first item in the array is a match, then we
// wasted all this time building the array in the first place.
for (let item of collectAllItems()) {
if (isMatch(item)) {
return true
}
}
// Creates iterator that lazily computes values as requested
function* iterateAllItems() {
yield calculateFirst()
yield calculateSecond()
// ...
}
// The loop will request each item as needed.
// If the very first item returned from the iterator is a match,
// then we don't waste any time calculating additional items.
for (let item of iterateAllItems()) {
if (isMatch(item)) {
return true
}
}
// **Nuance:** Building an array is very fast in most cases.
//
// These "generator functions" do have some overhead of their own,
// particularly if you still need to transpile them. Check out the
// browser support to see if you really need to be transpiling them.
//
// You won't need generators/iterators in most cases, but when you
// do, they can be a huge boost.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment