From 8e9b3168edd4fec2dd1c314e1961a4540a0b80f6 Mon Sep 17 00:00:00 2001 From: Timur Demin Date: Sun, 26 Jan 2020 14:43:30 +0500 Subject: [PATCH] Add a sort helper --- src/helpers/sort.test.ts | 52 ++++++++++++++++++++++++++++++++++++++++ src/helpers/sort.ts | 27 +++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 src/helpers/sort.test.ts create mode 100644 src/helpers/sort.ts diff --git a/src/helpers/sort.test.ts b/src/helpers/sort.test.ts new file mode 100644 index 0000000..4a8c5c0 --- /dev/null +++ b/src/helpers/sort.test.ts @@ -0,0 +1,52 @@ +import { sortByAttrs } from "./sort"; + +type Record = { + id: number; + name: string; +}; + +const testData: Record[] = [ + { id: 1, name: "Beth" }, + { id: 2, name: "Anna" }, + { id: 3, name: "Roy" }, + { id: 4, name: "Amy" }, +]; +const sortedByName: Record[] = [ + { id: 2, name: "Anna" }, + { id: 4, name: "Amy" }, + { id: 1, name: "Beth" }, + { id: 3, name: "Roy" }, +]; +const sortedByID: Record[] = [ + { id: 1, name: "Beth" }, + { id: 2, name: "Anna" }, + { id: 3, name: "Roy" }, + { id: 4, name: "Amy" }, +]; +const testDataWithMultipleProps: Record[] = [ + { id: 2, name: "Beth" }, + { id: 1, name: "Beth" }, + { id: 3, name: "Roy" }, + { id: 3, name: "Amy" }, +]; +const sortedByMultipleProps: Record[] = [ + { id: 1, name: "Beth" }, + { id: 2, name: "Beth" }, + { id: 3, name: "Amy" }, + { id: 3, name: "Roy" }, +]; + +describe("sort helpers on strict types", () => { + it("generates an empty array in response to an empty array", () => { + expect(sortByAttrs([])).toEqual([]); + }); + it("sorts an array by a single property", () => { + expect(sortByAttrs(testData, "name")).toEqual(sortedByName); + expect(sortByAttrs(testData, "id")).toEqual(sortedByID); + }); + it("sorts an array by multiple props", () => { + expect(sortByAttrs(testDataWithMultipleProps, "name", "id")).toEqual( + sortedByMultipleProps + ); + }); +}); diff --git a/src/helpers/sort.ts b/src/helpers/sort.ts new file mode 100644 index 0000000..7985c60 --- /dev/null +++ b/src/helpers/sort.ts @@ -0,0 +1,27 @@ +type Map = { [key: string]: any }; + +/** + * Sorts any array given the list of attributes in order of descending priority. + * Uses bubble sort algorithm to sort the array. Returns a new array. + * @param a The array of things to sort + * @param attrs The attributes in order of descending priority + */ +export const sortByAttrs = (a: T[], ...attrs: (keyof T)[]) => { + // the single edge case + if (a.length === 0) { + return []; + } + const arr = [...a]; + for (let i = 0; i < arr.length; i++) { + for (let j = i; j < arr.length - 1; j++) { + attrs.forEach((attr) => { + if (arr[j][attr] > arr[j + 1][attr]) { + let temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + }); + } + } + return arr; +};