1
0

add cartesian product

This commit is contained in:
2025-10-19 14:41:58 +02:00
parent 955acc6c96
commit 4e5dfd7134
4 changed files with 98 additions and 0 deletions

View File

@@ -664,6 +664,10 @@ export abstract class BaseAsyncSequence<TElement> extends AsyncSequenceMarker im
return new ZippedAsyncSequence<TElement, TOther>(this, wrap(sequence));
}
cartesianProduct<TOther>(sequence: MaybeAsyncIterable<TOther>): AsyncSequence<[TElement, TOther]> {
return new CartesianProductAsyncSequence<TElement, TOther>(this, wrap(sequence));
}
indexed(): AsyncSequence<[number, TElement]> {
return new IndexedAsyncSequence<TElement>(this);
}
@@ -1022,6 +1026,10 @@ export class DelegatedAsyncSequence<TElement> extends AsyncSequenceMarker implem
return this.#sequence.zip(wrap(sequence));
}
cartesianProduct<TOther>(sequence: MaybeAsyncIterable<TOther>): AsyncSequence<[TElement, TOther]> {
return this.#sequence.cartesianProduct(wrap(sequence));
}
indexed(): AsyncSequence<[number, TElement]> {
return this.#sequence.indexed();
}
@@ -1821,6 +1829,46 @@ class ZippedAsyncSequence<T, U> extends BaseAsyncSequence<[T, U]> {
}
}
export class CartesianProductAsyncSequence<T, U> extends BaseAsyncSequence<[T, U]> {
readonly #first: AsyncSequence<T>;
readonly #second: AsyncSequence<U>;
constructor(first: AsyncSequence<T>, second: AsyncSequence<U>) {
super();
this.#first = first;
this.#second = second;
}
override async nonEnumeratedCount() {
const n1 = await this.#first.nonEnumeratedCount();
if (n1 < 0) {
return -1;
}
const n2 = await this.#second.nonEnumeratedCount();
if (n2 < 0) {
return -1;
}
return n1 * n2;
}
override async maxCount() {
return await this.#first.maxCount() * await this.#second.maxCount();
}
override async *iterator() {
for await (const firstObj of this.#first) {
for await (const secondObj of this.#second) {
yield [firstObj, secondObj] as [T, U];
}
}
}
}
class UnionAsyncSequence<T> extends BaseAsyncSequence<T> {
readonly #first: AsyncSequence<T>;
readonly #second: AsyncSequence<T>;