This repository has been archived by the owner on Dec 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproduct.go
95 lines (73 loc) · 1.56 KB
/
product.go
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package planner
import "sync"
// Producter is an interface for retrieving products.
type Producter interface {
// Product returns a Product and an error.
Product() (Product, error)
}
func mergeProducts(producters ...Producter) (Product, error) {
var wg sync.WaitGroup
var m sync.Mutex
errors := make([]error, len(producters))
products := make([]Product, len(producters))
for i, p := range producters {
wg.Add(1)
i := i
p := p
go func() {
defer wg.Done()
defer m.Unlock()
p, err := p.Product()
m.Lock()
if err != nil {
errors[i] = err
return
}
products[i] = p
}()
}
wg.Wait()
var p Product
for _, err := range errors {
if err != nil {
return p, err
}
}
for _, product := range products {
p = p.Merge(product)
}
return p, nil
}
// Merge takes another product and replaces zero values.
func (p Product) Merge(p2 Product) Product {
var merged Product
merged.Name = p.Name
if merged.Name == "" {
merged.Name = p2.Name
}
merged.Description = p.Description
if merged.Description == "" {
merged.Description = p2.Description
}
merged.Price = p.Price
if merged.Price == 0 {
merged.Price = p2.Price
}
merged.URL = p.URL
if merged.URL == "" {
merged.URL = p2.URL
}
merged.Image = p.Image
if merged.Image == "" {
merged.Image = p2.Image
}
merged.OriginalImage = p.OriginalImage
if merged.OriginalImage == "" {
merged.OriginalImage = p2.OriginalImage
}
merged.PossibleImages = p.PossibleImages
if merged.PossibleImages == nil {
merged.PossibleImages = p2.PossibleImages
}
return merged
}