Created
April 10, 2019 19:41
-
-
Save jmakeig/83f6903ad4f40e48cdc59550e436c3d6 to your computer and use it in GitHub Desktop.
takeWhile implementation for JavaScript Iterables
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
function* takeWhile(iterable /* Sequence, Array, etc. */, predicate = () => true) { | |
// TODO: Test that iterable is, well, iterable and not something else | |
for (const item of iterable) { | |
if (predicate(item)) { | |
yield item; | |
} else { | |
break; | |
} | |
} | |
} | |
console.log(Array.from(takeWhile([1, 2, 3, 4, 5, 6, 7], x => x < 3))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add index param so that a predicate can use it to determine whether to take. For example, I only want the first 20.