* Reshapes a 1-dimensional array into an n-dimensional array, according to the provided dimensions. * * @example * reshape([10 ], [1 ]); // Type: number[] Value: [10] * reshape([1, 2, 3, 4 ], [2, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4]]
(data, dimensions)
| 972 | * @returns {NestArray<T, DIM["length"]>} The reshaped array. |
| 973 | */ |
| 974 | function reshape(data, dimensions) { |
| 975 | const totalElements = data.length; |
| 976 | const dimensionSize = dimensions.reduce((a, b) => a * b); |
| 977 | |
| 978 | if (totalElements !== dimensionSize) { |
| 979 | throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`); |
| 980 | } |
| 981 | |
| 982 | /** @type {any} */ |
| 983 | let reshapedArray = data; |
| 984 | |
| 985 | for (let i = dimensions.length - 1; i >= 0; i--) { |
| 986 | reshapedArray = reshapedArray.reduce( |
| 987 | (acc, val) => { |
| 988 | let lastArray = acc[acc.length - 1]; |
| 989 | |
| 990 | if (lastArray.length < dimensions[i]) { |
| 991 | lastArray.push(val); |
| 992 | } else { |
| 993 | acc.push([val]); |
| 994 | } |
| 995 | |
| 996 | return acc; |
| 997 | }, |
| 998 | [[]], |
| 999 | ); |
| 1000 | } |
| 1001 | |
| 1002 | return reshapedArray[0]; |
| 1003 | } |
| 1004 | |
| 1005 | /** |
| 1006 | * Permutes a tensor according to the provided axes. |