1 | import type {Subtract} from './subtract';
|
2 | import type {IsEqual} from './is-equal';
|
3 |
|
4 | type Recursive<T> = ReadonlyArray<Recursive<T>>;
|
5 |
|
6 | /**
|
7 | Creates a type that represents a multidimensional readonly array that of the given type and dimension.
|
8 |
|
9 | Use-cases:
|
10 | - Return a n-dimensional array from functions.
|
11 | - Declare a n-dimensional array by defining its dimensions rather than declaring `[]` repetitively.
|
12 | - Infer the dimensions of a n-dimensional array automatically from function arguments.
|
13 | - Avoid the need to know in advance the dimensions of a n-dimensional array allowing them to be dynamic.
|
14 |
|
15 | @example
|
16 | ```
|
17 | import type {MultidimensionalReadonlyArray} from 'type-fest';
|
18 |
|
19 | function emptyMatrix<T extends number>(dimensions: T): MultidimensionalReadonlyArray<unknown, T> {
|
20 | const matrix: unknown[] = [];
|
21 |
|
22 | let subMatrix = matrix;
|
23 | for (let dimension = 1; dimension < dimensions; ++dimension) {
|
24 | console.log(`Initializing dimension #${dimension}`);
|
25 |
|
26 | subMatrix[0] = [];
|
27 | if (dimension < dimensions - 1) {
|
28 | subMatrix = subMatrix[0] as unknown[];
|
29 | } else {
|
30 | subMatrix[0] = 42;
|
31 | }
|
32 | }
|
33 |
|
34 | return matrix as MultidimensionalReadonlyArray<unknown, T>;
|
35 | }
|
36 |
|
37 | const matrix = emptyMatrix(3);
|
38 |
|
39 | const answer = matrix[0][0][0]; // 42
|
40 | ```
|
41 |
|
42 | @category Array
|
43 | */
|
44 | export type MultidimensionalReadonlyArray<Element, Dimensions extends number> = number extends Dimensions
|
45 | ? Recursive<Element>
|
46 | : IsEqual<Dimensions, 0> extends true
|
47 | ? Element
|
48 | : ReadonlyArray<MultidimensionalReadonlyArray<Element, Subtract<Dimensions, 1>>>;
|