Skip to content

Commit e5a84c2

Browse files
committed
Add a new initilization function for OrderedMap
Signed-off-by: Dušan Mitrović <dmitrovic@nanointeractive.com>
1 parent bf85cb3 commit e5a84c2

File tree

2 files changed

+36
-12
lines changed

2 files changed

+36
-12
lines changed

types/ordered_map.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,38 @@ type (
1212
}
1313
)
1414

15+
// NewOrderedMap
16+
//
17+
// Initializes a new instance of the OrderedMap
1518
func NewOrderedMap[T comparable, V any](length int) OrderedMap[T, V] {
1619
return OrderedMap[T, V]{
1720
insertionOrder: make([]T, 0, length),
1821
values: make(map[T]V, length),
22+
cmpFunc: nil,
1923
}
2024
}
2125

26+
func NewOrderedMapWithCompareFunc[T comparable, V any](
27+
length int,
28+
cmpFunc func(a, b T) int,
29+
) OrderedMap[T, V] {
30+
return OrderedMap[T, V]{
31+
insertionOrder: make([]T, 0, length),
32+
values: make(map[T]V, length),
33+
cmpFunc: cmpFunc,
34+
}
35+
}
36+
37+
// SetCompareFunc
38+
//
39+
// Sets the comparison function to determine ordering.
2240
func (om *OrderedMap[T, V]) SetCompareFunc(cmpFunc func(a, b T) int) {
2341
om.cmpFunc = cmpFunc
2442
}
2543

44+
// UnsetCompareFunc
45+
//
46+
// Unsets the comparison function
2647
func (om *OrderedMap[T, V]) UnsetCompareFunc() {
2748
om.cmpFunc = nil
2849
}

types/ordered_map_test.go

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -93,21 +93,24 @@ func TestOrderedMapIterWithCustomOrder(t *testing.T) {
9393

9494
assert := require.New(t)
9595

96-
om := types.NewOrderedMap[string, int](3)
96+
om := types.NewOrderedMapWithCompareFunc[string, int](
97+
3,
98+
func(a, b string) int {
99+
if a == b {
100+
return 0
101+
}
102+
103+
if a < b {
104+
return -1
105+
}
106+
107+
return 1
108+
},
109+
)
110+
97111
om.Set("foo", 78)
98112
om.Set("var", 90)
99113
om.Set("bar", 81)
100-
om.SetCompareFunc(func(a, b string) int {
101-
if a == b {
102-
return 0
103-
}
104-
105-
if a < b {
106-
return -1
107-
}
108-
109-
return 1
110-
})
111114

112115
expectedKeys := []string{"bar", "foo", "var"}
113116
actualKeys := make([]string, 0, len(expectedKeys))

0 commit comments

Comments
 (0)