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

31824 - Length of String 3 #33269

Open
alexandroppolus opened this issue May 16, 2024 · 2 comments
Open

31824 - Length of String 3 #33269

alexandroppolus opened this issue May 16, 2024 · 2 comments
Labels
31824 answer Share answers/solutions to a question en in English

Comments

@alexandroppolus
Copy link

type ToInt<S> = S extends `0${infer X}` ? ToInt<X> : S extends `${infer N extends number}` ? N : 0;

type Q1 = string;
type Q10 = `${Q1}${Q1}${Q1}${Q1}${Q1}${Q1}${Q1}${Q1}${Q1}${Q1 & {}}`;
type Q100 = `${Q10}${Q10}${Q10}${Q10}${Q10}${Q10}${Q10}${Q10}${Q10}${Q10}`;
type Q1000 = `${Q100}${Q100}${Q100}${Q100}${Q100}${Q100}${Q100}${Q100}${Q100}${Q100}`;
type Q10k = `${Q1000}${Q1000}${Q1000}${Q1000}${Q1000}${Q1000}${Q1000}${Q1000}${Q1000}${Q1000}`;
type Q100k = `${Q10k}${Q10k}${Q10k}${Q10k}${Q10k}${Q10k}${Q10k}${Q10k}${Q10k}${Q10k}`;

type Len<S, Q extends string, R extends 1[] = []> = S extends `${Q}${infer T}`
  ? Len<T, Q, [...R, 1]>
  : [R['length'], S];

type LengthOfString<S extends string> = Len<S, Q100k> extends [infer A extends number, infer S1]
  ? Len<S1, Q10k> extends [infer B extends number, infer S2]
    ? Len<S2, Q1000> extends [infer C extends number, infer S3]
      ? Len<S3, Q100> extends [infer D extends number, infer S4]
        ? Len<S4, Q10> extends [infer E extends number, infer S5]
          ? Len<S5, Q1> extends [infer F extends number, string]
            ? ToInt<`${A}${B}${C}${D}${E}${F}`>
            : 0
          : 0
        : 0
      : 0
    : 0
  : 0;

Play

@alexandroppolus alexandroppolus added answer Share answers/solutions to a question en in English labels May 16, 2024
@github-actions github-actions bot added the 31824 label May 16, 2024
@teamchong
Copy link

awesome

@alexandroppolus
Copy link
Author

alexandroppolus commented May 17, 2024

@teamchong Thanks.

This is the second time I've seen the magic of string & {}
(after the autocomplete hint 'value1' | 'value2' | (string & {}) for function parameter with type string)

It should be collapse to string, but stays as it is and works crazy magic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
31824 answer Share answers/solutions to a question en in English
Projects
None yet
Development

No branches or pull requests

2 participants