• [Typescript] 97. Hard Capitalize Words


    Implement CapitalizeWords<T> which converts the first letter of each word of a string to uppercase and leaves the rest as-is.

    For example

    type capitalized = CapitalizeWords<'hello world, my friends'> // expected to be 'Hello World, My Friends'
    /* _____________ Your Code Here _____________ */
    type StringToUnion<T extends string> = T extends `${infer F}${infer R}` ? F | StringToUnion<R> : never;
    type LowerLetterUnion = StringToUnion<'abcdefghijklmnopqrstuvwxyz'>;
    type UpperLetterUnion = Uppercase<LowerLetterUnion>;
    
    type CapitalizeWords<S extends string, Prev extends string = '', ACC extends string = ''> = S extends `${infer First}${infer REST}`
      ? Uppercase<Prev> extends UpperLetterUnion                     // only symbols and space cannnot be uppercased
        ? CapitalizeWords<REST, First, `${ACC}${First}`>                // prev is char, the follow char not need to be uppercased
        : CapitalizeWords<REST, First, `${ACC}${Uppercase<First>}`>     // pre is symbol, current char should be uppercased  
      : ACC;
    
    /* _____________ Test Cases _____________ */
    import type { Equal, Expect } from '@type-challenges/utils'
    
    type cases = [
      Expect<Equal<CapitalizeWords<'foobar'>, 'Foobar'>>,
      Expect<Equal<CapitalizeWords<'FOOBAR'>, 'FOOBAR'>>,
      Expect<Equal<CapitalizeWords<'foo bar'>, 'Foo Bar'>>,
      Expect<Equal<CapitalizeWords<'foo bar hello world'>, 'Foo Bar Hello World'>>,
      Expect<Equal<CapitalizeWords<'foo bar.hello,world'>, 'Foo Bar.Hello,World'>>,
      Expect<Equal<CapitalizeWords<'aa!bb@cc#dd$ee%ff^gg&hh*ii(jj)kk_ll+mm{nn}oo|ppqq'>, 
      'Aa!Bb@Cc#Dd$Ee%Ff^Gg&Hh*Ii(Jj)Kk_Ll+Mm{Nn}Oo|PpQq'>>,
      Expect<Equal<CapitalizeWords<''>, ''>>,
    ]
  • 相关阅读:
    The specified framework 'Microsoft.NETCore.App', version '1.0.1' was not found 解决办法
    docker registry push错误“server gave HTTP response to HTTPS client”
    windows server 2016安装docker
    Opserver 初探三《服务器数据监控》
    Opserver 初探二《exceptions配置》
    Opserver 初探一《Opserver的搭建》
    centos 7 免密登录
    nginx 入门配置
    php适配器模式
    进程和线程
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16880740.html
Copyright © 2020-2023  润新知