Skip to content
This repository has been archived by the owner on Jan 20, 2024. It is now read-only.

Commit

Permalink
Add a sort helper
Browse files Browse the repository at this point in the history
  • Loading branch information
tdemin committed Jan 26, 2020
1 parent de14ed1 commit 8e9b316
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
52 changes: 52 additions & 0 deletions 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
);
});
});
27 changes: 27 additions & 0 deletions 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 = <T extends Map>(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;
};

0 comments on commit 8e9b316

Please sign in to comment.