首页 > 其他分享 >[Typescript] 57. Medium - FlattenDepth

[Typescript] 57. Medium - FlattenDepth

时间:2022-10-19 15:00:07浏览次数:39  
标签:... Typescript _____________ FlattenDepth 57 extends Expect type

Recursively flatten array up to depth times.

For example:

type a = FlattenDepth<[1, 2, [3, 4], [[[5]]]], 2> // [1, 2, 3, 4, [5]]. flattern 2 times
type b = FlattenDepth<[1, 2, [3, 4], [[[5]]]]> // [1, 2, 3, 4, [[5]]]. Depth defaults to be 1

If the depth is provided, it's guaranteed to be positive integer.

 

/* _____________ Your Code Here _____________ */

type FlattenDepth<T extends any[], U extends number = 1, ACC extends any[] = []> = ACC['length'] extends U 
  ? T 
  : T extends [infer A, ...infer RT]
    ? A extends any[]
      ? [...FlattenDepth<A, U, [...ACC, null]>, ...FlattenDepth<RT, U, ACC>] 
      : [A, ...FlattenDepth<RT, U, ACC>]
    : [];

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<FlattenDepth<[]>, []>>,
  Expect<Equal<FlattenDepth<[1, 2, 3, 4]>, [1, 2, 3, 4]>>,
  Expect<Equal<FlattenDepth<[1, [2]]>, [1, 2]>>,
  Expect<Equal<FlattenDepth<[1, 2, [3, 4], [[[5]]]], 2>, [1, 2, 3, 4, [5]]>>,
  Expect<Equal<FlattenDepth<[1, 2, ['3', 4], [[[5]]]]>, [1, 2, '3', 4, [[5]]]>>,
  Expect<Equal<FlattenDepth<[1, [2, [3, [4, [5]]]]], 3>, [1, 2, 3, 4, [5]]>>,
  Expect<Equal<FlattenDepth<[1, [2, [3, [4, [5]]]]], 19260817>, [1, 2, 3, 4, 5]>>,
]

 The problem of current solution is possible to be overflow.

To find a better solution

 

 

标签:...,Typescript,_____________,FlattenDepth,57,extends,Expect,type
From: https://www.cnblogs.com/Answer1215/p/16806227.html

相关文章