Skip to content

Commit

Permalink
Type magic
Browse files Browse the repository at this point in the history
  • Loading branch information
butzopower committed Jan 2, 2022
1 parent c949496 commit 5b2cba9
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/dice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { type Add } from './math';

export type D<T extends number> = number extends T ? number :_D<T, []>;
type _D<T extends number, R extends number[]> = R['length'] extends T ?
R[number] :
_D<T, [...R, Add<R['length'], 1>]>;

export interface Dice<T extends number> {
roll(): D<T>
}
26 changes: 26 additions & 0 deletions src/math.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export type Add<N extends number, AmountToAdd extends number> = _Add<N, AmountToAdd, [], []>;
type _Add<
N extends number,
AmountToAdd extends number,
LeftAmount extends unknown[],
RightAmount extends unknown[]
> =
LeftAmount['length'] extends N ?
RightAmount['length'] extends AmountToAdd ?
[...LeftAmount, ...RightAmount]['length'] :
_Add<N, AmountToAdd, LeftAmount, [unknown, ...RightAmount]> :
_Add<N, AmountToAdd, [unknown, ...LeftAmount], []>

export type Sub<N extends number, AmountToSub extends number> = _Sub<N, AmountToSub, [], [], []>;
type _Sub<
N extends number,
AmountToSub extends number,
Take extends unknown[],
Left extends unknown[],
All extends unknown[],
> =
All['length'] extends N ?
Left['length'] :
Take['length'] extends AmountToSub ?
_Sub<N, AmountToSub, Take, [unknown, ...Left], [unknown, ...All]>:
_Sub<N, AmountToSub, [unknown, ...Take], [], [unknown, ...All]>;

0 comments on commit 5b2cba9

Please sign in to comment.