5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TypeScriptAdvent Calendar 2022

Day 22

すべてのパターンを返す関数

Posted at

typescriptで、与えられたパターンをすべて返す関数を作ってみました。

網羅的にチェックをする場合に使えるかもしれません。

// by KatagiriSo
const patterns = <A>(list: A[][]) =>
list.reduce(
  (as: A[][], pat: A[]) =>
    as.flatMap((a: A[]) => pat.map(b => a.concat([b]))),
  [[]]
)

これを使うと

console.log(patterns([["1", "2"], ["a", "b", "c"],["A","B"]]))
/*
[
  [ '1', 'a', 'A' ],
  [ '1', 'a', 'B' ],
  [ '1', 'b', 'A' ],
  [ '1', 'b', 'B' ],
  [ '1', 'c', 'A' ],
  [ '1', 'c', 'B' ],
  [ '2', 'a', 'A' ],
  [ '2', 'a', 'B' ],
  [ '2', 'b', 'A' ],
  [ '2', 'b', 'B' ],
  [ '2', 'c', 'A' ],
  [ '2', 'c', 'B' ]
]
*/

のようにすべてのパターンが網羅された配列を返します。

5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?