Skip to content

Commit

Permalink
Add sortByNumericValue function
Browse files Browse the repository at this point in the history
We want to be able to sort by the number of open issues too.
To keep things DRY it makes sense to add a function that allows us to
sort by any property of a repo that has a numeric value.
  • Loading branch information
rich committed Sep 13, 2024
1 parent 35284e1 commit 134cfb5
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
15 changes: 15 additions & 0 deletions utils/sorting.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,18 @@ export const sortByOpenPrs = (repos, sortDirection) => {
}
return repos.sort((a, b) => b.openPrsCount - a.openPrsCount);
};

/**
* Sorts repos by the a numeric value
* @param {UiRepo[]} repos
* @param {SortDirection} sortDirection
* @param {string} key - The key to sort by
* @returns {UiRepo[]}
*/
export const sortByNumericValue = (repos, sortDirection, key) => {
if (!sortDirection) return repos;
if (sortDirection === "asc") {
return repos.sort((a, b) => a[key] - b[key]);
}
return repos.sort((a, b) => b[key] - a[key]);
};
48 changes: 47 additions & 1 deletion utils/sorting.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it } from "node:test";
import expect from "node:assert";
import { sortByOpenPrs } from "./sorting.js";
import { sortByOpenPrs, sortByNumericValue } from "./sorting.js";

describe("sortByOpenPrs", () => {
it("returns the original array if sortDirection is not provided", () => {
Expand Down Expand Up @@ -47,3 +47,49 @@ describe("sortByOpenPrs", () => {
]);
});
});

describe("sortByNumericValue", () => {
it("returns the original array if sortDirection is not provided", () => {
const repos = [
{ name: "Repo 1", value: 5 },
{ name: "Repo 2", value: 3 },
{ name: "Repo 3", value: 7 },
];

const result = sortByNumericValue(repos, null, "value");

expect.deepEqual(result, repos);
});

it("sorts the array in ascending order by the specified key if sortDirection is 'asc'", () => {
const repos = [
{ name: "Repo 1", value: 5 },
{ name: "Repo 2", value: 3 },
{ name: "Repo 3", value: 7 },
];

const result = sortByNumericValue(repos, "asc", "value");

expect.deepEqual(result, [
{ name: "Repo 2", value: 3 },
{ name: "Repo 1", value: 5 },
{ name: "Repo 3", value: 7 },
]);
});

it("sorts the array in descending order by the specified key if sortDirection is 'desc'", () => {
const repos = [
{ name: "Repo 1", value: 5 },
{ name: "Repo 2", value: 3 },
{ name: "Repo 3", value: 7 },
];

const result = sortByNumericValue(repos, "desc", "value");

expect.deepEqual(result, [
{ name: "Repo 3", value: 7 },
{ name: "Repo 1", value: 5 },
{ name: "Repo 2", value: 3 },
]);
});
});

0 comments on commit 134cfb5

Please sign in to comment.