Skip to content

Commit

Permalink
refactor: setParent support pass null to cancel relationship
Browse files Browse the repository at this point in the history
  • Loading branch information
Aarebecca committed Nov 27, 2024
1 parent 1ac494f commit 5e039de
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down

0 comments on commit 5e039de

Please sign in to comment.