/** * Create a new type safe empty Iterable * @returns An `Iterable` that yields 0 items */ export function* newEmpty(): Iterable { return; } /** * Creates a new `Iterable` that yields at most n items from src. * Does not modify `src` which can be used later. * @param src An initial iterator * @param n The maximum number of elements to take from src. Yields up to the floor of `n` and 0 items if n < 0 */ export function* take(src: Iterable, n: number): Iterable { outer: for (let i = 0; i < n; i += 1) { for (const item of src) { yield item; continue outer; } // if we are here that means that `src` has been exhausted. Don't bother trying again. break outer; } } /** * Creates a new iterator that iterates (lazily) over its input and yields the * result of `fn` for each item. * @param src A type that can be iterated over * @param fn The function that is called for each value */ export function* map(src: Iterable, fn: (from: T) => U): Iterable { for (const from of src) { yield fn(from); } } export function* flatMap(src: Iterable, fn: (from: T) => Iterable): Iterable { for (const from of src) { yield* fn(from); } } /** * Creates a new iterator that iterates (lazily) over its input and yields the * items that return a `truthy` value from `fn`. * @param src A type that can be iterated over * @param fn The function that is called for each value */ export function* filter(src: Iterable, fn: (from: T) => any): Iterable { for (const from of src) { if (fn(from)) { yield from; } } } /** * Creates a new iterator that iterates (lazily) over its input and yields the * result of `fn` when it is `truthy` * @param src A type that can be iterated over * @param fn The function that is called for each value */ export function* filterMap(src: Iterable, fn: (from: T) => U): Iterable { for (const from of src) { const res = fn(from); if (res) { yield res; } } } /** * Creates a new iterator that iterates (lazily) over its input and yields the * result of `fn` when it is not null or undefined * @param src A type that can be iterated over * @param fn The function that is called for each value */ export function* filterMapStrict(src: Iterable, fn: (from: T) => U): Iterable { for (const from of src) { const res = fn(from); if (res != null) { yield res; } } }