Created
October 26, 2020 09:22
-
-
Save nyctef/0b9fd8dc0710015e66095f6552026d0b to your computer and use it in GitHub Desktop.
Fizzbuzz in typescript (types)
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
// based on https://dev.to/gypsydave5/fizz-buzz-in-typescript-7ip (with some corrections) | |
type Z = 0; | |
type S<N> = [N]; | |
type N1 = S<Z>; | |
type N2 = S<N1>; | |
type N3 = S<N2>; | |
type N4 = S<N3>; | |
type N5 = S<N4>; | |
type N6 = S<N5>; | |
type N7 = S<N6>; | |
type N8 = S<N7>; | |
type N9 = S<N8>; | |
type N10 = S<N9>; | |
type N11 = S<N10>; | |
type N12 = S<N11>; | |
type N13 = S<N12>; | |
type N14 = S<N13>; | |
type N15 = S<N14>; | |
type Equal<Na, Nb> = { | |
0: Nb extends Z ? true : false; | |
1: { | |
0: false; | |
1: Na extends S<infer Pa> ? (Nb extends S<infer Pb> ? Equal<Pa, Pb> : never) : never; | |
}[Nb extends Z ? 0 : 1]; | |
}[Na extends Z ? 0 : 1]; | |
type LessThan<Na, Nb> = { | |
0: false; | |
1: Na extends Z | |
? true | |
: Na extends S<infer Pa> | |
? Nb extends S<infer Pb> | |
? LessThan<Pa, Pb> | |
: never | |
: never; | |
}[Nb extends Z ? 0 : 1]; | |
type IsMultipleOfThree<T> = { | |
1: true; | |
0: Ternary<LessThan<T, N3>, false, T extends S<S<S<infer P>>> ? IsMultipleOfThree<P> : false>; | |
}[Equal<T, N3> extends true ? 1 : 0]; | |
type IsMultipleOfFive<T> = { | |
1: true; | |
0: Ternary< | |
LessThan<T, N3>, | |
false, | |
T extends S<S<S<S<S<infer P>>>>> ? IsMultipleOfFive<P> : false | |
>; | |
}[Equal<T, N5> extends true ? 1 : 0]; | |
type Ternary<B, P, Q> = { | |
1: P; | |
0: Q; | |
}[B extends true ? 1 : 0]; | |
type FIZZ = "fizz"; | |
type BUZZ = "buzz"; | |
type FIZZBUZZ = "fizzbuzz"; | |
type FB<N> = Ternary< | |
IsMultipleOfThree<N>, | |
Ternary<IsMultipleOfFive<N>, FIZZBUZZ, FIZZ>, | |
Ternary<IsMultipleOfFive<N>, BUZZ, N> | |
>; | |
type Should1 = FB<N1>; | |
type ShouldFizz = FB<N3>; | |
type Should4 = FB<N4>; | |
type ShouldBuzz = FB<N5>; | |
type ShouldFizzBuzz = FB<N15>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment