Skip to content

Commit

Permalink
HW06 correct for range
Browse files Browse the repository at this point in the history
  • Loading branch information
DimVlas committed Jun 9, 2024
1 parent ac39bad commit 3036f7e
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 2 deletions.
12 changes: 10 additions & 2 deletions hw06_pipeline_execution/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,19 @@ func chanWrap(in In, done In) Out {
go func() {
defer close(out)

for val := range in {
for {
select {
case out <- val:
case <-done:
return
case val, ok := <-in:
if !ok {
return
}
select {
case <-done:
return
case out <- val:
}
}
}
}()
Expand Down
76 changes: 76 additions & 0 deletions hw06_pipeline_execution/pipeline_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,79 @@ func TestPipeline(t *testing.T) {
require.Equal(t, []string{}, result)
})
}

func TestChanWrap(t *testing.T) {
t.Run("To end", func(t *testing.T) {
in := make(Bi)
done := make(Bi)
data := []int{1, 2, 3, 4, 5}

go func() {
for _, v := range data {
in <- v
time.Sleep(time.Millisecond * 10)
}
close(in)
}()

res := make([]int, 0, 5)
for i := range chanWrap(in, done) {
res = append(res, i.(int))
}

require.Len(t, res, 5)
require.Equal(t, []int{1, 2, 3, 4, 5}, res)
})

t.Run("Close Done", func(t *testing.T) {
in := make(Bi)
done := make(Bi)
data := []int{1, 2, 3, 4, 5}

go func() {
for i, v := range data {
if i == 2 {
close(done)
return
}
in <- v
time.Sleep(time.Millisecond * 10)
}
close(in)
}()

res := make([]int, 0, 5)
for i := range chanWrap(in, done) {
res = append(res, i.(int))
}

require.Len(t, res, 2)
require.Equal(t, []int{1, 2}, res)
})

t.Run("Close In", func(t *testing.T) {
in := make(Bi)
done := make(Bi)
data := []int{1, 2, 3, 4, 5}

go func() {
for i, v := range data {
if i == 2 {
close(in)
return
}
in <- v
time.Sleep(time.Millisecond * 10)
}
close(in)
}()

res := make([]int, 0, 5)
for i := range chanWrap(in, done) {
res = append(res, i.(int))
}

require.Len(t, res, 2)
require.Equal(t, []int{1, 2}, res)
})
}

0 comments on commit 3036f7e

Please sign in to comment.