Last active
August 22, 2023 09:29
-
-
Save sebinsua/5441536ac5bbbce444f44c8f57d8fb8e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Zipped<A extends readonly (readonly any[])[]> = { | |
[RowIndex in keyof A[0]]: RowIndex extends "length" ? number : { | |
[ArrayIndex in keyof A]: A[ArrayIndex] extends readonly any[] ? A[ArrayIndex][RowIndex] : never; | |
}; | |
}; | |
type NumericRange<TotalLength extends number, TempRange extends any[] = []> = | |
TempRange['length'] extends TotalLength ? TempRange : NumericRange<TotalLength, [...TempRange, TempRange['length']]>; | |
type TupleFromKeys<T, K extends readonly (keyof T)[]> = { | |
[I in keyof K]: K[I] extends keyof T ? T[K[I]] : never; | |
}; | |
type FixedSequence<T extends readonly (readonly any[])[]> = TupleFromKeys<Zipped<T>, NumericRange<T[0]['length']>>; | |
function zip<const T extends readonly (readonly any[])[]>(...arrays: T): FixedSequence<T> { | |
const minLength = Math.min(...arrays.map(arr => arr.length)); | |
const result: any[][] = []; | |
for (let i = 0; i < minLength; i++) { | |
const zippedItem = arrays.map(arr => arr[i]); | |
result.push(zippedItem); | |
} | |
return result as FixedSequence<T>; | |
} | |
const grid = [ | |
['a', 1, true], | |
['b', 2, false], | |
['c', 3, true] | |
] as const; | |
const [col1, col2, col3] = zip(...grid); | |
console.log(col1); | |
console.log(col2); | |
console.log(col3); |
I just realised that our code would only support const literals, so we should make it type-check for this:
// We check whether `T` is a numeric literal by checking that `number`
// does not extend from `T` but that `T` does extend from `number`.
type IsNumericLiteral<T> = number extends T
? false
: T extends number
? true
: false;
type InvalidArgument<T> = readonly [never, T];
type Zipped<A extends readonly (readonly any[])[]> = {
[RowIndex in keyof A[0]]: RowIndex extends "length" ? number : {
[ArrayIndex in keyof A]: A[ArrayIndex] extends readonly any[] ? A[ArrayIndex][RowIndex] : never;
};
};
type NumericRange<TotalLength extends number, TempRange extends any[] = []> =
TempRange['length'] extends TotalLength ? TempRange : NumericRange<TotalLength, [...TempRange, TempRange['length']]>;
type TupleFromKeys<T, K extends readonly (keyof T)[]> = {
[I in keyof K]: K[I] extends keyof T ? T[K[I]] : never;
};
type FixedSequence<T extends readonly (readonly any[])[]> = TupleFromKeys<Zipped<T>, NumericRange<T[0]['length']>>;
function zip<const T extends readonly (readonly any[])[]>(...arrays:
true extends IsNumericLiteral<T['length']>
? T
: InvalidArgument<T>
): FixedSequence<T> {
const minLength = Math.min(...arrays.map(arr => arr.length));
const result: any[][] = [];
for (let i = 0; i < minLength; i++) {
const zippedItem = arrays.map(arr => arr[i]);
result.push(zippedItem);
}
return result as FixedSequence<T>;
}
const grid = [
['a', 1, true],
['b', 2, false],
['c', 3, true]
] as const;
const [col1, col2, col3] = zip(...grid);
console.log(col1);
console.log(col2);
console.log(col3);
// We check whether `T` is a numeric literal by checking that `number`
// does not extend from `T` but that `T` does extend from `number`.
type IsNumericLiteral<T> = number extends T
? false
: T extends number
? true
: false;
type UserProvidedInvalidArgument<T> = readonly [invalidArgumentToZip: never];
type Zipped<A extends readonly (readonly any[])[]> = {
[RowIndex in keyof A[0]]: RowIndex extends "length" ? number : {
[ArrayIndex in keyof A]: A[ArrayIndex] extends readonly any[] ? A[ArrayIndex][RowIndex] : never;
};
};
type NumericRange<TotalLength extends number, TempRange extends any[] = []> =
TempRange['length'] extends TotalLength ? TempRange : NumericRange<TotalLength, [...TempRange, TempRange['length']]>;
type TupleFromKeys<T, K extends readonly (keyof T)[]> = {
[I in keyof K]: K[I] extends keyof T ? T[K[I]] : never;
};
type FixedSequence<T extends readonly (readonly any[])[]> = TupleFromKeys<Zipped<T>, NumericRange<T[0]['length']>>;
function zip<U extends (readonly any[]), T extends U[]>(...arrays: T):
true extends IsNumericLiteral<T[number]['length']>
? FixedSequence<T>
: UserProvidedInvalidArgument<T> {
const minLength = Math.min(...arrays.map(arr => arr.length));
const result: any[][] = [];
for (let i = 0; i < minLength; i++) {
const zippedItem = arrays.map(arr => arr[i]);
result.push(zippedItem);
}
return result as any;
}
const grid1 = [
['a', 1, true] as const,
['b', 2, false] as const,
['c', 3, true] as const,
];
const grid2 = [
['a', 1, true],
['b', 2, false],
['c', 3, true]
] as const;
const grid3 = [
['a', 1, true],
['b', 2, false],
['c', 3, true]
];
const [col1, col2, col3] = zip(...grid1);
const [col4, col5, col6] = zip(...grid2);
const [col7, col8, col9] = zip(...grid3);
console.log(col1);
console.log(col2);
console.log(col3);
// We check whether `T` is a numeric literal by checking that `number`
// does not extend from `T` but that `T` does extend from `number`.
type IsNumericLiteral<T> = number extends T
? false
: T extends number
? true
: false;
type UserProvidedInvalidArgument<T> = readonly [invalidArgumentToZip: never];
type Zipped<A extends readonly (readonly any[])[]> = {
[RowIndex in keyof A[0]]: RowIndex extends "length" ? number : {
[ArrayIndex in keyof A]: A[ArrayIndex] extends readonly any[] ? A[ArrayIndex][RowIndex] : never;
};
};
type NumericRange<TotalLength extends number, TempRange extends any[] = []> =
TempRange['length'] extends TotalLength ? TempRange : NumericRange<TotalLength, [...TempRange, TempRange['length']]>;
type TupleFromKeys<T, K extends readonly (keyof T)[]> = {
[I in keyof K]: K[I] extends keyof T ? T[K[I]] : never;
};
type FixedSequence<T extends readonly (readonly any[])[]> = TupleFromKeys<Zipped<T>, NumericRange<T[0]['length']>>;
function zip<const U extends (readonly any[]), T extends U[]>(...arrays: T):
true extends IsNumericLiteral<T[number]['length']>
? FixedSequence<T>
: UserProvidedInvalidArgument<T> {
const minLength = Math.min(...arrays.map(arr => arr.length));
const result: any[][] = [];
for (let i = 0; i < minLength; i++) {
const zippedItem = arrays.map(arr => arr[i]);
result.push(zippedItem);
}
return result as any;
}
// type GetLength<A extends any[]> = A['length'];
// type Increment<N extends number, A extends any[] = []> = GetLength<A> extends N ? GetLength<[...A, any]> : Increment<N, [...A, any]>
type PrependNumber<A extends any[]> = [...A, A['length']];
type CreateTuple<N extends number, A extends any[] = []> = A['length'] extends N ? A : CreateTuple<N, PrependNumber<A>>;
type Drop<N extends number, A extends any[], B extends any[] = []> = B['length'] extends N ? A : Drop<N, A extends [any, ...infer R] ? R : never, PrependNumber<B>>;
type NRange<Start extends number, Stop extends number> = Drop<Start, CreateTuple<Stop>>;
function range<Start extends number, Stop extends number>(start: Start, stop: Stop): NRange<Start, Stop> {
const result: number[] = [];
for (let i = start; i < stop; i++) {
result.push(i);
}
return result as NRange<Start, Stop>
}
function enumerate<Items extends ReadonlyArray<any>, Length extends Items['length'](items: Items) {
return zip(range(0, items.length as Length), items);
}
const output = enumerate(["a", "b", "c", "d", "e"] as const);
zip
ing values with a range is quite a fun way of enumerating that appears to come from Haskell.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See: https://www.typescriptlang.org/play?#code/C4TwDgpgBAWglmSATAPAQShAHsCA7JAZygCcIBDJAezwBsQoAKMym+qcvEAbQF0BKPgD4oAXigBvAFBQo3AEpUA7gEkC2KHDxQA1hBBUAZlDTcADL14AuKItXqsmHPiJQARLXwBzYAAs3UAD8UHgArgC2AEYQJFA20rKy3GgkJOQgakgaWrr6RibWJsmp6ZnYvE64BMQs1HQMnDwVwaYpaRkOvArKZVgVNngQAG4xANwyUAC+49NSUqCQUAByETFwAMbynF4QKAAqVMDktAAy3n6VLsRhUTEANFB7EOFgW3g7l9UcXHxicrwiUQTJ4vN47bgAck87z8EIq2CqrgOR1O518QUez1e22gNhW4TWmxx+0OxzOMN8D24ADpaSDse8IA96WCIJDoT5fHCAeN5uBoHtQmBPAAxEhUcIAaX0hH2D0ln1ctTYDEYegMxj2ggBfwSchUmm06vyksKku4Knhzi+xs1GL23HNlv6IWGYyksz5ixFcCwECQAGUIABHUL4da7PaKmoUOrsZixlXfJrawGPIWi8VSmUoeCIf37IQPfGE1n7cxdKFouFCIS8wyhPDrYBwGhQABeCBQ6xohGAj2jpET9SYypHjT4qcYtOp5BKIEINi1Nh9fsDIbDTcjIj1Pbwfag4S05M5fwAsuQ-NSj3hp7S5+1CNfyGBGA+xCIH9SOX5+PxxrIe4HmQhChLQwA2BOXQVOIfC8rIhhULEjCeP2cB-GYoyaFAKCHseaJYXAADURH8JIEyAb2-advmSAqLg4R-A+6RPuEL5vqkH4cKk3BwAIAGJCBYHANSYChIQviMDRyD0c8-4TJMcyyGQwChCQ2hCeBHDEKu-pBqG4bbjMcxAf2XgkHASB-NwEyQuQEIPAAjA8wAkGGvB3LZEKRA5UAAEwPIYxyEBAHleesvkAMwuW5oVSBU5DEKZvKmXIPa0M5UDpQFWVULQkUwR2CB3tS5mWfJUhAXlEDflQXiMOljnyVVni1fV2XNb21VtQ1eWRf+QA