Skip to content

Commit

Permalink
feat: Sort ontology trees (#4332)
Browse files Browse the repository at this point in the history
* feat: Sort ontology trees

Sort by level, if order field is set for a level use it , else use alphabet
  • Loading branch information
connoratrug authored Oct 11, 2024
1 parent 4ff7727 commit 9185e3c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
33 changes: 32 additions & 1 deletion apps/nuxt3-ssr/utils/ontologyUtils.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it, expect } from "vitest";
import type { IOntologyParentTreeItem } from "../interfaces/types";
import { buildTree, flattenTree } from "./ontologyUtils";
import { buildTree, flattenTree, sortTree } from "./ontologyUtils";

describe("flattenTree", () => {
it("passing an instance without parent should return a list containing only the item", () => {
Expand Down Expand Up @@ -79,3 +79,34 @@ describe("buildTree", () => {
expect(tree[0].children[0].name).toEqual("C1");
});
});

describe("sortTree", () => {
it("empty tree is sorted ", () => {
expect(sortTree([])).toEqual([]);
});

it("sorts ", () => {
expect(sortTree([{ name: "B" }, { name: "A" }])).toEqual([
{ name: "A" },
{ name: "B" },
]);
});

it("preserve the order ", () => {
expect(
sortTree([
{ name: "A", order: 2 },
{ name: "B", order: 1 },
])
).toEqual([
{ name: "B", order: 1 },
{ name: "A", order: 2 },
]);
});

it("goes deep ", () => {
expect(
sortTree([{ name: "A", order: 2, children: [{ name: "B", order: 1 }] }])
).toEqual([{ name: "A", order: 2, children: [{ name: "B", order: 1 }] }]);
});
});
22 changes: 21 additions & 1 deletion apps/nuxt3-ssr/utils/ontologyUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ export const buildTree = (
}

const roots = uniqueItems.filter((item) => !item.parent);
return roots;
const sorted = sortTree(roots);
return sorted;
};

export const flattenTree = (
Expand All @@ -60,4 +61,23 @@ export const flattenTree = (
}
};

export const sortTree = (tree: IOntologyItem[]): IOntologyItem[] => {
const sortBy = tree.every((item) => item.order !== undefined)
? "order"
: "name";
tree.sort((a, b) => {
return sortBy === "order" && a.order !== undefined && b.order !== undefined
? a.order - b.order
: a.name.localeCompare(b.name);
});

for (const item of tree) {
if (item.children) {
item.children = sortTree(item.children as IOntologyItem[]);
}
}

return tree;
};

const equals = (a: IOntologyItem, b: IOntologyItem) => a.name === b.name;

0 comments on commit 9185e3c

Please sign in to comment.