[Typescript] 121. Hard - IsPalindrome

Implement type IsPalindrome<T> to check whether a string or number is palindrome.

For example:

IsPalindrome<'abc'> // false
IsPalindrome<121> // true

 

/* _____________ Your Code Here _____________ */
type Equal<T, U> = (<P>(x: P) => P extends T? 1: 2) extends (<P>(x: P) => P extends U ? 1: 2) ? true: false;
type ToArray<S extends string> = S extends `${infer First}${infer REST}` ? [First, ...ToArray<REST>]: [];
type ReverseJoin<T extends any[]> = T extends [...infer REST, infer Last] ? Last extends string ? `${Last}${ReverseJoin<REST>}` : never: '';
type IsPalindrome<T extends string | number> = Equal<`${T}`,ReverseJoin<ToArray<`${T}`>>>

/* _____________ Test Cases _____________ */
import type {  Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<IsPalindrome<'abc'>, false>>,
  Expect<Equal<IsPalindrome<'b'>, true>>,
  Expect<Equal<IsPalindrome<'abca'>, false>>,
  Expect<Equal<IsPalindrome<'abcba'>, true>>,
  Expect<Equal<IsPalindrome<121>, true>>,
  Expect<Equal<IsPalindrome<19260817>, false>>,
]

 

posted @ 2022-11-29 15:14  Zhentiw  阅读(9)  评论(0编辑  收藏  举报