Skip to main content
Module

x/better_iterators/mod.ts

Chainable iterators (sync and async) for TypeScript, with support for opt-in, bounded parallelism
Latest
File
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
/** * Better Iterators * ================ * * This module provides {@link Lazy} and {@link LazyAsync} classes which make it easy * to chain together data transformations. * * The {@link lazy} function is the simplest way to get started. * * ```ts * import { lazy, range } from "./mod.ts" * * // You can use any Iterable here (such as an Array, or Generator), but * // Lazy objects are themselves Iterable: * let iterable = range({to: 1000}) * * let results = lazy(iterable) * .filter(it => it % 2 == 0) * .map(it => it*it) * .limit(10) * * // No iteration has happened yet. * // This will trigger it: * for (let item of results) { console.log(item) } * ``` * * Lazy Iteration Consumes All Input * --------------------------------- * * Note that iterating a Lazy(Async) will consume its items -- the operation is * not repeatable. If you need to iterate multiple times, save your result to * an array with {@link Lazy#toArray} * * ```ts * import { lazy, range } from "./mod.ts" * * let results = lazy([1, 2, 3, 4, 5]).map(it => `number: ${it}`) * * for (let result of results) { console.log("first pass:", result)} * * // Has no more values to yield, will throw an exception: * for (let result of results) { console.log("second pass:", result)} * ``` * * Asynchronous Iteration With Promises (Not Recommended) * ------------------------------------------------------ * * Other iterator libraries show examples of parallel/async iteration like this: * * ```ts * import { lazy, range } from "./mod.ts" * let urls = [ * "https://www.example.com/foo", * "https://www.example.com/bar" * ] * let lazySizes = lazy(urls) * .map(async (url) => { * let response = await fetch(url) * return await response.text() * }) * // The type is now Lazy<Promise<string>> so we're stuck having to deal * // with promises for the rest of the lazy chain: * .map(async (bodyPromise) => (await bodyPromise).length) * // and so on... * * // `lazySizes` also ends up as a `Lazy<Promise<number>>`, so we've got to * // await all of the items ourselves: * let sizes = await Promise.all(lazySizes.toArray()) * ``` * * This approach might seem to work, but it has unbounded parallelism. If you * have N URLs, `.toArray()` will create N promises, and the JavaScript runtime * will start making progress on all of them simultaneously. * * That might work for small workloads, but network and memory resources are not * unbounded, so you may end up with worse, or less reliable performance. * * * Lazy Asynchronous Iteration * --------------------------- * * Better Iterators provides a simpler, safer API when working with async code: * You can convert a `Lazy` to a `LazyAsync`: * * ```ts * import { lazy } from "./mod.ts" * let urls = [ * "https://www.example.com/foo", * "https://www.example.com/bar" * ] * let lazySizes = lazy(urls) * .toAsync() * .map(async (url) => { * let response = await fetch(url) * return await response.text() * }) * // here the type is LazyAsync<string> (not Lazy<Promise<string>>) * // so further lazy functions are easier to work with: * .map(it => it.length) * ``` * * Here, {@link LazyAsync#map} does the least surprising thing and does not * introduce parallelism implicitly. You've still got serial lazy iteration. * * If you DO want parallelism, you can explicitly opt in like this: * * ```ts * import { lazy } from "./mod.ts"* let urls = [ * "https://www.example.com/foo", * "https://www.example.com/bar" * ] * let lazySizes = lazy(urls) * .map({ * parallel: 5, * async mapper(url) { * let response = await fetch(url) * return await response.text() * } * }) * // etc. * ``` * * Functional Idioms * ----------------- * * You'll find other common Functional Programming idioms on the {@link Lazy} * and {@link LazyAsync} types, like `associateBy`, `groupBy`, `fold`, `sum`, * `partition`, etc. * * @module */
import { Peekable, PeekableAsync } from "./_src/peek.ts";import { stateful, StatefulPromise } from "./_src/promise.ts";import { Queue } from "./_src/queue.ts";
/** * Create a Lazy(Async) from your (Async)Iterator. */export function lazy<T>(iter: Iterable<T>): Lazy<T>export function lazy<T>(iter: AsyncIterable<T>): LazyAsync<T>export function lazy<T>(iter: Iterable<T>|AsyncIterable<T>): Lazy<T>|LazyAsync<T> { if (Symbol.asyncIterator in iter) { return LazyAsync.from(iter) }
return Lazy.from(iter)}
// Note: There seems to be a bug in `deno doc` so I'm going to copy/paste the// method docs onto the implementors. 😢// https://github.com/denoland/deno_doc/issues/136/** * Shared interface for {@link Lazy} and {@link LazyAsync}. * (Note: `LazyAsync` implements some methods that are not shared.) * * You shouldn't need to interact with these classes or this interface * directly, though. You can use {@link lazy} to automatically instantiate the * correct one. * * Operations on lazy iterators consume the underlying iterator. You should not * use them again. */export interface LazyShared<T> {
/** * Apply `transform` to each element. * * Works like {@link Array#map}. */ map<Out>(transform: Transform<T, Out>): LazyShared<Out>
/** * Asynchronously transform elements in parallel. */ map<Out>(options: ParallelMapOptions<T, Out>): LazyAsync<Out>
/** Keeps only items for which `f` is `true`. */ filter(f: Filter<T>): LazyShared<T> /** Overload to support type narrowing. */ filter<S extends T>(f: (t: T) => t is S): LazyShared<S>

