首页 > 其他分享 >[Typescript] 67. Medium - Chunk

[Typescript] 67. Medium - Chunk

时间:2022-10-25 03:33:05浏览次数:48  
标签:ACC Typescript _____________ Chunk Medium extends Expect type

Do you know lodashChunk is a very useful function in it, now let's implement it. Chunk<T, N> accepts two required type parameters, the T must be a tuple, and the N must be an integer >=1

 
type exp1 = Chunk<[1, 2, 3], 2> // expected to be [[1, 2], [3]]
type exp2 = Chunk<[1, 2, 3], 4> // expected to be [[1, 2, 3]]
type exp3 = Chunk<[1, 2, 3], 1> // expected to be [[1], [2], [3]]

 

/* _____________ Your Code Here _____________ */

type Chunk<T extends any[], U extends number, ACC extends any[]= []> = ACC['length'] extends U 
  ? [ACC, ...Chunk<T, U>]
  : T extends [infer F, ...infer RT]
    ? Chunk<RT, U, [...ACC, F]>
    : ACC['length'] extends 0 
      ? []
      : [ACC];

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

type cases = [
  Expect<Equal<Chunk<[], 1>, []>>,
  Expect<Equal<Chunk<[1, 2, 3], 1>, [[1], [2], [3]]>>,
  Expect<Equal<Chunk<[1, 2, 3], 2>, [[1, 2], [3]]>>,
  Expect<Equal<Chunk<[1, 2, 3, 4], 2>, [[1, 2], [3, 4]]>>,
  Expect<Equal<Chunk<[1, 2, 3, 4], 5>, [[1, 2, 3, 4]]>>,
  Expect<Equal<Chunk<[1, true, 2, false], 2>, [[1, true], [2, false]]>>,
]

 

标签:ACC,Typescript,_____________,Chunk,Medium,extends,Expect,type
From: https://www.cnblogs.com/Answer1215/p/16823663.html

相关文章

  • [Typescript] TypeScript module Augmentation
    Youmighthavesomechangeslocallyfor3rdpartylibrary.Forthelocalimplementation,youneedtomodifythetypesinordertoresolveIDEissue. Whenme......
  • Typescript类型体操 - Trunc
    题目中文实现类型版本的Math.trunc,其接受一个字符串或数字作为泛型参数,并返回移除了全部小数位部分后的整数示例:typeA=Trunc<12.34>;//12EnglishImpleme......
  • Typescript类型体操 - TrimRight
    题目中文实现TrimRight<T>,它接收确定的字符串类型并返回一个新的字符串,其中新返回的字符串删除了原字符串结尾的空白字符串。例如typeTrimed=TrimRight<'Hello......
  • TypeScript 高级类型
    一、高级类型class类型兼容性交叉类型泛型和keyof索引签名类型和索引查询类型映射类型二、class构造函数给变量赋值extends继承implement实现接口//感叹......
  • React-hooks+TypeScript最佳实战
    ReactHooks什么是HooksReact一直都提倡使用函数组件,但是有时候需要使用state或者其他一些功能时,只能使用类组件,因为函数组件没有实例,没有生命周期函数,只有类组件才......
  • TypeScript 官方文档(中文版)All In One
    TypeScript官方文档(中文版)AllInOneTypeScripthandbook/TypeScript手册https://www.typescriptlang.org/zh/docs/handbook/intro.htmlhttps://www.typescriptla......
  • 那些你不知道的Typescript面试题
    1.面试官:说说你对TypeScript中类的理解?应用场景?一、是什么类(Class)是面向对象程序设计(OOP,Object-OrientedProgramming)实现信息封装的基础类是一种用户定义的引用数据类型,......
  • Typescript类型体操 - Fill
    题目中文Fill是javascript中常用的方法,现在让我实现类型版本的FillFill<T,N,Start?,End?>,正如你看到的那样,Fill接受四个泛型参数,其中T和N是必填参数,......
  • Typescript类型体操 - Chunk
    题目中文你知道lodash吗?lodash中有一个非常实用的方法Chunk,让我们实现它吧.Chunk<T,N>接受两个泛型参数,其中T是tuple类型,N是大于1的数字typeexp1=......
  • Typescript类型体操 - GreaterThan
    题目中文在本挑战中,你需要实现GreaterThan<T,U>,它的作用像T>U你不需要考虑负数示例:GreaterThan<2,1>//shouldbetrueGreaterThan<......