TypeScript 杂记九 《Integers Comparator》
Posted 左手121
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TypeScript 杂记九 《Integers Comparator》相关的知识,希望对你有一定的参考价值。
TypeScript 杂记九 《Integers Comparator》
思路
参考这篇文章中的思路:TypeScript 杂记五 《Sort》
完整示例
type Reverser<T> = T extends 1 ? -1 : T extends 0 ? 0 : 1
type StringToArray<T extends string, RR extends string[] = []> = T extends `$infer L$infer R`
? StringToArray<R, [...RR, L]>
: RR
type Compare<A, B, H extends unknown[] = []> = `$H['length']` extends A
? `$H['length']` extends B
? 0
: -1
: `$H['length']` extends B
? 1
: Compare<A, B, [...H, unknown]>
type CompareArrayHelper<A, B> = A extends [infer AL, ...infer AR]
? B extends [infer BL, ...infer BR]
? Compare<AL, BL> extends 0
? CompareArrayHelper<AR, BR>
: Compare<AL, BL>
: 0
: 0
type CompareArray<
A extends string[],
B extends string[],
H extends unknown[] = [],
> = H['length'] extends A['length']
? H['length'] extends B['length']
? CompareArrayHelper<A, B>
: -1
: H['length'] extends B['length']
? 1
: CompareArray<A, B, [...H, unknown]>
type ComparatorHelper<A extends string, B extends string> = A extends `-$infer _A`
? B extends `-$infer _B`
? Reverser<CompareArray<StringToArray<_A>, StringToArray<_B>>>
: -1
: B extends `-$string`
? 1
: CompareArray<StringToArray<A>, StringToArray<B>>
type Comparator<A extends number | bigint, B extends number | bigint> = ComparatorHelper<
`$A`,
`$B`
> extends 1
? Comparison.Greater
: ComparatorHelper<`$A`, `$B`> extends 0
? Comparison.Equal
: Comparison.Lower
测试
type Test1 = Comparator<1, 2> // Comparison.Lower
type Test11 = Comparator<1, -2222> // Comparison.Greater
type Test111 = Comparator<-1, -2> // Comparison.Greater
type Test2 = Comparator<1_000_000_000_000n, 1_000_000_000_000n> // Comparison.Equal
type Test3 = Comparator<1_000_000_000_000n, 1_000_000_000_001n> // Comparison.Lower
type Test4 = Comparator<1_000_000_000_100n, 1_000_000_000_001n> // Comparison.Greater
type Test5 = Comparator<-1_000_000_000_100n, -1_000_000_000_001n> // Comparison.Lower
以上是关于TypeScript 杂记九 《Integers Comparator》的主要内容,如果未能解决你的问题,请参考以下文章