Last active
November 23, 2017 12:31
-
-
Save RoystonS/38b295a04c1c96eafe704bcfd3603e8e to your computer and use it in GitHub Desktop.
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
// 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