2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScriptの多重ループ読みにくいのでデカルト積でループしたいけどメモリ負荷高いのでデカルト積の要素を返却するジェネレータ(型定義有)

Last updated at Posted at 2022-11-17

TL;DR

を異なる型の配列でも使えるように型定義しただけです(プルリクだしてみようかな)

type CartesianProductElement<T extends unknown[][]> = T extends []
  ? []
  : T extends [Array<infer V>, ...infer W extends unknown[][]]
  ? [V, ...CartesianProductElement<W>]
  : [];

export function* cartesian<T extends unknown[][]>(
  ...args: T
): Generator<CartesianProductElement<T>, void, undefined> {
  if (args.length === 0) yield [] as any;
  else {
    const [head, ...rest] = args;
    for (const h of head) {
      const restIter = cartesian(...rest);
      for (const r of restIter) {
        yield [h, ...r] as any;
      }
    }
  }
}

cartesian([1, 2], ['a', 'b']) // => [[1,'a'], [1,'b'], [2,'a'], [2,'b']]
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?