summaryrefslogtreecommitdiffhomepage
path: root/packages/tui/internal/util/concurrency.go
blob: d24c7f974d38815270894207aaddd5dd39efa710 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package util

import (
	"strings"
)

func mapParallel[in, out any](items []in, fn func(in) out) chan out {
	mapChans := make([]chan out, 0, len(items))

	for _, v := range items {
		ch := make(chan out)
		mapChans = append(mapChans, ch)
		go func() {
			defer close(ch)
			ch <- fn(v)
		}()
	}

	resultChan := make(chan out)

	go func() {
		defer close(resultChan)
		for _, ch := range mapChans {
			v := <-ch
			resultChan <- v
		}
	}()

	return resultChan
}

// WriteStringsPar allows to iterate over a list and compute strings in parallel,
// yet write them in order.
func WriteStringsPar[a any](sb *strings.Builder, items []a, fn func(a) string) {
	ch := mapParallel(items, fn)

	for v := range ch {
		sb.WriteString(v)
	}
}