Debian Codegraph @

frontend/src/lib/tree.ts

raw
1 import { parent } from "./account";
2
3 /**
4 * A tree node.
5 *
6 * The only base property this has is `.children`, all others are
7 * passed in via the generic parameter.
8 */
9 export type TreeNode<S> = S & { readonly children: TreeNode<S>[] };
10
11 /**
12 * Generate an account tree from an array.
13 *
14 * This is a bit like d3-hierarchys stratify, but inserts implicit nodes that
15 * are missing in the hierarchy.
16 *
17 * @param data - the data to generate the tree for.
18 * @param id - A getter to obtain the node name for an input datum.
19 * @param init - A getter for any extra properties to set on the node.
20 */
21 export function stratify<T, S = null>(
22 data: Iterable<T>,
23 id: (datum: T) => string,
24 init: (name: string, datum?: T) => S,
25 ): TreeNode<S> {
26 const root: TreeNode<S> = { children: [], ...init("") };
27 const map = new Map<string, TreeNode<S>>();
28 map.set("", root);
29
30 function addAccount(name: string, datum?: T): TreeNode<S> {
31 const existing = map.get(name);
32 if (existing) {
33 Object.assign(existing, init(name, datum));
34 return existing;
35 }
36 const node: TreeNode<S> = { children: [], ...init(name, datum) };
37 map.set(name, node);
38 const parentName = parent(name);
39 const parentNode = map.get(parentName) ?? addAccount(parentName);
40 parentNode.children.push(node);
41 return node;
42 }
43
44 [...data]
45 .sort((a, b) => id(a).localeCompare(id(b)))
46 .forEach((datum) => addAccount(id(datum), datum));
47 return root;
48 }