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

2257 - MinusOne (explanation with other's code) #14499

Closed
baeharam opened this issue Aug 14, 2022 · 0 comments
Closed

2257 - MinusOne (explanation with other's code) #14499

baeharam opened this issue Aug 14, 2022 · 0 comments
Labels
2257 answer Share answers/solutions to a question en in English

Comments

@baeharam
Copy link

I couldn't solve so I studied @Chen0x00 's answer.

  1. To check current string is 0-9, let's define digit type.
type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
  1. To get number from string, we need array because can get length from array. This is the key of this problem. So, we need converter to convert digit type to array.
type ConvertDigitToArray<N extends Digit, DigitArray extends any[] = []>
  = `${DigitArray['length']}` extends N ? DigitArray : ConvertDigitToArray<N, [...DigitArray, 0]>;

0 can be any value because it just for length property.

  1. To express 10, 100, 1000.. digits, we need util type to multiply 10 type element.
type Multiply10<T extends any[]> = [...T, ...T, ...T, ...T, ...T, ...T, ...T, ...T, ...T, ...T];
  1. To convert number to array, let's combine above types into single util type. In this type, we use recursive typing with template literal string. At each digit, we use Multiply10 to get proper digit and conver it to digitarray to express proper number.
type ToArray<S extends string | number, T extends any[] = []>
  = `${S}` extends `${infer F}${infer L}` ? F extends Digit ? ToArray<L, [...Multiply10<T>, ...ConvertDigitToArray<F>]> : never
  : T;
  1. Finally, let's destruct number which is converted to array and compute "minus 1".
type Minus<S extends number, T extends number>
  = ToArray<S> extends [...ToArray<T>, ...infer L] ? L['length'] : 0;

type MinusOne<S extends number> = Minus<S, 1>;
@baeharam baeharam added answer Share answers/solutions to a question en in English labels Aug 14, 2022
@github-actions github-actions bot added the 2257 label Aug 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
2257 answer Share answers/solutions to a question en in English
Projects
None yet
Development

No branches or pull requests

1 participant