Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Last active April 4, 2023 20:25
Show Gist options
  • Save cowboyd/0bf62033b51c19e71674b8b786d6d80c to your computer and use it in GitHub Desktop.
Save cowboyd/0bf62033b51c19e71674b8b786d6d80c to your computer and use it in GitHub Desktop.
"Early Return" using delimited continuations
// 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