mchirico / zDaily

Playground to hack and test ideas with Zoe
1 stars 2 forks source link

Day 11: Create Your Own Program #13

Open mchirico opened 3 years ago

mchirico commented 3 years ago

Creative...

Today create your own program. I personally try to do this every day, as a warm up exercise. Here's the program I created today..

You can do anything you want; but, please show me the code!

repl.it

package main

import (
    "context"
    "fmt"
    "time"
)

func process(ctx context.Context, c <-chan int, cx2 chan int, tc chan<- []int) {
    run := true
    total := []int{}
    for run {
        select {
        case val := <-c:
            cx2 <- val * 2
            total = append(total, val)
        case <-ctx.Done():
            fmt.Printf("Caught ctx\n")
            run = false
            close(cx2)
        }
    }
    tc <- total
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 9500*time.Millisecond)
    defer cancel()

    c := make(chan int)
    cx2 := make(chan int)
    tc := make(chan []int)

    go func() {
        s := []int{7, 2, 8, -9, 4, 0, 5, 1}
        for _, v := range s {
            c <- v
            time.Sleep(250*time.Millisecond)
        }
    }()

    go process(ctx, c, cx2, tc)

    run := true
    for run {
        select {
        case val := <-cx2:
            fmt.Println("double:", val)
        case val := <-tc:
            fmt.Println("done: ", val)
            run = false
        default:
        }
    }

}
tacomonkautobot[bot] commented 3 years ago

mchirico, Thanks for opening this issue!

ZoeChiri commented 3 years ago

https://repl.it/join/drgrwpjw-zoechirico