Skip to content

Commit

Permalink
Graph.Add() returns pointer to new Vertex and error
Browse files Browse the repository at this point in the history
  • Loading branch information
ScarletTanager committed Mar 23, 2023
1 parent 9d75bf0 commit 22c0bac
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
2 changes: 1 addition & 1 deletion graph/graph.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,5 @@ type Graph interface {
Path(int, int) ([]*Vertex, error)
// Add adds the specified Vertex to the graph. Add does not do any uniqueness checks - it is up to the
// user to keep track of which vertices have already been added.
Add(Vertex)
Add(Vertex) (*Vertex, error)
}
4 changes: 3 additions & 1 deletion graph/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,11 @@ func New(vertices []Vertex) (Graph, error) {

var addMutex sync.Mutex

func (a AdjacencyList) Add(v Vertex) {
func (a AdjacencyList) Add(v Vertex) (*Vertex, error) {
addMutex.Lock()
v.index = len(a)
a = append(a, &v)
addMutex.Unlock()

return a.AtIndex(v.index)
}
21 changes: 21 additions & 0 deletions graph/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,4 +162,25 @@ var _ = Describe("List", func() {
})
})
})

Describe("Add", func() {
var (
newVertex graph.Vertex
)

BeforeEach(func() {
newVertex = graph.Vertex{
Attributes: graph.Attributes{
"foo": "peter",
},
}
})

It("Adds the new Vertex", func() {
nvp, err := g.Add(newVertex)
Expect(nvp).NotTo(BeNil())
Expect(err).NotTo(HaveOccurred())
Expect(nvp.Get("foo").(string)).To(Equal("peter"))
})
})
})

0 comments on commit 22c0bac

Please sign in to comment.