Skip to content

Commit

Permalink
ts - flat
Browse files Browse the repository at this point in the history
  • Loading branch information
jihunhong committed Oct 26, 2022
1 parent 92b8455 commit 992c0d2
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions TypeScript/22.10.26 flat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
### flat()

```ts
const a = [1, 2, 3, [1, 2], [[1], [2]]].flat();
// [1, 2, 3, 1, 2, [1], [2]]
// a: (number | number[])[]
```

flat()์˜ ํƒ€์ดํ•‘์€ ๊ฒฐ๊ณผ๊ฐ’์˜ dimension์„ ์ •ํ™•ํžˆ ์ถ”๋ก ํ•˜๊ณ  ์žˆ๋Š”๋ฐ ํƒ€์ดํ•‘๋œ ๋ฐฉ๋ฒ•์„ ์•Œ์•„๋ณด์ž

```ts
flat<A, D extends number = 1>(
this: A,
depth?: D
): FlatArray<A, D>[]

type FlatArray<Arr, Depth extends number> = {
"done": Arr,
"recur": Arr extends ReadonlyArray<infer InnerArr>
? FlatArray<InnerArr, [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 , 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]>[Depth]
: Arr
}[Depth extends -1 ? 'done' : 'recur'];
```
```ts
const test = [1, 2, 3, [1, 2], [[1], [2]]].flat(2);
// FlatArray<number | number[] | number[][][], 2>
// [Depth extends -1 ? 'done' : 'recur']; ์—์„œ Depth๋Š” 2์ด๋ฏ€๋กœ 'recur'๋กœ
// ReadonlyArray์—์„œ์˜ ์›์†Œ๋“ค์„ ์ถ”๋ก ํ•˜์—ฌ
// FlatArray<number | number[] | number[][], 1>
// FlatArray<number | number[], 0>
// number (done)
// number[]
```

0 comments on commit 992c0d2

Please sign in to comment.