From 375f187c63ade964e87eb179ae10b9bea3800f67 Mon Sep 17 00:00:00 2001 From: Eric Bower Date: Wed, 25 Sep 2024 23:42:29 -0400 Subject: [PATCH] refactor(range): use `iter` pkg Having `Range` return an iterator makes it so we can `range` over it like a slice which provides us with better flow control (e.g. `break`, `continue`, and `return`. --- go.mod | 2 +- syncmap.go | 19 +++++++++++-------- syncmap_test.go | 8 +++----- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/go.mod b/go.mod index 1539c26..9b97f97 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ module github.com/antoniomika/syncmap -go 1.18 +go 1.23 diff --git a/syncmap.go b/syncmap.go index 2978dac..025158b 100644 --- a/syncmap.go +++ b/syncmap.go @@ -2,6 +2,7 @@ package syncmap import ( + "iter" "sync" ) @@ -61,14 +62,16 @@ func (m *Map[K, V]) Store(I K, J V) { } // Range will iterate over the data in the Map and apply the func on it. -func (m *Map[K, V]) Range(L func(I K, J V) bool) { - m.ds.Range(func(A, B any) bool { - var C K - var D V +func (m *Map[K, V]) Range() iter.Seq2[K, V] { + return func(yield func(K, V) bool) { + m.ds.Range(func(A, B any) bool { + var C K + var D V - C, _ = A.(K) - D, _ = B.(V) + C, _ = A.(K) + D, _ = B.(V) - return L(C, D) - }) + return yield(C, D) + }) + } } diff --git a/syncmap_test.go b/syncmap_test.go index b9b8a9e..11c046c 100644 --- a/syncmap_test.go +++ b/syncmap_test.go @@ -91,15 +91,13 @@ func TestRange(t *testing.T) { testMap.Store("foo", "bar") testMap.Store("baz", "buz") - testMap.Range(func(a, b string) bool { + for a, b := range testMap.Range() { if a == "foo" || a == "baz" { if b == "bar" || b == "buz" { - return true + continue } } t.Error("expected range data") - - return true - }) + } } -- 2.45.2