[Typescript] 68. Medium - Fill

Fill, a common JavaScript function, now let us implement it with types. Fill<T, N, Start?, End?>, as you can see,Fill accepts four types of parameters, of which T and N are required parameters, and Start and End are optional parameters. The requirements for these parameters are: T must be a tupleN can be any type of value, Start and End must be integers greater than or equal to 0.

type exp = Fill<[1, 2, 3], 0> // expected to be [0, 0, 0]
type PlusOne<T extends number, C extends unknown[] = []> = C['length'] extends T
  ? [...C, unknown]['length']
  : PlusOne<T, [...C, unknown]>
type Fill<
  T extends unknown[],
  N,
  Start extends number = 0,
  End extends number = T['length'],
  P extends number = 0                                                // set a pointer, init with 0
> = Start extends End                                                 // Stop when Start = End
  ? T
  : T extends [infer F, ...infer RT] 
    ? P extends Start                  
      ? [N, ...Fill<RT, N, PlusOne<Start>, End, PlusOne<P>>]          // Replace the value when Pointer = Start, increasing value by 1
      : [F, ...Fill<RT, N, Start, End, PlusOne<P>>]                   // No need to replace F, increase P
    : [];

 

posted @   Zhentiw  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-10-26 [CSS] Use CSS Transforms to Create Configurable 3D Cuboids
2020-10-26 [CSS] Use CSS Variables Almost like Boolean Values with Calc (maintainable css)
2020-10-26 [Kotlin] Typecheck with 'is' keyword, 'as' keyword for assert type
2020-10-26 [Kotlin] When to add () and when not to
2020-10-26 [Kotlin] fold / reduce
2016-10-26 [CSS] Control Image Aspect Ratio Using CSS (object-fit)
2016-10-26 [Angular2 Form] Reactive form: valueChanges, update data model only when form is valid
点击右上角即可分享
微信分享提示