Skip to content

Commit

Permalink
Hidden goroutine.
Browse files Browse the repository at this point in the history
  • Loading branch information
cinar committed Dec 19, 2023
1 parent c84107b commit 5e7fa52
Show file tree
Hide file tree
Showing 6 changed files with 16 additions and 21 deletions.
2 changes: 1 addition & 1 deletion helper/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ fmt.Println(helper.ChanToSlice(half)) // [1, 2, 3, 4]
func Drain[T any](c <-chan T)
```

Drain drains the given channel.
Drain drains the given channel. It blocks the caller.

<a name="Duplicate"></a>
## func [Duplicate](<https://github.com/cinar/indicator/blob/v2/helper/duplicate.go#L17>)
Expand Down
4 changes: 1 addition & 3 deletions helper/buffered.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ package helper
func Buffered[T any](c <-chan T, size int) <-chan T {
result := make(chan T, size)

go func() {
Pipe(c, result)
}()
go Pipe(c, result)

return result
}
14 changes: 6 additions & 8 deletions helper/drain.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@

package helper

// Drain drains the given channel.
// Drain drains the given channel. It blocks the caller.
func Drain[T any](c <-chan T) {
go func() {
for {
_, ok := <-c
if !ok {
break
}
for {
_, ok := <-c
if !ok {
break
}
}()
}
}
5 changes: 3 additions & 2 deletions helper/first.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,17 @@ func First[T any](c <-chan T, count int) <-chan T {
result := make(chan T, cap(c))

go func() {
defer close(result)
for i := 0; i < count; i++ {
n, ok := <-c
if !ok {
return
break
}

result <- n
}

close(result)

Drain(c)
}()

Expand Down
10 changes: 4 additions & 6 deletions helper/pipe.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,8 @@ package helper
// helper.Pipe(input, output)
// fmt.println(helper.ChanToSlice(output)) // [2, 4, 6, 8]
func Pipe[T any](f <-chan T, t chan<- T) {
go func() {
defer close(t)
for n := range f {
t <- n
}
}()
defer close(t)
for n := range f {
t <- n
}
}
2 changes: 1 addition & 1 deletion helper/pipe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func TestPipe(t *testing.T) {
input := helper.SliceToChan(expected)
output := make(chan int)

helper.Pipe(input, output)
go helper.Pipe(input, output)
actual := helper.ChanToSlice(output)

if !reflect.DeepEqual(actual, expected) {
Expand Down

0 comments on commit 5e7fa52

Please sign in to comment.