1 import { Children } from "../../node_modules/@types/react";
3 // Copyright (C) The Arvados Authors. All rights reserved.
5 // SPDX-License-Identifier: AGPL-3.0
7 export type Tree<T> = Record<string, TreeNode<T>>;
9 export const TREE_ROOT_ID = '';
11 export interface TreeNode<T> {
18 export const createTree = <T>(): Tree<T> => ({});
20 export const getNode = (id: string) => <T>(tree: Tree<T>): TreeNode<T> | undefined => tree[id];
22 export const setNode = <T>(node: TreeNode<T>) => (tree: Tree<T>): Tree<T> => {
23 const [newTree] = [tree]
24 .map(tree => getNode(node.id)(tree) === node
26 : Object.assign({}, tree, { [node.id]: node }))
27 .map(addChild(node.parent, node.id));
31 export const getNodeValue = (id: string) => <T>(tree: Tree<T>) => {
32 const node = getNode(id)(tree);
33 return node ? node.value : undefined;
36 export const setNodeValue = (id: string) => <T>(value: T) => (tree: Tree<T>) => {
37 const node = getNode(id)(tree);
39 ? setNode(mapNodeValue(() => value)(node))(tree)
43 export const setNodeValueWith = <T>(mapFn: (value: T) => T) => (id: string) => (tree: Tree<T>) => {
44 const node = getNode(id)(tree);
46 ? setNode(mapNodeValue(mapFn)(node))(tree)
50 export const mapTreeValues = <T, R>(mapFn: (value: T) => R) => (tree: Tree<T>): Tree<R> =>
51 getNodeDescendants('')(tree)
52 .map(id => getNode(id)(tree))
53 .map(mapNodeValue(mapFn))
54 .reduce((newTree, node) => setNode(node)(newTree), createTree<R>());
56 export const mapTree = <T, R>(mapFn: (node: TreeNode<T>) => TreeNode<R>) => (tree: Tree<T>): Tree<R> =>
57 getNodeDescendants('')(tree)
58 .map(id => getNode(id)(tree))
60 .reduce((newTree, node) => setNode(node)(newTree), createTree<R>());
62 export const getNodeAncestors = (id: string) => <T>(tree: Tree<T>): string[] => {
63 const node = getNode(id)(tree);
64 return node && node.parent
65 ? [...getNodeAncestors(node.parent)(tree), node.parent]
69 export const getNodeDescendants = (id: string, limit = Infinity) => <T>(tree: Tree<T>): string[] => {
70 const node = getNode(id)(tree);
71 const children = node ? node.children :
73 ? getRootNodeChildren(tree)
80 .map(id => getNodeDescendants(id, limit - 1)(tree))
81 .reduce((nodes, nodeChildren) => [...nodes, ...nodeChildren], []));
84 export const getNodeChildren = (id: string) => <T>(tree: Tree<T>): string[] =>
85 getNodeDescendants(id, 0)(tree);
87 const mapNodeValue = <T, R>(mapFn: (value: T) => R) => (node: TreeNode<T>): TreeNode<R> =>
88 ({ ...node, value: mapFn(node.value) });
90 const getRootNodeChildren = <T>(tree: Tree<T>) =>
93 .filter(id => getNode(id)(tree)!.parent === TREE_ROOT_ID);
95 const addChild = (parentId: string, childId: string) => <T>(tree: Tree<T>): Tree<T> => {
96 const node = getNode(parentId)(tree);
98 const children = node.children.some(id => id === childId)
100 : [...node.children, childId];
102 const newNode = children === node.children
104 : { ...node, children };
106 return setNode(newNode)(tree);