Skip to content

Instantly share code, notes, and snippets.

@zbarnes757
Created November 15, 2018 09:19
Show Gist options
  • Save zbarnes757/acc068ee79d79b359f7d764ac22f96e1 to your computer and use it in GitHub Desktop.
Save zbarnes757/acc068ee79d79b359f7d764ac22f96e1 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
)
var chan1 = make(chan string)
var chan2 = make(chan string)
func main() {
fmt.Println(channelMagic(1, 0))
fmt.Println(channelMagic(0, 1))
fmt.Println(channelMagic(1, 1))
}
func channelMagic(sleepOne int, sleepTwo int) string {
go func() {
time.Sleep(time.Duration(sleepOne) * time.Second)
chan1 <- "I made it to channel one!"
}()
go func() {
time.Sleep(time.Duration(sleepTwo) * time.Second)
chan2 <- "I made it to channel two!"
}()
time.Sleep(time.Duration(10) * time.Millisecond)
select {
case v := <-chan1:
return v
case v := <-chan2:
return v
default:
return "Nothing from the channels"
}
}
package main
import "testing"
func Test_channelMagic(t *testing.T) {
type args struct {
sleepOne int
sleepTwo int
}
tests := []struct {
name string
args args
want string
}{
{
name: "First Channel",
args: args{0, 1},
want: "I made it to channel one!",
},
{
name: "Second Channel",
args: args{1, 0},
want: "I made it to channel two!",
},
{
name: "No Channels",
args: args{1, 1},
want: "Nothing from the channels",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := channelMagic(tt.args.sleepOne, tt.args.sleepTwo); got != tt.want {
t.Errorf("channelMagic() = %v, want %v", got, tt.want)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment