Skip to content

Commit

Permalink
add All method for iteration using range over func
Browse files Browse the repository at this point in the history
  • Loading branch information
makiuchi-d committed Sep 1, 2024
1 parent b1ec5b1 commit edeab38
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 1 deletion.
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,24 @@ func main() {
e2 := linq.Where(e1, func(s Student) (bool, error) { return s.Class == "1-B", nil })
e3 := linq.OrderByDescending(e2, func(s Student) (int, error) { return s.Score, nil })

linq.ForEach(e3, func(s Student) error {
// go1.23.0 or later
for s, err := range e3.All() {
if err != nil {
panic(err)
}
fmt.Printf("%d %s\n", s.Score, s.Name)
}

fmt.Println("----")

// it also works in older go
err := linq.ForEach(e3, func(s Student) error {
fmt.Printf("%d %s\n", s.Score, s.Name)
return nil
})
if err != nil {
panic(err)
}
}
```

Expand All @@ -60,6 +74,11 @@ Output:
425 山路 信之
405 緒方 俊
136 星 雅彦
----
594 三宅 直人
425 山路 信之
405 緒方 俊
136 星 雅彦
```

## Functions
Expand Down
34 changes: 34 additions & 0 deletions iter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//go:build go1.23

package linq

import "iter"

func (e Enumerable[T]) All() iter.Seq2[T, error] {
return iterAll(e())
}

func (e OrderedEnumerable[T]) All() iter.Seq2[T, error] {
return iterAll(e())
}

func iterAll[T any, E Enumerator[T]](e E) iter.Seq2[T, error] {
return func(yield func(T, error) bool) {
for {
v, err := e.Next()
if err != nil {
if isEOC(err) {
return
}
}

if !yield(v, err) {
return
}

if err != nil {
return
}
}
}
}
25 changes: 25 additions & 0 deletions iter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//go:build go1.23

package linq_test

import (
"testing"

"github.com/makiuchi-d/linq/v2"
)

func TestIterAll(t *testing.T) {
src := linq.FromSlice([]int{1, 2, 3, 4, 5})
c := 0
s := 0
for n, err := range src.All() {
if err != nil {
t.Fatalf("%v", err)
}
c++
s += n
}
if c != 5 || s != 15 {
t.Fatalf("(c, s) = (%v, %v) wants (%v, %v)", c, s, 5, 15)
}
}

0 comments on commit edeab38

Please sign in to comment.