Initial commit

This commit is contained in:
2024-05-30 19:42:26 +03:00
commit f04111c689
13 changed files with 455 additions and 0 deletions

42
worker/pool.go Normal file
View File

@@ -0,0 +1,42 @@
package worker
import (
"context"
"fmt"
"sync"
"go.uber.org/zap"
)
func NewPool(in <-chan [10]int, workersNum uint, log *zap.Logger) *Pool {
out := make(chan [3]int, workersNum)
return &Pool{
in: in,
out: out,
workersNum: int(workersNum),
log: log,
}
}
type Pool struct {
in <-chan [10]int
out chan [3]int
workersNum int
log *zap.Logger
}
func (p *Pool) Start(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
wg.Add(p.workersNum)
for i := 0; i < p.workersNum; i++ {
go NewWorker(p.in, p.out, p.log.Named(fmt.Sprintf("worker_%d", i))).Start(ctx, wg)
}
}
func (p *Pool) Out() <-chan [3]int {
return p.out
}

51
worker/worker.go Normal file
View File

@@ -0,0 +1,51 @@
package worker
import (
"context"
"sort"
"sync"
"go.uber.org/zap"
)
func NewWorker(in <-chan [10]int, out chan<- [3]int, log *zap.Logger) *Worker {
return &Worker{
in: in,
out: out,
log: log,
}
}
type Worker struct {
in <-chan [10]int
out chan<- [3]int
log *zap.Logger
}
func (w *Worker) Start(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case m, ok := <-w.in:
if !ok {
return
}
w.out <- w.findMax(m)
}
}
}
func (w *Worker) findMax(input [10]int) [3]int {
sort.Ints(input[:])
res := [3]int(input[7:])
w.log.Debug("new data", zap.Ints("input", input[:]), zap.Ints("output", res[:]))
return res
}

43
worker/worker_test.go Normal file
View File

@@ -0,0 +1,43 @@
package worker
import (
"reflect"
"strconv"
"testing"
)
func TestWorker_findMax(t *testing.T) {
t.Parallel()
tests := []struct {
in [10]int
out [3]int
}{
{
in: [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
out: [3]int{8, 9, 10},
},
{
in: [10]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1},
out: [3]int{8, 9, 10},
},
{
in: [10]int{9, 7, 6, 10, 5, 4, 3, 8, 1},
out: [3]int{8, 9, 10},
},
}
for idx, tt := range tests {
tt := tt
t.Run(strconv.Itoa(idx), func(t *testing.T) {
t.Parallel()
w := &Worker{}
if got := w.findMax(tt.in); !reflect.DeepEqual(got, tt.out) {
t.Errorf("findMax() = %v, want %v", got, tt.out)
}
})
}
}