Last active
April 5, 2024 20:26
-
-
Save nopeless/fce933df4b36b4fde9b79d127af49940 to your computer and use it in GitHub Desktop.
static prime checking using typescript types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Prime checking regex, which this code is based off of | |
// https://regex101.com/r/RIJkGF/1 | |
type StringDivisible<n extends string, div extends string> = n extends `` ? true : n extends `${div}${infer r}` ? StringDivisible<r, div> : false; | |
type Substrings<n extends string, d extends string = ""> = n extends `${d}${infer r}` ? readonly [` ${d}`, ...Substrings<r, ` ${d}`>] : readonly []; | |
type StringFactors<n extends string> = Substrings<n> extends readonly [unknown, ...infer R extends readonly string[], unknown] ? R : never; | |
type StringIsPrime<n extends string, Factors extends readonly string[] = StringFactors<n>> = Factors extends readonly [infer s extends string, ...infer R extends readonly string[]] ? StringDivisible<n, s> extends true ? false : StringIsPrime<n, R> : true; | |
type RepeatStringByStringDigit<str extends string, d extends string> = | |
d extends `0` ? "" | |
: d extends `1` ? `${str}` | |
: d extends `2` ? `${str}${str}` | |
: d extends `3` ? `${str}${str}${str}` | |
: d extends `4` ? `${str}${str}${str}${str}` | |
: d extends `5` ? `${str}${str}${str}${str}${str}` | |
: d extends `6` ? `${str}${str}${str}${str}${str}${str}` | |
: d extends `7` ? `${str}${str}${str}${str}${str}${str}${str}` | |
: d extends `8` ? `${str}${str}${str}${str}${str}${str}${str}${str}` | |
: d extends `9` ? `${str}${str}${str}${str}${str}${str}${str}${str}${str}` | |
: string; | |
type _mul10<str extends string> = `${str}${str}${str}${str}${str}${str}${str}${str}${str}${str}`; | |
type digits = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"; | |
type pow10fromstr<s extends string> = s extends `${infer _}${infer r}` ? _mul10<pow10fromstr<r>> : ' ' | |
type _NumberStrConversion<n extends string> = n extends `${infer i}${infer trail}` ? `${RepeatStringByStringDigit<pow10fromstr<trail>, i>}${_NumberStrConversion<trail>}` : `` | |
type NumberToStringOfLength<n extends number> = _NumberStrConversion<`${n}`>; | |
type NumberIsPrime<n extends number> = StringIsPrime<NumberToStringOfLength<n>>; | |
type answer = NumberIsPrime<42>; // false | |
// ^? | |
type answer2 = NumberIsPrime<607>; // true | |
// ^? |
nice, but is there any practical use?
no
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice, but is there any practical use?