Path: blob/main/extensions/copilot/src/util/common/asyncIterableUtils.ts
13397 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45export namespace AsyncIterUtils {67export async function* map<T0, T1>(iterable: AsyncIterable<T0>, mapItem: (item: T0) => T1): AsyncIterable<T1> {8for await (const item of iterable) {9yield mapItem(item);10}11}1213export async function* mapWithReturn<T0, R0, N, T1, R1 = R0>(14iterable: AsyncIterable<T0, R0, N>,15mapItem: (item: T0) => T1,16mapReturn: (ret: R0) => R1,17): AsyncGenerator<T1, R1, N> {18const iter = iterable[Symbol.asyncIterator]();19let v: IteratorResult<T0, R0>;2021while (!((v = await iter.next()).done)) {22yield mapItem(v.value);23}2425return mapReturn(v.value);26}2728export async function* filter<T>(iterable: AsyncIterable<T>, filterItem: (item: T) => boolean): AsyncIterable<T> {29for await (const item of iterable) {30if (filterItem(item)) {31yield item;32}33}34}3536export async function toArray<T>(iterable: AsyncIterable<T>): Promise<T[]> {37const arr: T[] = [];38for await (const item of iterable) {39arr.push(item);40}41return arr;42}4344export async function* fromArray<T>(arr: T[]): AsyncIterable<T> {45for (const item of arr) {46yield item;47}48}4950export async function* fromArrayWithReturn<T, R>(arr: T[], returnValue: R): AsyncGenerator<T, R> {51for (const item of arr) {52yield item;53}54return returnValue;55}5657export async function toArrayWithReturn<T, R>(iterable: AsyncIterable<T, R>): Promise<[T[], ret: R]> {58const iter = iterable[Symbol.asyncIterator]();59const arr: T[] = [];60let v: IteratorResult<T, R>;6162while (!((v = await iter.next()).done)) {63arr.push(v.value);64}6566return [arr, v.value];67}6869export async function drainUntilReturn<T, R>(iterable: AsyncIterable<T, R>): Promise<R> {70const iter = iterable[Symbol.asyncIterator]();71let v: IteratorResult<T, R>;7273do {74v = await iter.next();75} while (!v.done);7677return v.value;78}79}8081/**82* Namespace for extensions to AsyncIterUtils that are not generally useful enough to be in the main namespace, but are still worth keeping around.83*/84export namespace AsyncIterUtilsExt {8586export async function* splitLines(stream: AsyncIterable<string>): AsyncIterable<string> {87let buffer: string | null = null;8889for await (const chunk of stream) {90buffer ??= '';91buffer += chunk;9293const parts: string[] = buffer.split(/\r?\n/);94buffer = parts.pop() ?? '';9596yield* parts;97}9899if (buffer !== null) {100yield buffer;101}102}103}104105106