Created
June 4, 2023 18:19
-
-
Save SamuelNittala/b4398fc315814b50831390ee206fc686 to your computer and use it in GitHub Desktop.
type-level palindrome
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
type FirstCharacter<T extends string> = T extends `${infer first}${infer rest}` | |
? first | |
: T; | |
type LastCharacter<T extends string> = T extends `${infer first}${infer rest}` | |
? rest extends '' | |
? first | |
: LastCharacter<rest> | |
: T; | |
type RemoveFirst<T extends string> = T extends `${infer first}${infer rest}` | |
? rest | |
: T; | |
type RemoveLast< | |
T extends string, | |
K extends string | |
> = T extends `${infer first}${infer rest}` | |
? rest extends '' | |
? K | |
: RemoveLast<rest, `${K}${first}`> | |
: T; | |
export type IsPalindrome<T extends string> = | |
T extends `${infer first}${infer rest}` | |
? rest extends '' | |
? true | |
: FirstCharacter<T> extends LastCharacter<T> | |
? IsPalindrome<`${RemoveLast<T, `${RemoveFirst<T>}`>}`> | |
: false | |
: false; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment