| 3 | 3 | // convenience to get you started writing code faster. |
| 4 | 4 | // |
| 5 | 5 | |
| 6 | | export const transpose = () => { |
| 7 | | throw new Error('Remove this line and implement the function'); |
| 6 | export const transpose = (input) => { |
| 7 | // Edge Case: Empty input array |
| 8 | if (input.length === 0) { |
| 9 | return []; |
| 10 | } |
| 11 | |
| 12 | // Find the maximum length among all rows |
| 13 | const maxLength = Math.max(...input.map(row => row.length)); |
| 14 | |
| 15 | // Edge Case: All rows are empty |
| 16 | if (maxLength === 0) { |
| 17 | return []; |
| 18 | } |
| 19 | |
| 20 | const result = []; |
| 21 | |
| 22 | // Process each column index |
| 23 | for (let colIndex = 0; colIndex < maxLength; colIndex++) { |
| 24 | let newRow = ''; |
| 25 | let hasActualContent = false; |
| 26 | let actualContentLength = 0; |
| 27 | |
| 28 | // For each row, get the character at the current column index |
| 29 | for (let rowIndex = 0; rowIndex < input.length; rowIndex++) { |
| 30 | const row = input[rowIndex]; |
| 31 | |
| 32 | // If the current row has a character at this column index, use it |
| 33 | // Otherwise, add a space (left padding) |
| 34 | if (colIndex < row.length) { |
| 35 | newRow += row[colIndex]; |
| 36 | hasActualContent = true; |
| 37 | actualContentLength = rowIndex + 1; // Track how much actual content we have |
| 38 | } else { |
| 39 | newRow += ' '; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | // Trim trailing spaces that are purely padding |
| 44 | // Keep spaces up to the last row that has actual content |
| 45 | if (hasActualContent) { |
| 46 | result.push(newRow.substring(0, actualContentLength)); |
| 47 | } else { |
| 48 | result.push(newRow.replace(/\s+$/, '')); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | return result; |
| 8 | 53 | }; |
| 54 | |
| 55 | // Handled Edge Cases: Empty input array, Single row input, All rows are empty, Current row is shorter than the column index, Padding shorter rows with spaces, Remove trailing spaces from rows |