feat: create function to sort an array of objects by property
Summary: Test Plan:
This commit is contained in:
55
src/libs/sortByProperty.spec.ts
Normal file
55
src/libs/sortByProperty.spec.ts
Normal 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" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
15
src/libs/sortByProperty.ts
Normal file
15
src/libs/sortByProperty.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
export function sortByProperty(
|
||||
priorityObj: Record<string, number>,
|
||||
property: string,
|
||||
) {
|
||||
return (objA: Record<string, any>, objB: Record<string, any>) => {
|
||||
const priorityA = priorityObj[objA[property]];
|
||||
const priorityB = priorityObj[objB[property]];
|
||||
|
||||
if (priorityA && !priorityB) return -1;
|
||||
if (!priorityA && priorityB) return 1;
|
||||
if (priorityA && priorityB) return priorityA - priorityB;
|
||||
|
||||
return 0;
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user