type-challenges / type-challenges

Collection of TypeScript type challenges with online judge
https://tsch.js.org/
MIT License
43.28k stars 4.69k forks source link

8640 - Number Range #9988

Open PorkSashimi opened 2 years ago

PorkSashimi commented 2 years ago
type Utils<L, C extends any[] = [], R = L> = 
  C['length'] extends L
      ? R
      : Utils<L, [...C, 0], C['length'] | R>

type NumberRange<L, H> = L | Exclude<Utils<H>, Utils<L>>
Sophiekx commented 9 months ago
type NumberRange<T extends number, U extends number, RZ extends any[] = [], IsInRange extends boolean = false> = RZ['length'] extends U
    ? RZ[number]
    : RZ['length'] extends MinusOne<T> 
        ? NumberRange<T, U, [...RZ, U], true> 
        : IsInRange extends true 
            ? NumberRange<T, U, [...RZ, RZ['length']], IsInRange> 
            : NumberRange<T, U, [...RZ, never], IsInRange>
zhandeze commented 4 months ago
type NewArray<T, U extends any[] = []> = U['length'] extends T ? U : NewArray<T, [...U, U['length']]>;
type NumberRange<L, H> = NewArray<H> extends [...NewArray<L>, ...infer R] ? [...R, H][number] : never;
cin12211 commented 3 months ago
type ConstructTuple<
  L extends number,
  A extends any[] = []
> = A["length"] extends L ? A : ConstructTuple<L, [unknown, ...A]>;

// type foo = ConstructTuple<3> -> // [unknown,unknown,unknown]

type NumberRange<
  L extends number,
  H,
  U extends number = L,
  F extends any[] = ConstructTuple<L>
> = F["length"] extends H
  ? U | H
  : NumberRange<L, H, U | F["length"], [unknown, ...F]>;
2083335157 commented 3 days ago
type NumberRange<L, H, R extends unknown[] = []> = H extends R[0] ? R[number] : L extends R['length'] ? NumberRange<[any, ...R]['length'], H, [R['length'], ...R]> : NumberRange<L, H, [never, ...R]>