Created
April 7, 2022 06:04
-
-
Save hamzakaya/d341481b5dfac99537dbfe354faa6d81 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type BubbleSort< | |
A extends any[], | |
Curr extends number = A["length"] | |
> = Curr extends 1 | |
? A | |
: A extends [infer F, infer S, ...infer Rest] | |
? BubbleSort< | |
[ | |
...(Math.Comparator<Math.Num<F>, Math.Num<S>> extends true | |
? [S, ...BubbleSort<[F, ...Rest], Math.Sub<Curr, 1>>] | |
: [F, ...BubbleSort<[S, ...Rest], Math.Sub<Curr, 1>>]) | |
], | |
Math.Sub<Curr, 1> | |
> | |
: never; | |
type Demo1 = BubbleSort<[9, 8, 2, 6, 5, 4, 1]>; | |
// ^? type Demo1 = [1, 2, 4, 5, 6, 8, 9] | |
type Demo2 = BubbleSort<[234, 43, 55, 63, 5, 6, 235, 547]>; | |
// ^? type Demo2 = [5, 6, 43, 55, 63, 234, 235, 547] | |
// Math Utils | |
namespace Math { | |
export type Num<T> = Extract<T, number>; | |
type Length<T extends any[]> = T["length"]; | |
type Push<T extends any[], Val> = [...T, Val]; | |
type NTuple<N extends number, T extends any[] = []> = T["length"] extends N | |
? T | |
: NTuple<N, Push<T, any>>; | |
export type Add<A extends number, B extends number> = Length< | |
[...NTuple<A>, ...NTuple<B>] | |
>; | |
export type Sub<A extends number, B extends number> = NTuple<A> extends [ | |
...infer U, | |
...NTuple<B> | |
] | |
? Length<U> | |
: never; | |
export type Comparator<N1 extends number, N2 extends number> = N1 extends N2 | |
? false | |
: [Sub<N2, N1>] extends [never] | |
? true | |
: false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment