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 #26830

Open
JohnLi1999 opened this issue Apr 25, 2023 · 0 comments
Open

216 - Slice #26830

JohnLi1999 opened this issue Apr 25, 2023 · 0 comments
Labels
216 answer Share answers/solutions to a question en in English

Comments

@JohnLi1999
Copy link

JohnLi1999 commented Apr 25, 2023

type NumberToTuple<T extends number, U extends 1[] = []> = U['length'] extends T
  ? U
  : NumberToTuple<T, [...U, 1]>;

type Subtract<A extends number, B extends number> = NumberToTuple<A> extends [
  ...NumberToTuple<B>,
  ...infer R
]
  ? R['length']
  : 0;

type ToNonNegativeIndex<
  Index extends number,
  Length extends number
> = `${Index}` extends `-${infer AbsIndex extends number}`
  ? Subtract<Length, AbsIndex>
  : Index;

type SliceWithNonNegativeIndices<
  Arr,
  Start,
  End,
  Index extends 1[] = [],
  Result extends unknown[] = []
> = End extends Index['length']
  ? Result
  : Arr extends [infer F, ...infer R]
  ? Start extends Index['length'] | 0
    ? SliceWithNonNegativeIndices<R, 0, End, [...Index, 1], [...Result, F]>
    : SliceWithNonNegativeIndices<R, Start, End, [...Index, 1], Result>
  : [];

type Slice<
  Arr extends unknown[],
  Start extends number = 0,
  End extends number = Arr['length']
> = SliceWithNonNegativeIndices<
  Arr,
  ToNonNegativeIndex<Start, Arr['length']>,
  ToNonNegativeIndex<End, Arr['length']>
>;
@JohnLi1999 JohnLi1999 added answer Share answers/solutions to a question en in English labels Apr 25, 2023
@github-actions github-actions bot added the 216 label Apr 25, 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