Created
June 29, 2020 16:42
-
-
Save jamiebuilds/5ca3b8f52055556b6df135efd0b7f5df to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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