[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 @   Zhentiw  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-11-29 [Java Srping] @RestController and @Controller
2020-11-29 [Java Spring] Testing a view controller
2019-11-29 [Algorithm] BFS vs DFS
2017-11-29 [ES2017] Iterate over properties of an object with ES2017 Object.entries()
2016-11-29 [Elm] Installing and setting up Elm
2016-11-29 [Node.js] Use nodejs-dashboard event loop delay with hrtime()
2015-11-29 [Javascript] Introducing Reduce: Common Patterns
点击右上角即可分享
微信分享提示