/** Limit the iterator to returning at most `count` items. */ limit(count: number): LazyShared<T>
/** Collect all items into an array. */ toArray(): Awaitable<Array<T>>
/** Injects a function to run on each T as it is being iterated. */ also(fn: (t: T) => void): LazyShared<T>
/** Partition items into `matches` and `others` according to Filter `f`. */ partition(f: Filter<T>): Awaitable<Partitioned<T>>
/** Get the first item. @throws if there are no items. */ first(): Awaitable<T>
/** Get the first item. Returns `defaultValue` if there is no first item. */ firstOr<D>(defaultValue: D): Awaitable<T|D>
/** Skip (up to) the first `count` elements */ skip(count: number): LazyShared<T>
/** * Given `keyFn`, use it to extract a key from each item, and create a Map * grouping items by that key. */ groupBy<Key>(keyFn: Transform<T, Key>): Awaitable<Map<Key, T[]>> /** * Adds a `valueFn` to extract that value (instead of T) into a group. */ groupBy<Key, Value>(keyFn: Transform<T, Key>, valueFn: Transform<T, Value>): Awaitable<Map<Key, Value[]>>
/** * Given `uniqueKeyFn`, use it to extract a key from each item, and create a * 1:1 map from that to each item. * * @throws if duplicates are found for a given key. */ associateBy<Key>( uniqueKeyFn: Transform<T, Key>, ): Awaitable<Map<Key, T>>
/** * Takes an additional `valueFn` to extract a value from `T`. The returned * map maps from Key to Value. (instead of Key to T) */ associateBy<Key, Value>( uniqueKeyFn: Transform<T, Key>, valueFn: Transform<T, Value> ): Awaitable<Map<Key, Value>>
/** Flattens a Lazy<Iterable<T>> to a Lazy<T> */ flatten(): LazyShared<Flattened<T>>
/** Joins multiple string values into a string. */ joinToString(args?: JoinToStringArgs): Awaitable<JoinedToString<T>>
/** Fold values. See example in {@link LazyShared#sum} */ fold<I>(initialValue: I, foldFn: (i: I, t: T) => I): Awaitable<I>
/** * Sums a Lazy iterator of `number`s. * * This is equivalent to: * ```ts * import { lazy, range } from "./mod.ts" * * range({to: 10}).fold(0, (a, b) => a + b) * ``` * */ sum(): Awaitable<T extends number ? number : never> // Note: Technically, the sum() implementation will convert non-numbers to // a string and then do string concatenation. But it's probably not desired, // and would be more efficient with join(), so we return a `never` type here.
/** * Averages numbers from the Lazy iterable. * * Will return NaN if no numbers exist. * * Note: This algorithm does a simple left-to-right accumulation of the sum, * so can suffer from loss of precision when summing things with vastly * different scales, or working with sums over Number.MAX_SAFE_INTEGER. */ avg(): Awaitable<T extends number ? number : never>
/** * Get a "peekable" iterator, which lets you peek() at the next item without * removing it from the iterator. */ peekable(): Peekable<T> | PeekableAsync<T>
/** * Iterate by chunks of a given size formed from the underlying Iterator. * * Each chunk will be exactly `size` until the last chunk, which may be * from 1-size items long. */ chunked(size: number): LazyShared<T[]>
/** * Repeat items `count` times. * * ```ts * import { range } from "./mod.ts" * * let nine = range({to: 3}).repeat(3).sum() * ``` */ repeat(count: number): LazyShared<T>
/** * Like {@link #repeat}, but repeates forever. */ loop(): LazyShared<T>}
/** * Passing this to the map() function indicates that you want to map * values */export interface ParallelMapOptions<T, Out> { /** * The maximum number of map functions to run in parallel. * This gives you bounded parallelism so that you don't overwhelm * whatever resource you're mapping with. (ex: fetch, exec, write, etc.) */ parallel: number
/** * The async mapping function to run in parallel. */ mapper: (t: T) => Promise<Out>
/** * Should we maintain the input ordering in the output? * * This is the least-surprising behavior, but it comes at the cost of * potential head-of-line blocking. * * Default: true */ ordered?: boolean}
export class Lazy<T> implements Iterable<T>, LazyShared<T> {
/** Prefer to use the {@link lazy} function. */ static from<T>(iter: Iterable<T>): Lazy<T> { return new Lazy(iter) }
private constructor(iter: Iterable<T>) { this.#innerStore = iter }
#innerStore?: Iterable<T>
get #inner(): Iterable<T> { let inner = this.#innerStore this.#innerStore = undefined
if (inner === undefined) { throw new Error(`Logic Error: Iteration for this Lazy has already been consumed`) } return inner }
[Symbol.iterator](): Iterator<T> { return this.#inner[Symbol.iterator]() }
/** * Apply `transform` to each element. * * Works like {@link Array#map}. */ map<Out>(transform: Transform<T, Out>): Lazy<Out>; map<Out>(options: ParallelMapOptions<T,Out>): LazyAsync<Out>; map<Out>(arg: Transform<T,Out>|ParallelMapOptions<T,Out>): Lazy<Out>|LazyAsync<Out> { if ("parallel" in arg) { return this.toAsync().map(arg) } return this.#simpleMap(arg) }
#simpleMap<Out>(transform: Transform<T, Out>): Lazy<Out> { let inner = this.#inner let transformIter = function*() { for (let item of inner) { yield transform(item) } } return Lazy.from(transformIter()) }
/** Overload to support type narrowing. */ filter<S extends T>(f: (t: T) => t is S): Lazy<S> /** Keeps only items for which `f` is `true`. */ filter(f: Filter<T>): Lazy<T> filter(f: Filter<T>): Lazy<T> { let inner = this.#inner let matchIter = function*() { for (let item of inner) { if (!f(item)) { continue } yield item } } return Lazy.from(matchIter()) }
/** Limit the iterator to returning at most `count` items. */ limit(count: number): Lazy<T> { let inner = this.#inner let countIter = function*() { if (count <= 0) { return } for (let item of inner) { yield item if (--count <= 0) { break } } } return Lazy.from(countIter()) }
/** Injects a function to run on each T as it is being iterated. */ also(fn: (t: T) => void): Lazy<T> { let inner = this.#inner let gen = function*() { for (let item of inner) { fn(item) yield item } } return Lazy.from(gen()) }
/** Partition items into `matches` and `others` according to Filter `f`. */ partition(f: Filter<T>): Partitioned<T> { let matches: T[] = [] let others: T[] = []
for (const item of this) { if (f(item)) { matches.push(item) } else { others.push(item) } }
return {matches, others} }
/** Get the first item. @throws if there are no items. */ first(): T { for (let item of this) { return item } throw new Error(`No items.`) }
/** Get the first item. Returns `defaultValue` if there is no first item. */ firstOr<D>(defaultValue: D): T | D { for (let item of this) { return item } return defaultValue }
/** Skip (up to) the first `count` elements */ skip(count: number): Lazy<T> { let inner = this.#inner let gen = function * () { let iter = inner[Symbol.iterator]() while (count-- > 0) { let next = iter.next() if (next.done) { return } }
while (true) { let next = iter.next() if (next.done) { return } yield next.value } }
return Lazy.from(gen()) }
/** * Given `keyFn`, use it to extract a key from each item, and create a Map * grouping items by that key. */ groupBy<Key>(keyFn: Transform<T, Key>): Map<Key, T[]>; /** * Adds a `valueFn` to extract that value (instead of T) into a group. */ groupBy<Key, Value>(keyFn: Transform<T, Key>, valueFn: Transform<T, Value>): Map<Key, Value[]> groupBy<Key, Value>(keyFn: Transform<T, Key>, valueFn?: Transform<T, Value|T>): Map<Key, (T|Value)[]> { let map = new Map<Key, (T|Value)[]>() valueFn ??= (t) => t for (const item of this) { const key = keyFn(item) let group = map.get(key) if (!group) { group = [] map.set(key, group) } group.push(valueFn(item)) } return map } /** * Given `uniqueKeyFn`, use it to extract a key from each item, and create a * 1:1 map from that to each item. * * @throws if duplicates are found for a given key. */ associateBy<Key>(uniqueKeyFn: Transform<T, Key>, ): Map<Key, T>; /** * Takes an additional `valueFn` to extract a value from `T`. The returned * map maps from Key to Value. (instead of Key to T) */ associateBy<Key, Value>( uniqueKeyFn: Transform<T, Key>, valueFn: Transform<T, Value> ): Map<Key, Value>; associateBy<Key, Value>( uniqueKeyFn: Transform<T, Key>, valueFn?: Transform<T, Value|T> ): Map<Key, T|Value> { let map = new Map<Key, T|Value>() valueFn ??= (t) => t for (const item of this) { const key = uniqueKeyFn(item) if (map.has(key)) { throw new Error(`unique key collision on ${key}`) } map.set(key, valueFn(item)) } return map }
/** Flattens a Lazy<Iterable<T>> to a Lazy<T> */ flatten(): Lazy<Flattened<T>> { let inner = this.#inner return Lazy.from(function * () { for (const value of inner) { yield * requireIterable(value) } }()) }
/** Joins multiple string values into a string. */ joinToString(args?: JoinToStringArgs): JoinedToString<T> { const sep = args?.sep ?? ", " return this.toArray().join(sep) as JoinedToString<T> }
/** Collect all items into an array. */ toArray(): Array<T> { return [... this.#inner] }
/** * Convert to a LazyAsync, which better handles chains of Promises. */ toAsync(): LazyAsync<T> { let inner = this.#inner let gen = async function*() { for (let item of inner) { yield item } } return LazyAsync.from(gen()) }
fold<I>(initial: I, foldFn: (i: I, t: T) => I): I { let inner = this.#inner let accumulator = initial for (let item of inner) { accumulator = foldFn(accumulator, item) } return accumulator }
sum(): T extends number ? number : never { let out = this.fold(0, (a, b) => a + (b as number)) return out as (T extends number ? number : never) }
avg(): T extends number ? number : never { let count = 0 let sum = this.also( () => { count += 1 } ).sum() return sum / count as (T extends number ? number : never) }
/** * Get a "peekable" iterator, which lets you peek() at the next item without * removing it from the iterator. */ peekable(): Peekable<T> { let inner = this.#inner return Peekable.from(inner) }
/** * Iterate by chunks of a given size formed from the underlying Iterator. * * Each chunk will be exactly `size` until the last chunk, which may be * from 1-size items long. */ chunked(size: number): Lazy<T[]> { let inner = this.#inner let gen = function* generator() { let out: T[] = [] for (const item of inner) { out.push(item) if (out.length >= size) { yield out out = [] } } if (out.length > 0) { yield out } } return lazy(gen()) }
/** * Repeat items `count` times. * * ```ts * import { range } from "./mod.ts" * * let nine = range({to: 3}).repeat(3).sum() * ``` */ repeat(count: number): Lazy<T> { if (count < 0) { throw new Error(`count may not be < 0. Was: ${count}`) }
if (count == 1) { return this }
let inner = this.#inner const gen = function* generator() { const arr: T[] = [] for (const item of inner) { yield item arr.push(item) }
if (arr.length == 0) { return }
for (let i = 1; i < count; i++) { yield * arr } } return lazy(gen()) }
/** * Like {@link #repeat}, but repeates forever. */ loop(): Lazy<T> { let inner = this.#inner const gen = function* generator() { const arr: T[] = [] for (const item of inner) { yield item arr.push(item) }
if (arr.length == 0) { return }
while (true) { yield * arr } } return lazy(gen()) }}


export class LazyAsync<T> implements AsyncIterable<T>, LazyShared<T> {
/** * This lets you directly create an AsyncIterable, but you might prefer * the shorter {@link lazy} function. */ static from<T>(iter: AsyncIterable<T>): LazyAsync<T> { return new LazyAsync(iter) }
private constructor(iter: AsyncIterable<T>) { this.#innerStore = iter } #innerStore?: AsyncIterable<T>
get #inner(): AsyncIterable<T> { let inner = this.#innerStore this.#innerStore = undefined
if (inner === undefined) { throw new Error(`Logic Error: Iteration for this LazyAsync has already been consumed`) } return inner }
[Symbol.asyncIterator](): AsyncIterator<T> { return this.#inner[Symbol.asyncIterator]() }
/** * Apply `transform` to each element. * * Works like {@link Array#map}. */ map<Out>(transform: Transform<T, Awaitable<Out>>): LazyAsync<Out>; map<Out>(options: ParallelMapOptions<T, Out>): LazyAsync<Out>; map<Out>(arg: Transform<T, Awaitable<Out>>|ParallelMapOptions<T,Out>): LazyAsync<Out> { if ("parallel" in arg) { const { ordered, parallel, mapper } = arg if (ordered == false) { return this.#mapParUnordered(parallel, mapper) } return this.#mapPar(parallel, mapper) }
return this.#simpleMap(arg) }
#simpleMap<Out>(transform: Transform<T, Awaitable<Out>>): LazyAsync<Out> { let inner = this.#inner let gen = async function*() { for await (let item of inner) { yield await transform(item) } } return LazyAsync.from(gen()) }
/** * @deprecated Use {@link map} with {@link ParallelMapOptions} instead. */ mapPar<Out>(max: number, transform: Transform<T, Promise<Out>>): LazyAsync<Out> { return this.#mapPar(max, transform) }
#mapPar<Out>(max: number, transform: Transform<T, Promise<Out>>): LazyAsync<Out> { let inner = this.#inner let gen = async function*() {
let pending = new Queue<Promise<Out>>() for await (let item of inner) { pending.push(transform(item))
while (pending.size >= max) { yield await pending.pop() } } while (!pending.isEmpty) { yield await pending.pop() } }
return LazyAsync.from(gen()) }
/** * @deprecated Use {@link map} with {@link ParallelMapOptions} * and `ordered: false` */ mapParUnordered<Out>(max: number, transform: Transform<T, Promise<Out>>): LazyAsync<Out> { return this.#mapParUnordered(max, transform) }
#mapParUnordered<Out>(max: number, transform: Transform<T, Promise<Out>>): LazyAsync<Out> { if (max <= 0) { throw new Error("max must be > 0")} let inner = this.#inner let gen = async function*() {
let pending: StatefulPromise<Out>[] = [] let done: StatefulPromise<Out>[] = []
// Get a list of (at least one) "done" task. let repartition = async () => { if (pending.length == 0 || done.length > 0) { // nothing to do. return } await Promise.race(pending) let values = lazy(pending) .partition(it => it.state === "pending") pending = values.matches done = values.others }
for await (let item of inner) { pending.push(stateful(transform(item)))
while (pending.length + done.length >= max) { await repartition() yield done.pop()! } } while (pending.length + done.length > 0) { await repartition() for (let d of done) { yield d } done = [] } }
return LazyAsync.from(gen()) }
/** Overload to support type narrowing. */ filter<S extends T>(f: (t: T) => t is S): LazyAsync<S> /** Keeps only items for which `f` is `true`. */ filter(f: Filter<T>): LazyAsync<T> filter(f: Filter<T>): LazyAsync<T> { let inner = this.#inner let gen = async function*() { for await (let item of inner) { if (f(item)) { yield item } } } return LazyAsync.from(gen()) }
/** Limit the iterator to returning at most `count` items. */ limit(count: number): LazyAsync<T> { let inner = this.#inner let countIter = async function*() { if (count <= 0) { return } for await (let item of inner) { yield item if (--count <= 0) { break } } } return LazyAsync.from(countIter()) }
/** Injects a function to run on each T as it is being iterated. */ also(fn: (t: T) => void): LazyAsync<T> { let inner = this.#inner let gen = async function*() { for await (let item of inner) { fn(item) yield item } } return LazyAsync.from(gen()) }
/** Partition items into `matches` and `others` according to Filter `f`. */ async partition(f: Filter<T>): Promise<Partitioned<T>> { let matches: T[] = [] let others: T[] = []
for await (const item of this) { if (f(item)) { matches.push(item) } else { others.push(item) } }
return {matches, others} }
/** Get the first item. @throws if there are no items. */ async first(): Promise<T> { for await (let item of this) { return item } throw new Error(`No items.`) }
/** Get the first item. Returns `defaultValue` if there is no first item. */ async firstOr<D>(defaultValue: D): Promise<T | D> { for await (let item of this) { return item } return defaultValue }
/** Skip (up to) the first `count` elements */ skip(count: number): LazyAsync<T> { let inner = this.#inner let gen = async function * () { let iter = inner[Symbol.asyncIterator]() while (count-- > 0) { let next = await iter.next() if (next.done) { return } }
while (true) { let next = await iter.next() if (next.done) { return } yield next.value } }
return LazyAsync.from(gen()) }
/** * Given `keyFn`, use it to extract a key from each item, and create a Map * grouping items by that key. */ async groupBy<Key>(keyFn: Transform<T, Key>): Promise<Map<Key, T[]>> /** * Adds a `valueFn` to extract that value (instead of T) into a group. */ async groupBy<Key, Value>(keyFn: Transform<T, Key>, valueFn: Transform<T, Value>): Promise<Map<Key, Value[]>> async groupBy<Key, Value>(keyFn: Transform<T, Key>, valueFn?: Transform<T, Value|T>): Promise<Map<Key, (T|Value)[]>> { let map = new Map<Key, (T|Value)[]>() valueFn ??= (t) => t for await (const item of this) { const key = keyFn(item) let group = map.get(key) if (!group) { group = [] map.set(key, group) } group.push(valueFn(item)) } return map }
/** * Given `uniqueKeyFn`, use it to extract a key from each item, and create a * 1:1 map from that to each item. * * @throws if duplicates are found for a given key. */ associateBy<Key>( uniqueKeyFn: Transform<T, Key>, ): Promise<Map<Key, T>>; /** * Takes an additional `valueFn` to extract a value from `T`. The returned * map maps from Key to Value. (instead of Key to T) */ associateBy<Key, Value>( uniqueKeyFn: Transform<T, Key>, valueFn: Transform<T, Value> ): Promise<Map<Key, Value>>; async associateBy<Key, Value>( uniqueKeyFn: Transform<T, Key>, valueFn?: Transform<T, T|Value> ): Promise<Map<Key, T|Value>> { let map = new Map<Key, T|Value>() valueFn ??= (t) => t for await (const item of this) { const key = uniqueKeyFn(item) if (map.has(key)) { throw new Error(`unique key collision on ${key}`) } map.set(key, valueFn(item)) } return map }
/** Flattens a Lazy<Iterable<T>> to a Lazy<T> */ flatten(): LazyAsync<Flattened<T>> { let inner = this.#inner return LazyAsync.from(async function * () { for await (const value of inner) { yield * requireIterable(value) } }()) }
/** Joins multiple string values into a string. */ async joinToString(args?: JoinToStringArgs): Promise<JoinedToString<T>> { const sep = args?.sep ?? ", " return (await this.toArray()).join(sep) as JoinedToString<T> }
/** Collect all items into an array. */ async toArray(): Promise<T[]> { let out: T[] = [] for await (let item of this) { out.push(item) } return out }
async fold<I>(initial: I, foldFn: (i: I, t: T) => I): Promise<I> { let inner = this.#inner let accumulator = initial for await (let item of inner) { accumulator = foldFn(accumulator, item) } return accumulator }
async sum(): Promise<T extends number ? number : never> { let out = await this.fold(0, (a, b) => a + (b as number)) return out as (T extends number ? number : never) }
async avg(): Promise<T extends number ? number : never> { let count = 0 let sum = await this.also( () => { count += 1 } ).sum() return sum / count as (T extends number ? number : never) } /** * Get a "peekable" iterator, which lets you peek() at the next item without * removing it from the iterator. */ peekable(): PeekableAsync<T> { let inner = this.#inner return PeekableAsync.from(inner) }
/** * Iterate by chunks of a given size formed from the underlying Iterator. * * Each chunk will be exactly `size` until the last chunk, which may be * from 1-size items long. */ chunked(size: number): LazyAsync<T[]> { let inner = this.#inner let gen = async function* generator() { let out: T[] = [] for await (const item of inner) { out.push(item) if (out.length >= size) { yield out out = [] } } if (out.length > 0) { yield out } } return lazy(gen()) }
/** * Repeat items `count` times. * * ```ts * import { range } from "./mod.ts" * * let nine = range({to: 3}).repeat(3).sum() * ``` */ repeat(count: number): LazyAsync<T> { if (count < 0) { throw new Error(`count may not be < 0. Was: ${count}`) }
if (count == 1) { return this }
let inner = this.#inner const gen = async function* generator() { const arr: T[] = [] for await (const item of inner) { yield item arr.push(item) }
if (arr.length == 0) { return }
for (let i = 1; i < count; i++) { yield * arr } } return lazy(gen()) }
/** * Like {@link #repeat}, but repeates forever. */ loop(): LazyAsync<T> { let inner = this.#inner const gen = async function* generator() { const arr: T[] = [] for await (const item of inner) { yield item arr.push(item) }
if (arr.length == 0) { return }
while (true) { yield * arr } } return lazy(gen()) }}
/** * See: <https://github.com/microsoft/TypeScript/issues/31394> */export type Awaitable<T> = T | PromiseLike<T>
/** A function that transforms from In to Out */export type Transform<In,Out> = (i: In) => Out
/** Filters for matches (where boolean is true) */export type Filter<T> = (t: T) => boolean
/** The result of partitioning according to a `Filter<T>` */export interface Partitioned<T> { matches: T[], others: T[],}
export type Flattened<T> = T extends Iterable<infer Out> ? Out : never;

/** * Returns a Lazy which will yield consecutive numbers. */export function range(args?: RangeArgs): Lazy<number> { let {from, to, step, inclusive} = {...rangeArgsDefaults, ...args} let gen = function*() { for (let x = from; x < to; x += step) { yield x } if (inclusive) { yield to } } if (step < 0) { gen = function*() { for (let x = from; x > to; x += step) { yield x } if (inclusive) { yield to } } }
return Lazy.from(gen())}
export interface RangeArgs { /** default: 0 */ from?: number
/** default: Number.MAX_SAFE_INTEGER */ to?: number
/** default: 1 */ step?: number
/** * default: false * * Like ranges in many other languages, a range by default includes its * start, but not its end. If `true`, this will cause the range to include * its end. * * ```ts * import { range } from "./mod.ts" * * // [1, 2]: * console.log(range({from: 1, to: 3})) * * // [1, 2, 3]: * console.log(range({from: 1, to: 3, inclusive: true})) * ``` */ inclusive?: boolean}
export interface JoinToStringArgs { /** The separator to use. Default: ", " */ sep?: string
// Can add more join options here if people want. }
/** * Only `string` values can be joined to string */export type JoinedToString<T> = T extends string ? string : never
const rangeArgsDefaults: Required<RangeArgs> = { from: 0, to: Number.MAX_SAFE_INTEGER, step: 1, inclusive: false,} as const
function requireIterable<T>(value: T): Iterable<Flattened<T>> { if (typeof value != "object" || !value || !(Symbol.iterator in value)) { throw new Error(`value is not iterable`) } return value as Iterable<Flattened<T>>}