首页 > 其他分享 >[Typescript] 45. Medium - MinusOne (Solution to solve max number of iteration by tail call)

[Typescript] 45. Medium - MinusOne (Solution to solve max number of iteration by tail call)

时间:2022-10-07 23:13:02浏览次数:90  
标签:Typescript _____________ max 45 length MinusOne Expect extends type

Just for fun...

Given a number (always positive) as a type. Your type should return the number decreased by one.

For example:

type Zero = MinusOne<1> // 0
type FiftyFour = MinusOne<55> // 54

 

/* _____________ Your Code Here _____________ */
type Tuple<L extends number, T extends unknown[] = []> = T["length"] extends L
  ? T
  : Tuple<L, [...T, unknown]>;
type MinusOne<T extends number> = Tuple<T> extends [...infer L, unknown]
  ? L["length"]
  : never;

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

type cases = [
  Expect<Equal<MinusOne<1>, 0>>,
  Expect<Equal<MinusOne<55>, 54>>,
  Expect<Equal<MinusOne<3>, 2>>,
  Expect<Equal<MinusOne<100>, 99>>,
  Expect<Equal<MinusOne<1101>, 1100>>, // won't work
]

 

For `Tuple<L>`, we need adding `unknown` into tuple, until the length of tuple is the same as `L`.

For `MinusOne<L>`, using `Tuple` to accumate the tuple length, then sub one get result.

 

But the solution has one problem, the number of iterlation might crash the compiler. 

In function programming, there is a technique called tail call. See this post: https://www.cnblogs.com/Answer1215/p/16598616.html

Trampolines is the solution idea to solve the problem. basicly wrap function into another function, inside wrapper, keep calling original function. But since everytime calling the orignial function return a new function, the callstack will be free (size will be 1 or 0), never increase. That solve the max number iteration problem.

In the Type, we can do the magic by add to the begining:

0 extends 1 ? never: <...rest of the code>

/* _____________ Your Code Here _____________ */
type Tuple<L extends number, T extends unknown[] = []> = 0 extends 1 ? never: T["length"] extends L
  ? T
  : Tuple<L, [...T, unknown]>;
type MinusOne<T extends number> = Tuple<T> extends [...infer L, unknown]
  ? L["length"]
  : never;

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

type cases = [
  Expect<Equal<MinusOne<1>, 0>>,
  Expect<Equal<MinusOne<55>, 54>>,
  Expect<Equal<MinusOne<3>, 2>>,
  Expect<Equal<MinusOne<100>, 99>>,
  Expect<Equal<MinusOne<1101>, 1100>>, // works
]

 

Solution 2: 

type MinusOne<T extends number, ARR extends unknown[] = []> = any extends never ? never: [...ARR, 1]['length'] extends T ? ARR['length'] : MinusOne<T, [...ARR, 1]>

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

type cases = [
  Expect<Equal<MinusOne<1>, 0>>,
  Expect<Equal<MinusOne<55>, 54>>,
  Expect<Equal<MinusOne<3>, 2>>,
  Expect<Equal<MinusOne<100>, 99>>,
  Expect<Equal<MinusOne<1101>, 1100>>,
]

 

Refer: https://github.com/microsoft/TypeScript/issues/49459

标签:Typescript,_____________,max,45,length,MinusOne,Expect,extends,type
From: https://www.cnblogs.com/Answer1215/p/16767460.html

相关文章

  • 【CMU15-445 Project #2】B+Tree
    Checkpoint#1task#1二分查找[K0,V0(pre_page)][K1,V1]....[Kn,Vn][next_page]在[K1,V1]...[Kn,Vn]中找到第一个大于等于key值的编号i使得,key<=......
  • jira项目笔记14-TypeScript vs JavaScript
    TypeScriptvsJavaScriptTypeScript是“强类型”版的JavaScript,当我们在代码中定义变量(包括普通变量、函数、组件、hook等)的时候,TypeScript允许我们在定义的同......
  • jira项目笔记15-TypeScript 的类型
    TypeScript的类型 8种类型:number,string,boolean,函数,array,any,void,object这一节我们接触到了平常使用中会接触到的大部分的类型,下面我们挨个梳理一遍:numbe......
  • 【译】适用于Node.js和TypeScript的完整ORM —— Prisma
    翻译自:www.prisma.io/blogPrisma是Node.js和TypeScript的下一代ORM。经过两年多的开发,我们很高兴分享所有Prisma工具已准备好投入生产!一个对象关系映射的新范例Prism......
  • [Typescript + React] Tip: Use generics in React to make dynamic and flexible com
    YoucanusegenericsinReacttomakeincrediblydynamic,flexiblecomponents.Here,ImakeaTablecomponentwithageneric'items'type.interfaceTableProp......
  • 仿真之路-模型建立3-jcmaxx33
    信念:输入能力磁性材料特性和熟练的建模输出电磁仿真之路的拦路虎,实体模型建立,重新拾起SOLIDWORKS,每日一练! ......
  • [Typescript] 44. Medium - Drop char
    Dropaspecifiedcharfromastring.Forexample:typeButterfly=DropChar<'butterfly!',''>//'butterfly!' /*_____________YourCodeHere......
  • 「牛客网」45道JS能力测评经典题总结
    前言牛客网的45道JS能力评测题个人觉得是非常好的45道js基础检测题,基本就是对自己的JavaScript基础做一个比较全面的评估,包括if语句、循环体、基础操作符、setInterval、s......
  • TypeScript
    学习文档:https://www.runoob.com/typescript/ts-tutorial.htmlTypeScript是JavaScript的一个超集(js的扩展),支持ECMAScript6标准1.安装使用国内镜像:npmconfigset......
  • Maximum Deletions on a String
    MaximumDeletionsonaStringYouaregivenastring s consistingofonlylowercaseEnglishletters.Inoneoperation,youcan:Deletetheentirestring s......