diff --git a/src/graph.ts b/src/graph.ts index 9aafa61..78a9dfd 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -1008,22 +1008,25 @@ export class Graph< /** * Set node parent. If this operation causes a circle, it fails with an error. * @param id - ID of the child node. - * @param parent - ID of the parent node. If it is undefined, means unset parent for node with id. + * @param parent - ID of the parent node. If it is undefined or null, means unset parent for node with id. * @param treeKey - Which tree structure the relation is applied to. * @group TreeMethods */ - public setParent(id: ID, parent?: ID, treeKey?: string) { + public setParent(id: ID, parent?: ID | null, treeKey?: string) { this.checkTreeExistence(treeKey); - const tree = this.treeIndices.get(treeKey)!; + const tree = this.treeIndices.get(treeKey); + + if (!tree) return; + const node = this.getNode(id); const oldParent = tree.parentMap.get(id); // Same parent id as old one, skip if (oldParent?.id === parent) return; - // New parent is undefined, unset parent for the node - if (parent === undefined) { + // New parent is undefined or null, unset parent for the node + if (parent === undefined || parent === null) { if (oldParent) { tree.childrenMap.get(oldParent.id)?.delete(node); }