Skip to content

Commit 5dc536e

Browse files
author
Antoine Pelisse
committed
Implement Equals for each interface, avoid Iteration escape
1 parent 186edae commit 5dc536e

File tree

2 files changed

+32
-18
lines changed

2 files changed

+32
-18
lines changed

value/map.go

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -26,27 +26,11 @@ type Map interface {
2626
Set(key string, val Value)
2727
Get(key string) (Value, bool)
2828
Delete(key string)
29+
Equals(other Map) bool
2930
Iterate(func(key string, value Value) bool) bool
3031
Length() int
3132
}
3233

33-
// Equals compares two maps lexically.
34-
func MapEquals(lhs, rhs Map) bool {
35-
if lhs.Length() != rhs.Length() {
36-
return false
37-
}
38-
return lhs.Iterate(func(k string, vl Value) bool {
39-
vr, ok := rhs.Get(k)
40-
if !ok {
41-
return false
42-
}
43-
if !Equals(vl, vr) {
44-
return false
45-
}
46-
return true
47-
})
48-
}
49-
5034
// Less compares two maps lexically.
5135
func MapLess(lhs, rhs Map) bool {
5236
return Compare(lhs, rhs) == -1
@@ -150,6 +134,23 @@ func (m MapInterface) Length() int {
150134
return len(m)
151135
}
152136

137+
func (m MapInterface) Equals(other Map) bool {
138+
for k, v := range m {
139+
ks, ok := k.(string)
140+
if !ok {
141+
return false
142+
}
143+
vo, ok := other.Get(ks)
144+
if !ok {
145+
return false
146+
}
147+
if !Equals(v, vo) {
148+
return false
149+
}
150+
}
151+
return true
152+
}
153+
153154
type MapString map[string]interface{}
154155

155156
func (m MapString) Set(key string, val Value) {
@@ -180,3 +181,16 @@ func (m MapString) Iterate(fn func(key string, value Value) bool) bool {
180181
func (m MapString) Length() int {
181182
return len(m)
182183
}
184+
185+
func (m MapString) Equals(other Map) bool {
186+
for k, v := range m {
187+
vo, ok := other.Get(k)
188+
if !ok {
189+
return false
190+
}
191+
if !Equals(v, vo) {
192+
return false
193+
}
194+
}
195+
return true
196+
}

value/value.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ func Equals(lhs, rhs Value) bool {
9999
}
100100
if IsMap(lhs) {
101101
if IsMap(rhs) {
102-
return MapEquals(ValueMap(lhs), ValueMap(rhs))
102+
return ValueMap(lhs).Equals(ValueMap(rhs))
103103
}
104104
return false
105105
}

0 commit comments

Comments
 (0)