Skip to content

Instantly share code, notes, and snippets.

@SamuelNittala
Created June 4, 2023 18:19
Show Gist options
  • Save SamuelNittala/b4398fc315814b50831390ee206fc686 to your computer and use it in GitHub Desktop.
Save SamuelNittala/b4398fc315814b50831390ee206fc686 to your computer and use it in GitHub Desktop.
type-level palindrome
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