task_1

 avatar
unknown
typescript
a month ago
908 B
3
Indexable
type BoxID = number;
type TreeNode = { id: BoxID; parentId: BoxID | null };
type Flat = TreeNode[];
type Box = TreeNode & { child: Box[] };
type Tree = Box[];

const getTree = (a: Flat): Tree => {
  const map = new Map<BoxID, Box>();
  const tree: Tree = [];

  for (const node of a) {
    map.set(node.id, { ...node, child: [] });
  }
  
  for (const node of a) {
    const { id, parentId } = node;
    if (parentId === null) {
      tree.push(map.get(id)!);
    } else {
      const parent = map.get(parentId);
      if (parent) {
        parent.child.push(map.get(id)!);
      }
    }
  }

  return tree;
};


const flatArray: Flat = [
  { id: 1, parentId: null },
  { id: 2, parentId: 1 },
  { id: 3, parentId: 1 },
  { id: 4, parentId: 2 },
  { id: 5, parentId: 2 },
  { id: 6, parentId: null },
  { id: 7, parentId: 6 },
];

const tree = getTree(flatArray);
console.log(JSON.stringify(tree, null, 2));
Leave a Comment