| 8 | 8 | * @return {string[]} |
| 9 | 9 | */ |
| 10 | 10 | export function transpose(input) { |
| 11 | | throw new Error('Remove this line and implement the function'); |
| 11 | // Edge Case: Empty input array |
| 12 | if (input.length === 0) { |
| 13 | return []; |
| 14 | } |
| 15 | |
| 16 | // Edge Case: Input with empty strings |
| 17 | if (input.every(row => row.length === 0)) { |
| 18 | return []; |
| 19 | } |
| 20 | |
| 21 | // Find the maximum length among all rows |
| 22 | const maxLength = Math.max(...input.map(row => row.length)); |
| 23 | |
| 24 | // Edge Case: All rows are empty strings |
| 25 | if (maxLength === 0) { |
| 26 | return []; |
| 27 | } |
| 28 | |
| 29 | const result = []; |
| 30 | |
| 31 | // For each column index in the transposed matrix |
| 32 | for (let colIndex = 0; colIndex < maxLength; colIndex++) { |
| 33 | let newRow = ''; |
| 34 | |
| 35 | // For each row in the original matrix |
| 36 | for (let rowIndex = 0; rowIndex < input.length; rowIndex++) { |
| 37 | const row = input[rowIndex]; |
| 38 | |
| 39 | // Edge Case: Current row is shorter than the column index |
| 40 | if (colIndex < row.length) { |
| 41 | newRow += row[colIndex]; |
| 42 | } else { |
| 43 | // Pad with space if the row is too short |
| 44 | newRow += ' '; |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // Remove trailing spaces from the new row |
| 49 | result.push(newRow.replace(/\s+$/, '')); |
| 50 | } |
| 51 | |
| 52 | return result; |
| 12 | 53 | }; |
| 54 | |
| 55 | // Handled Edge Cases: Empty input array, input with empty strings, all rows are empty strings, current row is shorter than the column index, remove trailing spaces from rows |