From c4d78a6c0cdd9d09b73b663219e979185b6e0b63 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Thu, 10 Apr 2025 18:34:04 +0200 Subject: [PATCH] utils: array util functions (any types) --- src/utils/array.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/utils/array.ts diff --git a/src/utils/array.ts b/src/utils/array.ts new file mode 100644 index 0000000..3ab7c50 --- /dev/null +++ b/src/utils/array.ts @@ -0,0 +1,26 @@ +/** + * Transpose a 2D array (matrix). + * @param {any[][]} matrix - The 2D array to transpose. + * @returns {any[][]} - The transposed 2D array. + **/ + +export function transpose(matrix: T[][]): any[][] { + return matrix[0].map((_, colIndex) => matrix.map((row) => row[colIndex])); +} + +/** + * Normalize and fill a 2D array to ensure all rows have the same length. + * @param {any[][]} matrix - The 2D array to normalize and fill. + * @param {any} fillValue - The value to fill in for missing elements. + * @returns {any[][]} - The normalized and filled 2D array. + * **/ +export function normalizeAndFill(matrix: T[][], fillValue: T): T[][] { + const maxLength = Math.max(...matrix.map((row) => row.length)); + return matrix.map((row) => { + const filledRow = [...row]; + while (filledRow.length < maxLength) { + filledRow.push(fillValue); + } + return filledRow; + }); +}