Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
kardolus
GitHub Repository: kardolus/chatgpt-cli
Path: blob/main/vendor/github.com/sagikazarmark/locafero/internal/queue/eager.go
2893 views
1
package queue
2
3
import "sync"
4
5
// NewEager creates a new eager queue.
6
func NewEager[T any]() Queue[T] {
7
return &Eager[T]{}
8
}
9
10
// Eager is a queue that processes items eagerly.
11
type Eager[T any] struct {
12
results []T
13
error error
14
15
mu sync.Mutex
16
}
17
18
// Add implements the [Queue] interface.
19
func (p *Eager[T]) Add(fn func() (T, error)) {
20
p.mu.Lock()
21
defer p.mu.Unlock()
22
23
// Return early if there's an error
24
if p.error != nil {
25
return
26
}
27
28
result, err := fn()
29
if err != nil {
30
p.error = err
31
32
return
33
}
34
35
p.results = append(p.results, result)
36
}
37
38
// Wait implements the [Queue] interface.
39
func (p *Eager[T]) Wait() ([]T, error) {
40
p.mu.Lock()
41
defer p.mu.Unlock()
42
43
if p.error != nil {
44
return nil, p.error
45
}
46
47
results := p.results
48
49
// Reset results for reuse
50
p.results = nil
51
52
return results, nil
53
}
54
55