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 addChild = (parentId: string, childId: string) => <T>(tree: Tree<T>): Tree<T> => {
32 const node = getNode(parentId)(tree);
34 const children = node.children.some(id => id === childId)
36 : [...node.children, childId];
38 const newNode = children === node.children
40 : { ...node, children };
42 return setNode(newNode)(tree);
48 export const getNodeAncestors = (id: string) => <T>(tree: Tree<T>): string[] => {
49 const node = getNode(id)(tree);
50 return node && node.parent
51 ? [...getNodeAncestors(node.parent)(tree), node.parent]
55 export const getNodeDescendants = (id: string, limit = Infinity) => <T>(tree: Tree<T>): string[] => {
56 const node = getNode(id)(tree);
57 const children = node ? node.children :
59 ? getRootNodeChildren(tree)
66 .map(id => getNodeDescendants(id, limit - 1)(tree))
67 .reduce((nodes, nodeChildren) => [...nodes, ...nodeChildren], []));
70 export const getNodeChildren = (id: string) => <T>(tree: Tree<T>): string[] =>
71 getNodeDescendants(id, 0)(tree);
73 export const mapNodes = (ids: string[]) => <T>(mapFn: (node: TreeNode<T>) => TreeNode<T>) => (tree: Tree<T>): Tree<T> =>
75 .map(id => getNode(id)(tree))
78 .reduce((tree, update) => update(tree), tree);
80 export const mapTree = <T, R>(mapFn: (node: TreeNode<T>) => TreeNode<R>) => (tree: Tree<T>): Tree<R> =>
81 getNodeDescendants('')(tree)
82 .map(id => getNode(id)(tree))
84 .reduce((newTree, node) => setNode(node)(newTree), createTree<R>());
86 export const mapNodeValue = <T>(mapFn: (value: T) => T) => (node: TreeNode<T>) =>
87 ({ ...node, value: mapFn(node.value) });
89 const getRootNodeChildren = <T>(tree: Tree<T>) =>
92 .filter(id => getNode(id)(tree)!.parent === TREE_ROOT_ID);