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

216 - Slice #22018

Open
thanhhtse04588 opened this issue Jan 13, 2023 · 0 comments
Open

216 - Slice #22018

thanhhtse04588 opened this issue Jan 13, 2023 · 0 comments
Labels
216 answer Share answers/solutions to a question en in English

Comments

@thanhhtse04588
Copy link

type Subtraction<
  A extends number,
  B extends number,
  AArray extends unknown[] = LengthToArray<A>,
  BArray extends unknown[] = [],
> = BArray['length'] extends B
  ? AArray['length']
  : AArray extends [infer F, ...infer R]
    ? Subtraction<A, B, R, [...BArray, F]>
    : 'A must greater than B'

type SliceWithPositiveNumber<
  Arr extends number[],
  Start = 0,
  End = Arr['length'],
  Left extends unknown[] = [],
  T extends unknown[] = [],
> = Arr extends [infer F, ...infer R extends number[]]
  ? Start extends number
    ? GreaterThan<Start, Left['length']> extends true
      ? SliceWithPositiveNumber<R, Start, End, [...Left, F]>
      : End extends number
        ? GreaterThan<End, Left['length']> extends true
          ? SliceWithPositiveNumber<R, Start, End, [...Left, F], [...T, F]>
          : T
        : never
    : never
  : T

  type Slice<
    Arr extends number[],
    Start extends number = 0,
    End extends number = Arr['length'],
    Length extends number = Arr['length'],
  > = SliceWithPositiveNumber<
    Arr,
    `${Start}` extends `-${infer S extends number}`
      ? Subtraction<Length, S>
      : Start,
    `${End}` extends `-${infer E extends number}`
      ? Subtraction<Length, E>
      : End
  >
@thanhhtse04588 thanhhtse04588 added answer Share answers/solutions to a question en in English labels Jan 13, 2023
@github-actions github-actions bot added the 216 label Jan 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
216 answer Share answers/solutions to a question en in English
Projects
None yet
Development

No branches or pull requests

1 participant