From 9185e3c8c1b8329fa149f5ff09e9f7b7d4300829 Mon Sep 17 00:00:00 2001 From: connoratrug <47183404+connoratrug@users.noreply.github.com> Date: Fri, 11 Oct 2024 10:45:13 +0200 Subject: [PATCH] feat: Sort ontology trees (#4332) * feat: Sort ontology trees Sort by level, if order field is set for a level use it , else use alphabet --- apps/nuxt3-ssr/utils/ontologyUtils.test.ts | 33 +++++++++++++++++++++- apps/nuxt3-ssr/utils/ontologyUtils.ts | 22 ++++++++++++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/apps/nuxt3-ssr/utils/ontologyUtils.test.ts b/apps/nuxt3-ssr/utils/ontologyUtils.test.ts index ac3f9c4f18..1b1bf53b84 100644 --- a/apps/nuxt3-ssr/utils/ontologyUtils.test.ts +++ b/apps/nuxt3-ssr/utils/ontologyUtils.test.ts @@ -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", () => { @@ -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 }] }]); + }); +}); diff --git a/apps/nuxt3-ssr/utils/ontologyUtils.ts b/apps/nuxt3-ssr/utils/ontologyUtils.ts index b44c127195..dd43d9d722 100644 --- a/apps/nuxt3-ssr/utils/ontologyUtils.ts +++ b/apps/nuxt3-ssr/utils/ontologyUtils.ts @@ -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 = ( @@ -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;