// 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