25270 - Transpose
sunupupup opened this issue · comments
A very blunt solution ...
type InitRetItems<
M extends number[][],
Ret extends number[][] = []
> = Ret['length'] extends M[0]['length'] ? Ret : InitRetItems<M, [[], ...Ret]>;
type RemoveFirstItem<Arr extends any[]> = Arr extends [any, ...infer Rest]
? Rest
: [];
// append every line
type AppendEveryLine<
Line extends number[],
Ret extends number[][]
> = Line extends [infer FirstNum, ...infer Rest extends number[]]
? [[...Ret[0], FirstNum], ...AppendEveryLine<Rest, RemoveFirstItem<Ret>>]
: [];
type Transpose<
M extends number[][],
Ret extends number[][] = InitRetItems<M>
> = M extends [infer Arr extends number[], ...infer Rest extends number[][]]
? Transpose<Rest, AppendEveryLine<Arr, Ret>>
: Ret;
very concise solution
type Transpose<
M extends number[][],
Ret = M["length"] extends 0 ? [] : M[0] //初始化数组长度
> = {
[X in keyof Ret]: {
[Y in keyof M]: X extends keyof M[Y] ? M[Y][X] : never
}
}