Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions pkg/treemap/custom.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,15 @@ func (m *TreeMap[K, V]) Range(f func(key K, value V) bool) {
}
}
}

// ReverseRange calls f sequentially in reverse order for each key and value
// present in the map. If f returns false, range stops the iteration.
func (m *TreeMap[K, V]) ReverseRange(f func(key K, value V) bool) {
iterator := m.Iterator()
iterator.End()
for iterator.Prev() {
if !f(iterator.Key(), iterator.Value()) {
break
}
}
}
35 changes: 35 additions & 0 deletions pkg/treemap/custom_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package treemap

import "testing"

func TestMapRange(t *testing.T) {
m := New[int, string]()

m.Put(5, "e")
m.Put(6, "f")
m.Put(7, "g")
m.Put(3, "c")
m.Put(4, "d")
m.Put(1, "x")
m.Put(2, "b")

expectedKey := 1
m.Range(func(key int, value string) bool {
if key != expectedKey {
t.Errorf("[Range] expected %d, got %d", expectedKey, key)
return false
}
expectedKey++
return true
})

expectedKey = 7
m.ReverseRange(func(key int, value string) bool {
if key != expectedKey {
t.Errorf("[ReverseRange] expected %d, got %d", expectedKey, key)
return false
}
expectedKey--
return true
})
}