tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

AsyncIterableUtil.ts (992B)


      1 /**
      2 * @license
      3 * Copyright 2023 Google Inc.
      4 * SPDX-License-Identifier: Apache-2.0
      5 */
      6 import type {AwaitableIterable} from '../common/types.js';
      7 
      8 /**
      9 * @internal
     10 */
     11 export class AsyncIterableUtil {
     12  static async *map<T, U>(
     13    iterable: AwaitableIterable<T>,
     14    map: (item: T) => Promise<U>,
     15  ): AsyncIterable<U> {
     16    for await (const value of iterable) {
     17      yield await map(value);
     18    }
     19  }
     20 
     21  static async *flatMap<T, U>(
     22    iterable: AwaitableIterable<T>,
     23    map: (item: T) => AwaitableIterable<U>,
     24  ): AsyncIterable<U> {
     25    for await (const value of iterable) {
     26      yield* map(value);
     27    }
     28  }
     29 
     30  static async collect<T>(iterable: AwaitableIterable<T>): Promise<T[]> {
     31    const result = [];
     32    for await (const value of iterable) {
     33      result.push(value);
     34    }
     35    return result;
     36  }
     37 
     38  static async first<T>(
     39    iterable: AwaitableIterable<T>,
     40  ): Promise<T | undefined> {
     41    for await (const value of iterable) {
     42      return value;
     43    }
     44    return;
     45  }
     46 }