Last active
March 19, 2021 23:36
-
-
Save HichamBenjelloun/74710109ffb6cc49bcc3a2999ad73864 to your computer and use it in GitHub Desktop.
A function that creates a generator over a subset of a specified iterable using a condition
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
const filter = function* (iterable, cond) { | |
const iterator = iterable[Symbol.iterator](); | |
let cursor = iterator.next(); | |
do { | |
const {value} = cursor; | |
if (cond(value)) { | |
yield value; | |
} | |
} while (!(cursor = iterator.next()).done); | |
}; | |
export {filter}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
Note that this function also works for "infinite" iterables.