TypeScript 杂记九 《Integers Comparator》
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>
type Test11 = Comparator<1, -2222>
type Test111 = Comparator<-1, -2>
type Test2 = Comparator<1_000_000_000_000n, 1_000_000_000_000n>
type Test3 = Comparator<1_000_000_000_000n, 1_000_000_000_001n>
type Test4 = Comparator<1_000_000_000_100n, 1_000_000_000_001n>
type Test5 = Comparator<-1_000_000_000_100n, -1_000_000_000_001n>
|