[Typescript] 45. Medium - MinusOne (Solution to solve max number of iteration by tail call)
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>>,
]