DEV Community

Acid Coder
Acid Coder

Posted on

4 2

Typescript Numeric Literal Types How To X^N (Exponentiation)

In this post, we are going to try to raise x to the power of n

x and n are both numeric literal types

to do this, we need to utilize multiplication type with a slight modification:

type CreateArrayWithLengthX<
    LENGTH extends number,
    ACC extends unknown[] = [],
> = ACC['length'] extends LENGTH
    ? ACC
    : CreateArrayWithLengthX<LENGTH, [...ACC,1]>

type Multiplication<X extends number, Y extends number, Z extends number[] = [], V extends unknown[] = []> = 
    [...CreateArrayWithLengthX<Y>]['length'] extends Z['length']
    ? V // modified
    : Multiplication<X,Y,[1,...Z],[...CreateArrayWithLengthX<X>,...V]>
Enter fullscreen mode Exit fullscreen mode

ok, we have the building block now, let's do it

type Exponentiation<X extends number, N extends number, Counter extends number[] =[], Acc extends unknown[] = [1]> =
    Counter['length'] extends N 
        ? Acc['length'] 
        : Exponentiation<X, N, [1, ...Counter], Multiplication<Acc['length'],X> >

type A = Exponentiation<2,0> // 1
type B = Exponentiation<2,1> // 2
type C = Exponentiation<2,10> // 1024
type D = Exponentiation<3,7> // 2187
type E = Exponentiation<21,3> // 9261
Enter fullscreen mode Exit fullscreen mode

playground

limitation: the result cannot exceed 9999 because the max tuple size is 9999

there is also some limitation to n, depending on the value of x
if x is 2, then n cannot exceed 10 (2¹⁰ is the first time exponential of 2 exceed 1000)

if x is 3, then n cannot exceed 7 (3⁷ is the first time exponential of 3 exceed 1000)

at this point, x^n is larger than 1000 and it is not possible to create an array with a length larger than 1000 for the next n because the max recursion depth is only 1000

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
juliocastrodev profile image
juliocastrodev

This is impressive :o

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay