Skip to content

Instantly share code, notes, and snippets.

@mst-mkt
Last active February 14, 2024 07:02
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mst-mkt/001a5bc70569b81cc74c578430aa55fb to your computer and use it in GitHub Desktop.
Save mst-mkt/001a5bc70569b81cc74c578430aa55fb to your computer and use it in GitHub Desktop.
TypeScriptの型で世界のナベアツ
type Natural = 0[];
type Zero = [];
type One = [0];
type AhoSuffix = '(アホ)';
type Length<Array extends unknown[]> = Extract<Array['length'], number>;
type Add<N1 extends Natural, N2 extends Natural> = [...N1, ...N2];
type AddNum<N1 extends number, N2 extends number> = Length<[...NumToNat<N1>, ...NumToNat<N2>]>;
type Sub<N1 extends Natural, N2 extends Natural> = N1 extends [...N2, ...infer M]
? M
: never;
type IsStrictlySmaller<N1 extends Natural, N2 extends Natural> = Sub<N1, N2> extends never
? true
: false;
type IsDivisible<N1 extends Natural, N2 extends Natural> = N1 extends Zero
? true
: IsStrictlySmaller<N1, N2> extends true
? false
: IsDivisible<Sub<N1, N2>, N2>;
type NatToNum<N extends Natural> = Length<N>;
type NumToNat<N extends number, M extends Natural = []> = Length<M> extends N
? M
: NumToNat<N, Add<M, One>>;
type IsIncludeThree<N extends number> = `${N}` extends `${infer _N}${3}${infer _M}`
? true
: false;
type IsMultipleOfThree<N extends number> = IsDivisible<NumToNat<N>, NumToNat<3>>;
type IsAho<N extends number> = IsIncludeThree<N> extends true
? true
: IsMultipleOfThree<N> extends true
? true
: false;
type Aho<N extends number> = IsAho<N> extends true
? `${N}${AhoSuffix}`
: `${N}`;
type AhoRange<L extends number, Result extends string[] = []> = Length<Result> extends L
? Result
: AhoRange<L, [...Result, Aho<AddNum<Length<Result>, 1>>]>
type Aho1 = Aho<1>; // '1'
type Aho3 = Aho<3>; // '3(アホ)'
type Aho5 = Aho<5>; // '5'
type Aho9 = Aho<9>; // '9(アホ)'
type Aho10 = Aho<10>; // '10'
type Aho13 = Aho<13>; // '13(アホ)'
type Aho1_50 = AhoRange<50>;
// ['1', '2', '3(アホ)', '4', '5', '6(アホ)', '7', '8', '9(アホ)', '10', '11', '12(アホ)', '13(アホ)', '14', '15(アホ)', '16', '17', '18(アホ)', '19', '20', '21(アホ)', '22', '23(アホ)', '24(アホ)', '25', '26', '27(アホ)', '28', '29', '30(アホ)', '31(アホ)', '32(アホ)', '33(アホ)', '34(アホ)', '35(アホ)', '36(アホ)', '37(アホ)', '38(アホ)', '39(アホ)', '40', '41', '42(アホ)', '43(アホ)', '44', '45(アホ)', '46', '47', '48(アホ)', '49', '50']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment