feat: create function to sort an array of objects by property

Summary:

Test Plan:
This commit is contained in:
2024-05-24 16:06:36 -04:00
parent 62e780e8bf
commit c5cce2543c
2 changed files with 70 additions and 0 deletions

View File

@@ -0,0 +1,55 @@
import { describe, expect, it } from "bun:test";
import { sortByProperty } from "./sortByProperty";
describe("sortByProperty", () => {
it("ascending order, array stays same", () => {
const sorted = [{ key: "a" }, { key: "b" }, { key: "c" }].sort(
sortByProperty({ a: 1, b: 2, c: 3 }, "key"),
);
expect(sorted).toEqual([{ key: "a" }, { key: "b" }, { key: "c" }]);
});
it("descending order, array is reversed", () => {
const sorted = [{ key: "a" }, { key: "b" }, { key: "c" }].sort(
sortByProperty({ a: 3, b: 2, c: 1 }, "key"),
);
expect(sorted).toEqual([{ key: "c" }, { key: "b" }, { key: "a" }]);
});
it("randomized order, array is randomized", () => {
const sorted = [
{ key: "a" },
{ key: "b" },
{ key: "c" },
{ key: "d" },
{ key: "e" },
].sort(sortByProperty({ a: 3, b: 4, c: 1, d: 2, e: 5 }, "key"));
expect(sorted).toEqual([
{ key: "c" },
{ key: "d" },
{ key: "a" },
{ key: "b" },
{ key: "e" },
]);
});
it("object without expected property gets put to end of array", () => {
const sorted = [
{ key: "a" },
{ different: "key" },
{ key: "b" },
{ key: "c" },
].sort(sortByProperty({ a: 3, b: 2, c: 1, key: 0 }, "key"));
expect(sorted).toEqual([
{ key: "c" },
{ key: "b" },
{ key: "a" },
{ different: "key" },
]);
});
});