import { Children } from "../../node_modules/@types/react"; // Copyright (C) The Arvados Authors. All rights reserved. // // SPDX-License-Identifier: AGPL-3.0 export type Tree = Record>; export const TREE_ROOT_ID = ''; export interface TreeNode { children: string[]; value: T; id: string; parent: string; } export const createTree = (): Tree => ({}); export const getNode = (id: string) => (tree: Tree): TreeNode | undefined => tree[id]; export const setNode = (node: TreeNode) => (tree: Tree): Tree => { const [newTree] = [tree] .map(tree => getNode(node.id)(tree) === node ? tree : Object.assign({}, tree, { [node.id]: node })) .map(addChild(node.parent, node.id)); return newTree; }; export const getNodeValue = (id: string) => (tree: Tree) => { const node = getNode(id)(tree); return node ? node.value : undefined; }; export const setNodeValue = (id: string) => (value: T) => (tree: Tree) => { const node = getNode(id)(tree); return node ? setNode(mapNodeValue(() => value)(node))(tree) : tree; }; export const setNodeValueWith = (mapFn: (value: T) => T) => (id: string) => (tree: Tree) => { const node = getNode(id)(tree); return node ? setNode(mapNodeValue(mapFn)(node))(tree) : tree; }; export const mapTreeValues = (mapFn: (value: T) => R) => (tree: Tree): Tree => getNodeDescendants('')(tree) .map(id => getNode(id)(tree)) .map(mapNodeValue(mapFn)) .reduce((newTree, node) => setNode(node)(newTree), createTree()); export const mapTree = (mapFn: (node: TreeNode) => TreeNode) => (tree: Tree): Tree => getNodeDescendants('')(tree) .map(id => getNode(id)(tree)) .map(mapFn) .reduce((newTree, node) => setNode(node)(newTree), createTree()); export const getNodeAncestors = (id: string) => (tree: Tree): string[] => { const node = getNode(id)(tree); return node && node.parent ? [...getNodeAncestors(node.parent)(tree), node.parent] : []; }; export const getNodeDescendants = (id: string, limit = Infinity) => (tree: Tree): string[] => { const node = getNode(id)(tree); const children = node ? node.children : id === TREE_ROOT_ID ? getRootNodeChildren(tree) : []; return children .concat(limit < 1 ? [] : children .map(id => getNodeDescendants(id, limit - 1)(tree)) .reduce((nodes, nodeChildren) => [...nodes, ...nodeChildren], [])); }; export const getNodeChildren = (id: string) => (tree: Tree): string[] => getNodeDescendants(id, 0)(tree); const mapNodeValue = (mapFn: (value: T) => R) => (node: TreeNode): TreeNode => ({ ...node, value: mapFn(node.value) }); const getRootNodeChildren = (tree: Tree) => Object .keys(tree) .filter(id => getNode(id)(tree)!.parent === TREE_ROOT_ID); const addChild = (parentId: string, childId: string) => (tree: Tree): Tree => { const node = getNode(parentId)(tree); if (node) { const children = node.children.some(id => id === childId) ? node.children : [...node.children, childId]; const newNode = children === node.children ? node : { ...node, children }; return setNode(newNode)(tree); } return tree; };