Skip to content

Commit

Permalink
Added a function to delete a Node and its associated Edges (#24)
Browse files Browse the repository at this point in the history
* Added a function to delete a Node and its associated Edges

* Requested changes
  • Loading branch information
EwenQuim authored May 4, 2021
1 parent a78a723 commit 6136323
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
22 changes: 22 additions & 0 deletions graph.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,28 @@ func (g *Graph) Node(id string) Node {
return n
}

// DeleteNode deletes a node and all the edges associated to the node
// Returns false if the node wasn't found, true otherwise
func (g *Graph) DeleteNode(id string) bool {
if _, ok := g.findNode(id); ok {
// Remove Node
delete(g.nodes, id)
// Remove all the edges from the Node
delete(g.edgesFrom, id)
// Remove all the edges to the Node
for parent, edgeList := range g.edgesFrom {
for i, edge := range edgeList {
if edge.to.id == id {
g.edgesFrom[parent] = append(g.edgesFrom[parent][:i], g.edgesFrom[parent][i+1:]...)
break
}
}
}
return true
}
return false
}

// Edge creates a new edge between two nodes.
// Nodes can be have multiple edges to the same other node (or itself).
// If one or more labels are given then the "label" attribute is set to the edge.
Expand Down
28 changes: 28 additions & 0 deletions graph_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,34 @@ func TestEmptyWithHTMLLabel(t *testing.T) {
}
}

func TestDeleteNode(t *testing.T) {
di := NewGraph(Directed)
n1 := di.Node("A")
n2 := di.Node("B")
n3 := di.Node("C")
di.Edge(n1, n2) // Will be deleted
di.Edge(n2, n3) // Will also be deleted
di.Edge(n1, n3) // Must not be deleted
wasDeleted := di.DeleteNode("B")
if got, want := flatten(di.String()), `digraph {n1[label="A"];n3[label="C"];n1->n3;}`; wasDeleted && got != want {
t.Errorf("got [%v] want [%v]", got, want)
}
}

func TestDeleteNodeWhenNodeDoesNotExist(t *testing.T) {
di := NewGraph(Directed)
n1 := di.Node("A")
n2 := di.Node("B")
n3 := di.Node("C")
di.Edge(n1, n2)
di.Edge(n2, n3)
wasDeleted := di.DeleteNode("D")

if got, want := flatten(di.String()), `digraph {n1[label="A"];n2[label="B"];n3[label="C"];n1->n2;n2->n3;}`; !wasDeleted && got != want {
t.Errorf("got [%v] want [%v]", got, want)
}
}

func TestEmptyWithLiteralValueLabel(t *testing.T) {
di := NewGraph(Directed)
di.ID("test")
Expand Down

0 comments on commit 6136323

Please sign in to comment.