Skip to content

Commit

Permalink
refactor: flip less bloated
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelriosoliveira committed Jan 17, 2024
1 parent e82d236 commit 19d804b
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 24 deletions.
40 changes: 40 additions & 0 deletions src/2024/335-flip/flip.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,44 @@ describe('#flip', () => {
[1, 2, 3],
]);
});

it('should handle an empty array', () => {
expect(flip([], 'horizontal')).toStrictEqual([]);
});

it('should handle a single-row array horizontally', () => {
const array = [[1, 2, 3]];
expect(flip(array, 'horizontal')).toStrictEqual([[3, 2, 1]]);
});

it('should handle a single-column array vertically', () => {
const array = [[1], [4], [7]];
expect(flip(array, 'vertical')).toStrictEqual([[7], [4], [1]]);
});

it('should handle a non-squared matrix horizontally', () => {
const array = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
];
expect(flip(array, 'horizontal')).toStrictEqual([
[4, 3, 2, 1],
[8, 7, 6, 5],
[12, 11, 10, 9],
]);
});

it('should handle a non-squared matrix vertically', () => {
const array = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
];
expect(flip(array, 'vertical')).toStrictEqual([
[9, 10, 11, 12],
[5, 6, 7, 8],
[1, 2, 3, 4],
]);
});
});
28 changes: 4 additions & 24 deletions src/2024/335-flip/flip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,29 +24,9 @@ let array = [
]
*/

type Matrix = number[][];

function flipHorizontally(matrix: Matrix): Matrix {
return matrix.map(row => row.toReversed());
}

function transpose(matrix: Matrix) {
const transposed: Matrix = [];
for (let i = 0; i < matrix.length; i++) {
const column: number[] = [];

for (let j = 0; j < matrix[i].length; j++) {
column.push(matrix[j][i]);
}

transposed.push(column);
export function flip(matrix: number[][], direction: 'horizontal' | 'vertical'): number[][] {
if (direction === 'vertical') {
return matrix.toReversed();
}
return transposed;
}

export function flip(matrix: Matrix, direction: 'horizontal' | 'vertical'): Matrix {
if (direction === 'horizontal') {
return flipHorizontally(matrix);
}
return transpose(flipHorizontally(transpose(matrix)));
return matrix.map(row => row.toReversed());
}

0 comments on commit 19d804b

Please sign in to comment.