1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 export type Tree<T> = Record<string, TreeNode<T>>;
7 export const TREE_ROOT_ID = '';
9 export interface TreeNode<T> {
16 export const createTree = <T>(): Tree<T> => ({});
18 export const getNode = (id: string) => <T>(tree: Tree<T>): TreeNode<T> | undefined => tree[id];
20 export const setNode = <T>(node: TreeNode<T>) => (tree: Tree<T>): Tree<T> => {
21 const [newTree] = [tree]
22 .map(tree => getNode(node.id)(tree) === node
24 : {...tree, [node.id]: node})
25 .map(addChild(node.parent, node.id));
29 export const getNodeValue = (id: string) => <T>(tree: Tree<T>) => {
30 const node = getNode(id)(tree);
31 return node ? node.value : undefined;
34 export const setNodeValue = (id: string) => <T>(value: T) => (tree: Tree<T>) => {
35 const node = getNode(id)(tree);
37 ? setNode(mapNodeValue(() => value)(node))(tree)
41 export const setNodeValueWith = <T>(mapFn: (value: T) => T) => (id: string) => (tree: Tree<T>) => {
42 const node = getNode(id)(tree);
44 ? setNode(mapNodeValue(mapFn)(node))(tree)
48 export const mapTreeValues = <T, R>(mapFn: (value: T) => R) => (tree: Tree<T>): Tree<R> =>
49 getNodeDescendants('')(tree)
50 .map(id => getNode(id)(tree))
51 .map(mapNodeValue(mapFn))
52 .reduce((newTree, node) => setNode(node)(newTree), createTree<R>());
54 export const mapTree = <T, R>(mapFn: (node: TreeNode<T>) => TreeNode<R>) => (tree: Tree<T>): Tree<R> =>
55 getNodeDescendants('')(tree)
56 .map(id => getNode(id)(tree))
58 .reduce((newTree, node) => setNode(node)(newTree), createTree<R>());
60 export const getNodeAncestors = (id: string) => <T>(tree: Tree<T>): string[] => {
61 const node = getNode(id)(tree);
62 return node && node.parent
63 ? [...getNodeAncestors(node.parent)(tree), node.parent]
67 export const getNodeDescendants = (id: string, limit = Infinity) => <T>(tree: Tree<T>): string[] => {
68 const node = getNode(id)(tree);
69 const children = node ? node.children :
71 ? getRootNodeChildren(tree)
78 .map(id => getNodeDescendants(id, limit - 1)(tree))
79 .reduce((nodes, nodeChildren) => [...nodes, ...nodeChildren], []));
82 export const getNodeChildren = (id: string) => <T>(tree: Tree<T>): string[] =>
83 getNodeDescendants(id, 0)(tree);
85 const mapNodeValue = <T, R>(mapFn: (value: T) => R) => (node: TreeNode<T>): TreeNode<R> =>
86 ({ ...node, value: mapFn(node.value) });
88 const getRootNodeChildren = <T>(tree: Tree<T>) =>
91 .filter(id => getNode(id)(tree)!.parent === TREE_ROOT_ID);
93 const addChild = (parentId: string, childId: string) => <T>(tree: Tree<T>): Tree<T> => {
94 const node = getNode(parentId)(tree);
96 const children = node.children.some(id => id === childId)
98 : [...node.children, childId];
100 const newNode = children === node.children
102 : { ...node, children };
104 return setNode(newNode)(tree);