From bd4563b699721e9b06b0c54e1f80e3a56d4723f2 Mon Sep 17 00:00:00 2001 From: James Shubin Date: Wed, 31 May 2017 15:32:38 -0400 Subject: [PATCH] pgraph: Add sort function to sort a list of vertices With tests too! --- pgraph/pgraph.go | 12 +++++++++++ pgraph/pgraph_test.go | 48 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/pgraph/pgraph.go b/pgraph/pgraph.go index 102fe9f5..28212cac 100644 --- a/pgraph/pgraph.go +++ b/pgraph/pgraph.go @@ -623,3 +623,15 @@ func Reverse(vs []Vertex) []Vertex { } return out } + +// Sort the list of vertices and return a copy without modifying the input. +func Sort(vs []Vertex) []Vertex { + vertices := []Vertex{} + for _, v := range vs { // copy + vertices = append(vertices, v) + } + sort.Sort(VertexSlice(vertices)) + return vertices + // sort.Sort(VertexSlice(vs)) // this is wrong, it would modify input! + //return vs +} diff --git a/pgraph/pgraph_test.go b/pgraph/pgraph_test.go index 86bfcbf6..e488f362 100644 --- a/pgraph/pgraph_test.go +++ b/pgraph/pgraph_test.go @@ -693,3 +693,51 @@ func TestPgraphGraphCmp1(t *testing.T) { t.Errorf("should have error during GraphCmp, but got nil") } } + +func TestPgraphSort0(t *testing.T) { + vs := []Vertex{} + s := Sort(vs) + + if !reflect.DeepEqual(s, []Vertex{}) { + t.Errorf("sort failed!") + if s == nil { + t.Logf("output is nil!") + } else { + str := "Got:" + for _, v := range s { + str += " " + v.String() + } + t.Errorf(str) + } + } +} + +func TestPgraphSort1(t *testing.T) { + v1 := NV("v1") + v2 := NV("v2") + v3 := NV("v3") + v4 := NV("v4") + v5 := NV("v5") + v6 := NV("v6") + + vs := []Vertex{v3, v2, v6, v1, v5, v4} + s := Sort(vs) + + if !reflect.DeepEqual(s, []Vertex{v1, v2, v3, v4, v5, v6}) { + t.Errorf("sort failed!") + str := "Got:" + for _, v := range s { + str += " " + v.String() + } + t.Errorf(str) + } + + if !reflect.DeepEqual(vs, []Vertex{v3, v2, v6, v1, v5, v4}) { + t.Errorf("sort modified input!") + str := "Got:" + for _, v := range vs { + str += " " + v.String() + } + t.Errorf(str) + } +}