Skip to content

Instantly share code, notes, and snippets.

@HichamBenjelloun
Last active March 19, 2021 23:36
Show Gist options
  • Save HichamBenjelloun/74710109ffb6cc49bcc3a2999ad73864 to your computer and use it in GitHub Desktop.
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
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};
@HichamBenjelloun
Copy link
Author

HichamBenjelloun commented Jun 10, 2020

Usage:

const arr = [1, 2, 3, 4, 5, 6];

console.log([...filter(arr, x => x % 2 === 0)]); // [ 2, 4, 6 ]
console.log([...filter(arr, x => x % 2 === 1)]); // [ 1, 3, 5 ]

Note that this function also works for "infinite" iterables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment