Typescript Numeric Literal Types Y / X (Division)

In the last post we know multiplication is possible

In this post we are going to try division

type CreateArrayWithLengthX<
LENGTH extends number,
ACC extends unknown[] = [],
> = ACC['length'] extends LENGTH
? ACC
: CreateArrayWithLengthX<LENGTH, [...ACC,1]>
type Division<Dividend extends number, Divisor extends number, ACC extends unknown[] = [], Counter extends unknown[] = []> =
[...ACC,...CreateArrayWithLengthX<Divisor>]['length'] extends [...CreateArrayWithLengthX<Dividend>]['length']
? [1,...Counter]['length']
: Division<Dividend, Divisor, [...ACC,...CreateArrayWithLengthX<Divisor>],[1,...Counter]>
type result = Division<999, 3> // 333

playground

limitation: the dividend cannot exceed 999 because the max depth of TS recursion is only 1000, only work with positive integer. the divisor must be factors of the dividend

--

--

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Acid Coder

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)