ghaiklor / type-challenges-solutions

Solutions for the collection of TypeScript type challenges with explanations
https://ghaiklor.github.io/type-challenges-solutions/
Creative Commons Attribution 4.0 International
471 stars 56 forks source link

type-challenges-solutions/en/medium-percentage-parser #321

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

Percentage Parser

This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.

https://ghaiklor.github.io/type-challenges-solutions/en/medium-percentage-parser.html

albert-luta commented 1 year ago

I solved this similarly, but in a recursive manner

type PercentageParser<
  A extends string,
  Acc extends string[] = ["", "", ""]
> = A extends `${infer Sign extends "+" | "-"}${infer Rest}`
  ? PercentageParser<Rest, [Sign, "", ""]>
  : A extends `${infer Rest}%`
  ? PercentageParser<Rest, [Acc[0], '', "%"]>
  : [Acc[0], A, Acc[2]];
codeninja-ru commented 1 year ago
type NumParser<T extends string> = T extends `${infer N}%`
  ? [N, '%'] : [T, ''];
type PercentageParser<T extends string> = T extends `${infer PM}${infer Rest}`
  ? PM extends '+' | '-'
    ? [PM, ...NumParser<Rest>] : ['', ...NumParser<T>]
  : ['', '', ''];