UNPKG

2.28 kBTypeScriptView Raw
1import type { TypedArray } from "./typedarray.js";
2/**
3 * Returns an array's value type. Assumes array is homogeneous (only type of
4 * first element will be considered).
5 */
6export type ArrayValue<T extends unknown[]> = T[0];
7/**
8 * Somewhat similar, but recursive version of {@link ArrayValue}. If `T` is an
9 * array/typedarray recursively descends into it or (if not an array) returns
10 * `T`. Assumes arrays at each level are homogeneous (only type of first
11 * elements will be considered).
12 */
13export type DeepArrayValue<T> = T extends unknown[] ? DeepArrayValue<T[0]> : T extends TypedArray ? number : T;
14/**
15 * Defines a fixed sized, iterable tuple with elements of type `T` and
16 * length `N`.
17 */
18export type Tuple<T, N extends number> = [T, ...T[]] & {
19 length: N;
20} & Iterable<T>;
21/**
22 * Extracts a tuple's length / size.
23 */
24export type TupleLength<T extends unknown[]> = T["length"];
25/**
26 * Returns 1 if T is empty tuple, else 0
27 */
28export type IsEmpty<T extends unknown[]> = T extends [] ? 1 : 0;
29/**
30 * Extracts the first element of a tuple.
31 */
32export type Head<T extends unknown[]> = T extends [infer A, ...unknown[]] ? A : never;
33/**
34 * Extracts everything except the first element from a tuple.
35 */
36export type Tail<T extends unknown[]> = T extends [unknown, ...infer A] ? A : never;
37/**
38 * Adds an element at the start of an tuple.
39 */
40export type Prepend<T, U extends unknown[]> = [T, ...U];
41/**
42 * Internal version of {@link Reverse} accepting 1 extra argument for
43 * the accumulated value.
44 */
45type ReverseReducer<T extends unknown[], C extends unknown[]> = {
46 0: C;
47 1: Prepend<Head<T>, C>;
48 2: ReverseReducer<Tail<T>, Prepend<Head<T>, C>>;
49}[Tail<T> extends [] ? (Head<T> extends never ? 0 : 1) : 2];
50/**
51 * Reverses the order of elements from a tuple.
52 */
53export type Reverse<T extends unknown[]> = ReverseReducer<T, []>;
54/**
55 * Extracts the last element from a tuple.
56 */
57export type Last<T extends unknown[]> = {
58 0: Last<Tail<T>>;
59 1: Head<T>;
60}[IsEmpty<Tail<T>>];
61/**
62 * Extracts everything except the last element from a tuple.
63 */
64export type ButLast<T extends unknown[], C extends unknown[] = []> = {
65 0: ButLast<Tail<T>, Prepend<Head<T>, C>>;
66 1: Reverse<C>;
67}[IsEmpty<Tail<T>>];
68export {};
69//# sourceMappingURL=tuple.d.ts.map
\No newline at end of file