Created
January 16, 2024 03:30
-
-
Save lndgalante/ef318c5742614325d703a90f8b79c06b to your computer and use it in GitHub Desktop.
Given a 2D array, write a function that flips it vertically or horizontally.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Given a 2D array, write a function that flips it vertically or horizontally. | |
*/ | |
export function flip(matrix: number[][], direction: "horizontal" | "vertical") { | |
if (direction === "horizontal") { | |
return matrix.map((row) => row.toReversed()); | |
} | |
if (direction === "vertical") { | |
return matrix.toReversed(); | |
} | |
throw new Error("Direction not supported"); | |
} | |
// tests | |
import { expect, test } from "bun:test"; | |
import { flip } from "."; | |
test("that horizontal direction returns sorted matrix", () => { | |
const array = [ | |
[1, 2, 3], | |
[4, 5, 6], | |
[7, 8, 9], | |
]; | |
expect(flip(array, "horizontal")).toEqual([ | |
[3, 2, 1], | |
[6, 5, 4], | |
[9, 8, 7], | |
]); | |
}); | |
test("that vertical direction returns sorted matrix", () => { | |
const array = [ | |
[1, 2, 3], | |
[4, 5, 6], | |
[7, 8, 9], | |
]; | |
expect(flip(array, "vertical")).toEqual([ | |
[7, 8, 9], | |
[4, 5, 6], | |
[1, 2, 3], | |
]); | |
}); | |
test("that unrecognized direction throws an error", () => { | |
const array = [[0]]; | |
expect(() => flip(array, "diagonal")).toThrow("Direction not supported"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment