관리 메뉴

프로그래밍 삽질 중

[TS] flat 본문

과거 프로그래밍 자료들/Javascript&typescript

[TS] flat

평부 2022. 9. 20. 15:54

 

 

 

출처 : https://github.com/ZeroCho/ts-all-in-one

 

GitHub - ZeroCho/ts-all-in-one

Contribute to ZeroCho/ts-all-in-one development by creating an account on GitHub.

github.com

 

출처 : https://github.com/microsoft/TypeScript/blob/main/lib/lib.es2019.array.d.ts

 

GitHub - microsoft/TypeScript: TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

TypeScript is a superset of JavaScript that compiles to clean JavaScript output. - GitHub - microsoft/TypeScript: TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

github.com

 

 

* [lib.es2019.array.d.ts] flat 

   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"];

 

 

* Flat 예제

const a = [1, 2, 3, [1, 2], [[1], [2]]].flat(); //[1, 2, 3, 1, 2, [1], [2]];
const b = [1, 2,3, [1, 2]].flat(); //[1, 2, 3, 1, 2]
const c = [1, 2, 3, [1, 2], [[1], [2]]].flat(2) //[1, 2, 3, 1, 2, 1, 2]

//flat : 차원을 알아내는 매서드, 차원을 한 단계 낮춰줌

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

//FlatArray<(number[] | number[][] | number[][][]), 2>[]
//FlatArray<(number | number[] | number[][]), 1>[]

// "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 => number은 array가 아니면 number로 나옴

//FlatArray<(number | number[]), 0>[]
//FlatArray<(number | -1>[]
//number[]