Skip to main content
added 576 characters in body
Source Link
noodle person
  • 10.3k
  • 1
  • 22
  • 76

TypeScript’s type system, 145 bytes

  
type F<S>=SF<N>=N extends[...infer S,infer D]?"0123456789abcdedghijklmnopqrstuvwxyz"extends`${any}${D&string}${infer I}${any}`?[...S,I]:[...F<S>,"0"]:S

Try it at the TS playground

This is a generic type F<N> which takes a tuple type of characters and returns a type in the same format.

Explanation:

In the input tuple type N, match the last digit D and the rest S.

N extends[...infer S,infer D]

Match 0-9a-z against: anything + D + match the next character as I + anything.

"0123456789abcdedghijklmnopqrstuvwxyz"extends`${any}${D&string}${infer I}${any}`

If the match succeeded, return S + I.

?[...S,I]

Otherwise, recurse with S as the input, and append 0.

:[...F<S>,"0"]

This isn’t tail recursive, but that’s okay because the input is guaranteed to be 10 digits and the recursion limit for non tail-recursive TS types is 50.

TypeScript’s type system, 145 bytes

 
type F<S>=S extends[...infer S,infer D]?"0123456789abcdedghijklmnopqrstuvwxyz"extends`${any}${D&string}${infer I}${any}`?[...S,I]:[...F<S>,"0"]:S

Try it at the TS playground

TypeScript’s type system, 145 bytes

 
type F<N>=N extends[...infer S,infer D]?"0123456789abcdedghijklmnopqrstuvwxyz"extends`${any}${D&string}${infer I}${any}`?[...S,I]:[...F<S>,"0"]:S

Try it at the TS playground

This is a generic type F<N> which takes a tuple type of characters and returns a type in the same format.

Explanation:

In the input tuple type N, match the last digit D and the rest S.

N extends[...infer S,infer D]

Match 0-9a-z against: anything + D + match the next character as I + anything.

"0123456789abcdedghijklmnopqrstuvwxyz"extends`${any}${D&string}${infer I}${any}`

If the match succeeded, return S + I.

?[...S,I]

Otherwise, recurse with S as the input, and append 0.

:[...F<S>,"0"]

This isn’t tail recursive, but that’s okay because the input is guaranteed to be 10 digits and the recursion limit for non tail-recursive TS types is 50.

Source Link
noodle person
  • 10.3k
  • 1
  • 22
  • 76

TypeScript’s type system, 145 bytes

type F<S>=S extends[...infer S,infer D]?"0123456789abcdedghijklmnopqrstuvwxyz"extends`${any}${D&string}${infer I}${any}`?[...S,I]:[...F<S>,"0"]:S

Try it at the TS playground