Skip to content

Commit

Permalink
Add channels example.
Browse files Browse the repository at this point in the history
  • Loading branch information
jbelmont committed May 2, 2017
1 parent 1a18dd6 commit fc29dfe
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
48 changes: 48 additions & 0 deletions channels.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package workshop

import "fmt"

func average(numbers []float64, c chan float64) {
c <- sum(numbers) / float64(len(numbers))
}

func sum(numbers []float64) float64 {
var sum = 0.0
for i := 0; i < len(numbers); i++ {
sum += numbers[i]
}
return float64(sum)
}

func bufferedSum(numbers []float64, c chan float64) {
var sum float64
for i := 0; i < len(numbers); i++ {
sum += numbers[i]
}
c <- sum
}

func channels() {
var numbers = []float64{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
}
c := make(chan float64)
go average(numbers, c)

avg := <-c

assert(avg == 5.5)

c1 := make(chan float64, 10)

numbers2 := []float64{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
}

defer func() {
go bufferedSum(numbers2, c1)
}()

bufferSum := <-c1
fmt.Println(bufferSum)
}
18 changes: 17 additions & 1 deletion practice/closures_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package practice

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestAverage(t *testing.T) {
Expand All @@ -14,7 +16,7 @@ func TestAverage(t *testing.T) {
}
}

func TestStandarDeviation(t *testing.T) {
func TestStandardDeviation(t *testing.T) {
numbers := []float64{
5.3,
2.5,
Expand All @@ -29,3 +31,17 @@ func TestStandarDeviation(t *testing.T) {
t.Error("Expected 2.49 but received ", actual)
}
}

func TestStandardDeviation2(t *testing.T) {
numbers := []float64{
5.3,
2.5,
3.75,
9.55,
8.5,
6.75,
}
actual := standardDeviation(numbers)()
expected := "2.49"
assert.Equal(t, actual, expected)
}

0 comments on commit fc29dfe

Please sign in to comment.