Skip to content

Instantly share code, notes, and snippets.

@lndgalante
Created January 16, 2024 03:30
Show Gist options
  • Save lndgalante/ef318c5742614325d703a90f8b79c06b to your computer and use it in GitHub Desktop.
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.
/*
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