Skip to content

Commit a759533

Browse files
authored
feat: supports undefined parent as unsetting parent for setParent API (#8)
* feat: supports undefiend parent as unsetting parent for setParent API * chore: upgrade version num * docs: update changelog * fix: judgement for undefined parent id
1 parent e3d8f13 commit a759533

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@
2121

2222
## Change Log
2323

24+
#### 2.0.2
25+
26+
- feat: supports undefined parent as unsetting parent for setParent API;
27+
2428
#### 2.0
2529

2630
- 🎉 Release new version

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@antv/graphlib",
3-
"version": "2.0.0",
3+
"version": "2.0.2",
44
"sideEffects": false,
55
"scripts": {
66
"clean": "rimraf lib esm dist",

src/graph.ts

+15-2
Original file line numberDiff line numberDiff line change
@@ -1001,16 +1001,29 @@ export class Graph<
10011001
/**
10021002
* Set node parent. If this operation causes a circle, it fails with an error.
10031003
* @param id - ID of the child node.
1004-
* @param parent - ID of the parent node.
1004+
* @param parent - ID of the parent node. If it is undefined, means unset parent for node with id.
10051005
* @param treeKey - Which tree structure the relation is applied to.
10061006
* @group TreeMethods
10071007
*/
1008-
public setParent(id: ID, parent: ID, treeKey?: string) {
1008+
public setParent(id: ID, parent?: ID, treeKey?: string) {
10091009
this.checkTreeExistence(treeKey);
10101010

10111011
const tree = this.treeIndices.get(treeKey)!;
10121012
const node = this.getNode(id);
10131013
const oldParent = tree.parentMap.get(id);
1014+
1015+
// Same parent id as old one, skip
1016+
if (oldParent?.id === parent) return;
1017+
1018+
// New parent is undefined, unset parent for the node
1019+
if (parent === undefined) {
1020+
if (oldParent) {
1021+
tree.childrenMap.get(oldParent.id)?.delete(node);
1022+
}
1023+
tree.parentMap.delete(id);
1024+
return;
1025+
}
1026+
10141027
const newParent = this.getNode(parent);
10151028

10161029
// Set parent

0 commit comments

Comments
 (0)