Skip to content

Commit

Permalink
Merge pull request #52 from semihbkgr/iterators
Browse files Browse the repository at this point in the history
Adding Go 1.23 Iterator Support
  • Loading branch information
alphadose authored Oct 27, 2024
2 parents 23da600 + f24bcf8 commit fae115c
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 11 deletions.
23 changes: 13 additions & 10 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,24 @@ name: Go

on:
push:
branches: [ main ]
branches: [main]
pull_request:
branches: [ main ]
branches: [main]

jobs:
e2e:
strategy:
matrix:
go-version: ["=1.18", "^1.23"]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4

- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.18
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go-version }}

- name: Test
run: |
go test *.go
- name: Test
run: |
go test -v .
2 changes: 1 addition & 1 deletion e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ func TestGetOrSet(t *testing.T) {
}
}

func TestIterator(t *testing.T) {
func TestForEach(t *testing.T) {
m := New[int, *Animal]()

m.ForEach(func(i int, a *Animal) bool {
Expand Down
26 changes: 26 additions & 0 deletions iterator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//go:build go1.23
// +build go1.23

package haxmap

import "iter"

func (m *Map[K, V]) Iterator() iter.Seq2[K, V] {
return func(yield func(key K, value V) bool) {
for item := m.listHead.next(); item != nil; item = item.next() {
if !yield(item.key, *item.value.Load()) {
return
}
}
}
}

func (m *Map[K, _]) Keys() iter.Seq[K] {
return func(yield func(key K) bool) {
for item := m.listHead.next(); item != nil; item = item.next() {
if !yield(item.key) {
return
}
}
}
}
53 changes: 53 additions & 0 deletions iterator_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//go:build go1.23
// +build go1.23

package haxmap

import (
"testing"
)

func TestIterators(t *testing.T) {
type Value = struct {
key int
}

m := New[int, *Value]()

itemCount := 16
for i := itemCount; i > 0; i-- {
m.Set(i, &Value{i})
}

t.Run("iterator", func(t *testing.T) {
counter := 0
for k, v := range m.Iterator() {
if v == nil {
t.Error("Expecting an object.")
} else if k != v.key {
t.Error("Incorrect key/value pairs")
}

counter++
}

if counter != itemCount {
t.Error("Iterated item count did not match.")
}
})

t.Run("keys", func(t *testing.T) {
counter := 0
for k := range m.Keys() {
_, ok := m.Get(k)
if !ok {
t.Error("The key is not is the map")
}
counter++
}

if counter != itemCount {
t.Error("Iterated item count did not match.")
}
})
}

0 comments on commit fae115c

Please sign in to comment.