Skip to content

Commit 057d954

Browse files
authored
Range over channel exercise (#170)
2 parents ac12867 + 5bf8943 commit 057d954

File tree

4 files changed

+58
-1
lines changed

4 files changed

+58
-1
lines changed

internal/exercises/catalog.yaml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,11 @@ concepts:
236236
- Use `sync/atomic` package to create and increment atomic counter.
237237
- Launch 10,000 anonymous go routines that simultaneously increment the counter.
238238
- Use WaitGroups to wait for all go routines to finish.
239-
239+
- slug: 45_range_over_channels
240+
title: Range over channels
241+
test_regex: ".*"
242+
hints:
243+
- Use `for i := range ch {...}` syntax to range over a channels.
240244

241245
projects:
242246
- slug: 101_text_analyzer
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package range_over_channels
2+
3+
func getEvents(ch chan<- int) {
4+
for i := range 10 {
5+
ch <- i
6+
}
7+
close(ch)
8+
}
9+
10+
func processStream() int {
11+
ch := make(chan int)
12+
go getEvents(ch)
13+
14+
sum := 0
15+
for event := range ch {
16+
sum += event
17+
}
18+
return sum
19+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package range_over_channels
2+
3+
// Assume case where you receive stream of events
4+
// through a channel till it is closed.
5+
// And you process those events as they come through.
6+
7+
func getEvents(ch chan<- int) {
8+
for i := range 10 {
9+
ch <- i
10+
}
11+
close(ch)
12+
}
13+
14+
// TODO: 1. Range over the channel, calculate the sum from events and return it.
15+
func processStream() int {
16+
ch := make(chan int)
17+
go getEvents(ch)
18+
19+
return 0
20+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package range_over_channels
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestRangeOverChannels(t *testing.T) {
8+
got := processStream()
9+
want := 45
10+
11+
if got != want {
12+
t.Fatalf("Expected %v, got %v", want, got)
13+
}
14+
}

0 commit comments

Comments
 (0)