Last active
April 4, 2023 20:25
-
-
Save cowboyd/0bf62033b51c19e71674b8b786d6d80c to your computer and use it in GitHub Desktop.
"Early Return" using delimited continuations
This file contains 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
// could be really expensive if the enumerable is really long. | |
[...worlds].find(x => x.name === "Arcadia"); | |
// this will return early the moment that the predicate matches | |
function* find(enumerable, predicate) { | |
return yield* shift(function*(k) { | |
for (let item of enumerable) { | |
if (predicate(item) { | |
k(item); | |
break; | |
} | |
} | |
}); | |
} | |
// now completely safe | |
yield* find(worlds, x => x.name === "Arcadia"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment