From 22c0bace5fb332d5f3b791612352e3d45c080231 Mon Sep 17 00:00:00 2001 From: Sandy Cash Date: Thu, 23 Mar 2023 10:07:22 -0400 Subject: [PATCH] Graph.Add() returns pointer to new Vertex and error --- graph/graph.go | 2 +- graph/list.go | 4 +++- graph/list_test.go | 21 +++++++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/graph/graph.go b/graph/graph.go index f243c2c..58fd459 100644 --- a/graph/graph.go +++ b/graph/graph.go @@ -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) } diff --git a/graph/list.go b/graph/list.go index d534946..6432ae4 100644 --- a/graph/list.go +++ b/graph/list.go @@ -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) } diff --git a/graph/list_test.go b/graph/list_test.go index cc88f04..b15b9e2 100644 --- a/graph/list_test.go +++ b/graph/list_test.go @@ -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")) + }) + }) })