Skip to content

Instantly share code, notes, and snippets.

@RoystonS
Last active November 23, 2017 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RoystonS/38b295a04c1c96eafe704bcfd3603e8e to your computer and use it in GitHub Desktop.
Save RoystonS/38b295a04c1c96eafe704bcfd3603e8e to your computer and use it in GitHub Desktop.
// Returns an iterator of all positive integers
function* allPositiveIntegers(): IterableIterator<number> {
let i = 1;
while (true) {
yield i++;
}
}
// Returns an iterator which passes through selected items
// from another iterator, selected by a predicate
function* filter<T>(iterator: IterableIterator<T>, predicate: (value: T) => boolean): IterableIterator<T> {
for (const x of iterator) {
if (predicate(x)) {
yield x;
}
}
}
// Returns an iterator which selects the first 'n' values
// from another iterator
function* take<T>(iterator: IterableIterator<T>, n: number): IterableIterator<T> {
for (const x of iterator) {
if (!n--) {
return;
}
yield x;
}
}
const isEven = x => (x % 2) == 0;
// Log out the first 5 even positive integers
for (const x of take(filter(allPositiveIntegers(), isEven), 5)) {
console.log(x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment