summaryrefslogtreecommitdiff
path: root/src/utils/iterator.ts
blob: fa58fc9314f48920188cf467b9d5a0d85851b4f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
export type MaybeIterable<T> = T | Iterable<T>;
export type NonEmptyArray<T> = [T, ...T[]];
export type AsyncYieldType<T> = T extends AsyncGenerator<infer U> ? U : never;

export function surelyIterable<T>(maybe: MaybeIterable<T>): Iterable<T> {
  return typeof maybe === "object" && maybe !== null && Symbol.iterator in maybe
    ? maybe
    : [maybe];
}

export async function* createAsyncIterator<T>(
  promises: Promise<T>[],
): AsyncGenerator<T, void, void> {
  for (const promise of promises) {
    yield promise;
  }
}

export function filterDuplicate<T, K>(
  array: Iterable<T>,
  key: (i: T) => K,
): T[] {
  const seen = new Map<K, T>();
  for (const i of array) {
    const id = key(i);
    if (!seen.has(id)) {
      seen.set(id, i);
    }
  }
  return Array.from(seen.values());
}

export async function findMapAsync<T, R>(
  iter: Iterable<T>,
  predicate: (value: T) => Promise<R>,
): Promise<R | undefined> {
  const arr = Array.from(iter);

  async function tryNext(index: number): Promise<R | undefined> {
    if (index >= arr.length) {
      return await Promise.resolve(undefined);
    }

    try {
      return await predicate(arr[index]);
    } catch {
      return tryNext(index + 1);
    }
  }

  return await tryNext(0);
}