Last active
April 7, 2022 13:00
-
-
Save Grubba27/86caf877c03376ca8b7c87460fc6bfb0 to your computer and use it in GitHub Desktop.
Simple power made with types in TS
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
// Multiplication comes from this issue: https://github.com/type-challenges/type-challenges/issues/5814 | |
type Reverse<A> = | |
`${A}` extends `${infer AH}${infer AT}` | |
? `${Reverse<AT>}${AH}` : A | |
type Digs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
type DigsNext<I = Digs, R = {}> = | |
I extends [infer Head, infer Next, ...infer Tail] | |
? DigsNext<[Next, ...Tail], R & Record<Head, Next>> | |
: { [K in keyof R]: R[K] } | |
type DigsPrev = { [K in keyof DigsNext as DigsNext[K]]: K } | |
type AddOne<A> = | |
A extends `${infer AH}${infer AT}` | |
? AH extends '9' ? `0${AddOne<AT>}` : `${DigsNext[AH]}${AT}` | |
: `1` | |
type SubOne<A> = | |
A extends `${infer AH}${infer AT}` | |
? AH extends '0' ? `9${SubOne<AT>}` : `${DigsPrev[AH]}${AT}` | |
: never | |
type Add<A, B> = | |
A extends `${infer AH}${infer AT}` ? | |
B extends `${infer BH}${infer BT}` | |
? BH extends '0' ? `${AH}${Add<AT, BT>}` : Add<AddOne<A>, SubOne<B>> | |
: A : B | |
type Mul<A, B, R = '0'> = | |
A extends '0' ? R : | |
B extends '0' ? R : | |
A extends `${infer AH}${infer AT}` | |
? AH extends '0' ? Mul<AT, `0${B}`, R> : Mul<SubOne<A>, B, Add<R, B>> | |
: R | |
type Multiply<A extends string | number | bigint, B extends string | number | bigint> = | |
Reverse<Mul<Reverse<A>, Reverse<B>>> | |
type Power< | |
V extends string, | |
P extends string, | |
A extends string = V> = | |
P extends '1' | |
? A | |
: P extends '0' | |
? '1' | |
: Power<V, SubOne<P>, Multiply<V, A>> | |
const $: Power<'2', '4'> = "16"; | |
const _: Power<'2', '3'> = "8"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment