Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
utterances-bot opened this issue Feb 1, 2023 · 2 comments
Open

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

utterances-bot opened this issue Feb 1, 2023 · 2 comments

Comments

@utterances-bot
Copy link

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

Copy link

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]];

Copy link

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>]
  : ['', '', ''];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants