-
Notifications
You must be signed in to change notification settings - Fork 1
/
element.go
71 lines (59 loc) · 1.38 KB
/
element.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
package hranoprovod
import (
"sort"
)
// Element contains single element data
type Element struct {
Name string
Value float64
}
// Elements contains array of elements
type Elements []Element
// NewElement creates new element
func NewElement(name string, val float64) Element {
el := &Element{name, val}
return *el
}
// NewElements creates new element list
func NewElements() Elements {
return Elements{}
}
// Add adds new element to the list
func (el *Elements) Add(name string, val float64) {
*el = append(*el, NewElement(name, val))
}
// Index returns the index of the element by name
func (el *Elements) Index(name string) (int, bool) {
for n, e := range *el {
if e.Name == name {
return n, true
}
}
return 0, false
}
// SumMerge merges the element list with new one multiplied by mult
func (el *Elements) SumMerge(left Elements, mult float64) {
for _, v := range left {
if ndx, exists := (*el).Index(v.Name); exists {
(*el)[ndx].Value += v.Value * mult
} else {
(*el).Add(v.Name, v.Value*mult)
}
}
}
// Len returns the length of the element list
func (el Elements) Len() int {
return len(el)
}
// Less compares two elements
func (el Elements) Less(i, j int) bool {
return el[i].Name < el[j].Name
}
// Swap swaps two elements
func (el Elements) Swap(i, j int) {
el[i], el[j] = el[j], el[i]
}
// Sort sorts the element list
func (el Elements) Sort() {
sort.Sort(el)
}