From c5cce2543c0cf4dc122a1271a44dca836126773d Mon Sep 17 00:00:00 2001 From: Rushil Perera Date: Fri, 24 May 2024 16:06:36 -0400 Subject: [PATCH] feat: create function to sort an array of objects by property Summary: Test Plan: --- src/libs/sortByProperty.spec.ts | 55 +++++++++++++++++++++++++++++++++ src/libs/sortByProperty.ts | 15 +++++++++ 2 files changed, 70 insertions(+) create mode 100644 src/libs/sortByProperty.spec.ts create mode 100644 src/libs/sortByProperty.ts diff --git a/src/libs/sortByProperty.spec.ts b/src/libs/sortByProperty.spec.ts new file mode 100644 index 0000000..6b2686b --- /dev/null +++ b/src/libs/sortByProperty.spec.ts @@ -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" }, + ]); + }); +}); diff --git a/src/libs/sortByProperty.ts b/src/libs/sortByProperty.ts new file mode 100644 index 0000000..74d3ee4 --- /dev/null +++ b/src/libs/sortByProperty.ts @@ -0,0 +1,15 @@ +export function sortByProperty( + priorityObj: Record, + property: string, +) { + return (objA: Record, objB: Record) => { + 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; + }; +}