Skip to content

Commit

Permalink
add FromIterator
Browse files Browse the repository at this point in the history
  • Loading branch information
makiuchi-d committed Sep 16, 2024
1 parent 0274501 commit ffbf93f
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
29 changes: 28 additions & 1 deletion iter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

package linq

import "iter"
import (
"context"
"iter"
)

// All returns an iterator function
func (e Enumerable[T]) All() iter.Seq2[T, error] {
Expand Down Expand Up @@ -45,3 +48,27 @@ func (e OrderedEnumerable[T]) All() iter.Seq2[T, error] {
}
}
}

// FromIterator generates an IEnumerable[T] from an iterator function.
func FromIterator[T any](ctx context.Context, it iter.Seq[T]) Enumerable[T] {
return Generator(ctx, func(yield func(T) error) error {
for v := range it {
if err := yield(v); err != nil {
return err
}
}
return nil
})
}

// FromIterator2 generates an IEnumerable[KeyValue[K,V]] from an iterator function.
func FromIterator2[K comparable, V any](ctx context.Context, it iter.Seq2[K, V]) Enumerable[KeyValue[K, V]] {
return Generator(ctx, func(yield func(KeyValue[K, V]) error) error {
for k, v := range it {
if err := yield(KeyValue[K, V]{k, v}); err != nil {
return err
}
}
return nil
})
}
37 changes: 37 additions & 0 deletions iter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
package linq_test

import (
"context"
"reflect"
"testing"

"github.com/makiuchi-d/linq/v2"
Expand All @@ -23,3 +25,38 @@ func TestIterAll(t *testing.T) {
t.Fatalf("(c, s) = (%v, %v) wants (%v, %v)", c, s, 5, 15)
}
}

func TestFromIterator(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
e := linq.FromIterator(ctx, func(yield func(int) bool) {
_ = yield(1) && yield(2) && yield(3) && yield(4) && yield(5)
})
e = linq.Take(e, 3)

a, err := linq.ToSlice(e)
if err != nil {
t.Fatalf("%+v", err)
}
exp := []int{1, 2, 3}
if !reflect.DeepEqual(a, exp) {
t.Fatalf("ToSlice: %v, wants %v", a, exp)
}
}

func TestFromIterator2(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
e := linq.FromIterator2(ctx, func(yield func(int, string) bool) {
_ = yield(1, "one") && yield(2, "two") && yield(3, "three")
})

a, err := linq.ToMap(e)
if err != nil {
t.Fatalf("%+v", err)
}
exp := map[int]string{1: "one", 2: "two", 3: "three"}
if !reflect.DeepEqual(a, exp) {
t.Fatalf("ToMap: %v, wants %v", a, exp)
}
}

0 comments on commit ffbf93f

Please sign in to comment.