Skip to content

Commit

Permalink
Adds Copy() function (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
ebh committed Feb 5, 2021
1 parent 5498093 commit 724076b
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ module github.com/elliotchance/orderedmap

go 1.12

require github.com/stretchr/testify v1.4.0
require github.com/stretchr/testify v1.7.0
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
12 changes: 12 additions & 0 deletions orderedmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,15 @@ func (m *OrderedMap) Back() *Element {
Value: element.value,
}
}

// Copy returns a new OrderedMap with the same elements.
// Using Copy while there are concurrent writes may mangle the result.
func (m *OrderedMap) Copy() *OrderedMap {
m2 := NewOrderedMap()

for el := m.Front(); el != nil; el = el.Next() {
m2.Set(el.Key, el.Value)
}

return m2
}
14 changes: 14 additions & 0 deletions orderedmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,20 @@ func TestOrderedMap_Back(t *testing.T) {
})
}

func TestOrderedMap_Copy(t *testing.T) {
t.Run("ReturnsEqualButNotSame", func(t *testing.T) {
key, value := 1, "a value"
m := orderedmap.NewOrderedMap()
m.Set(key, value)

m2 := m.Copy()
m2.Set(key, "a different value")

assert.Equal(t, m.Len(), m2.Len(), "not all elements are copied")
assert.Equal(t, value, m.GetElement(key).Value)
})
}

func TestGetElement(t *testing.T) {
t.Run("ReturnsElementForKey", func(t *testing.T) {
m := orderedmap.NewOrderedMap()
Expand Down

0 comments on commit 724076b

Please sign in to comment.