Skip to content

Commit

Permalink
feat(api): add Drop, TupleLength, update Tuple
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 21, 2020
1 parent ad858fb commit dc79324
Showing 1 changed file with 36 additions and 5 deletions.
41 changes: 36 additions & 5 deletions packages/api/src/api/tuple.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
export type Tuple<T, N extends number> = [T, ...T[]] & { length: N };
/**
* Defines a fixed sized, iterable tuple with elements of type `T` and
* length `N`.
*/
export type Tuple<T, N extends number> = [T, ...T[]] & { length: N } & Iterable<
T
>;

/**
* @deprecated merged w/ {@link Tuple}
*/
export type IterableTuple<T, N extends number> = Tuple<T, N> & Iterable<T>;

/**
* Extracts a tuple's length / size.
*/
export type TupleLength<T extends unknown[]> = T["length"];

/**
* Extracts the first element of a tuple.
*/
Expand All @@ -22,14 +36,15 @@ export type Tail<T extends unknown[]> = ((...a: T) => void) extends (
: never;

/**
* Add an element at the start of an tuple.
* Adds an element at the start of an tuple.
*/
export type Prepend<T, U extends unknown[]> = Parameters<
(v: T, ...args: U) => void
>;

/**
* Internal version of Reverse accepting 1 extra argument for the accumulated value.
* Internal version of {@link Reverse} accepting 1 extra argument for
* the accumulated value.
*/
type ReverseReducer<T extends unknown[], C extends unknown[] = []> = {
// case when we got 0 elements
Expand All @@ -53,13 +68,15 @@ export type Reverse<T extends unknown[]> = ReverseReducer<T>;
* Extracts the last element from a tuple.
*/
export type Last<T extends unknown[]> = {
// We need to use this trick to get around typescripts recursive type limit.
// We need to use this trick to get around typescripts recursive
// type limit.
0: Head<T>;
1: Last<Tail<T>>;
}[Tail<T> extends [] ? 0 : 1];

/**
* Internal version of ButLast accepting 1 extra argument for the accumulated value.
* Internal version of {@link ButLast} accepting 1 extra argument for
* the accumulated value.
*/
type ButLastReducer<T extends unknown[], C extends unknown[] = []> = {
0: Reverse<C>;
Expand All @@ -70,3 +87,17 @@ type ButLastReducer<T extends unknown[], C extends unknown[] = []> = {
* Extracts everything except the last element from a tuple.
*/
export type ButLast<T extends unknown[]> = ButLastReducer<T>;

/**
* Internal version of {@link Drop} accepting 1 extra argument for the
* accumulated value.
*/
type DropReducer<T extends unknown[], C extends unknown[] = []> = {
0: C;
1: DropReducer<Prepend<Head<T>, C>, Tail<T>>;
}[Tail<T> extends [] ? 0 : 1];

/**
* Extracts everything except the first element from a tuple.
*/
export type Drop<T extends unknown[]> = DropReducer<T>;

0 comments on commit dc79324

Please sign in to comment.