Skip to content

Instantly share code, notes, and snippets.

@ljbc1994
Last active May 7, 2022 19:39
Show Gist options
  • Save ljbc1994/582d7987c7df0d73746e7fb121fa45e9 to your computer and use it in GitHub Desktop.
Save ljbc1994/582d7987c7df0d73746e7fb121fa45e9 to your computer and use it in GitHub Desktop.
Playing about with arithmetic
type Count<A, S extends 0[] = []> = A extends S['length'] ? S : Count<A, [...S, 0]>
type Increment<A> = [...Count<A>, 0]['length']
type Decrement<A> = Count<A> extends [infer A, ...infer Rest] ? Rest['length'] : A
type Add<A, B> = [...Count<A>, ...Count<B>]['length']
type Multiply<A, B, S = 0> = B extends 0 ? S : Multiply<A, Decrement<B>, Add<S, A>>
type Power<A, B, S = A> = B extends 1 ? S : Power<A, Decrement<B>, Multiply<S, A>>
type Square<A> = Power<A, 2>
type Cube<A> = Power<A, 3>
type Incremented = Increment<10>
type Decremented = Decrement<5>
type Added = Add<10, 5>
type Multiplied = Multiply<10, 5>
type Squared = Square<2>
type Cubed = Cube<2>
type Power4 = Power<5, 4>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment