Skip to content

Commit b420081

Browse files
cleitonmarxCleiton Marques Souza
and
Cleiton Marques Souza
authored
Adds ToChannelT function (#94)
Co-authored-by: Cleiton Marques Souza <[email protected]>
1 parent 55c110a commit b420081

File tree

3 files changed

+48
-1
lines changed

3 files changed

+48
-1
lines changed

example_test.go

+16-1
Original file line numberDiff line numberDiff line change
@@ -1296,7 +1296,6 @@ func ExampleQuery_Take() {
12961296
fmt.Printf("The top three grades are: %v", topThreeGrades)
12971297
// Output:
12981298
// The top three grades are: [98 92 85]
1299-
13001299
}
13011300

13021301
// The following code example demonstrates how to use TakeWhile
@@ -1354,6 +1353,22 @@ func ExampleQuery_ToChannel() {
13541353
// 10
13551354
}
13561355

1356+
// The following code example demonstrates how to use ToChannelT
1357+
// to send a slice to a typed channel.
1358+
func ExampleQuery_ToChannelT() {
1359+
c := make(chan string)
1360+
1361+
go Repeat("ten", 3).ToChannelT(c)
1362+
1363+
for i := range c {
1364+
fmt.Println(i)
1365+
}
1366+
// Output:
1367+
// ten
1368+
// ten
1369+
// ten
1370+
}
1371+
13571372
// The following code example demonstrates how to use ToMap to populate a map.
13581373
func ExampleQuery_ToMap() {
13591374
type Product struct {

result.go

+16
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,22 @@ func (q Query) ToChannel(result chan<- interface{}) {
544544
close(result)
545545
}
546546

547+
// ToChannelT is the typed version of ToChannel.
548+
//
549+
// - result is of type "chan TSource"
550+
//
551+
// NOTE: ToChannel has better performance than ToChannelT.
552+
func (q Query) ToChannelT(result interface{}) {
553+
r := reflect.ValueOf(result)
554+
next := q.Iterate()
555+
556+
for item, ok := next(); ok; item, ok = next() {
557+
r.Send(reflect.ValueOf(item))
558+
}
559+
560+
r.Close()
561+
}
562+
547563
// ToMap iterates over a collection and populates result map with elements.
548564
// Collection elements have to be of KeyValue type to use this method. To
549565
// populate a map with elements of different type use ToMapBy method. ToMap

result_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,22 @@ func TestToChannel(t *testing.T) {
464464
}
465465
}
466466

467+
func TestToChannelT(t *testing.T) {
468+
c := make(chan string)
469+
input := []string{"1", "2", "3", "4", "5"}
470+
471+
go From(input).ToChannelT(c)
472+
473+
result := []string{}
474+
for value := range c {
475+
result = append(result, value)
476+
}
477+
478+
if !reflect.DeepEqual(result, input) {
479+
t.Errorf("From(%v).ToChannelT()=%v expected %v", input, result, input)
480+
}
481+
}
482+
467483
func TestToMap(t *testing.T) {
468484
input := make(map[int]bool)
469485
input[1] = true

0 commit comments

Comments
 (0)