/
difference.go
51 lines (41 loc) · 962 Bytes
/
difference.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
package balance
type differenceOperation int
const (
add differenceOperation = 0
del differenceOperation = 1
)
type chunk struct {
operation differenceOperation
endpoint Endpoint
}
func isIn(needle Endpoint, haystack []Endpoint) bool {
for i := range haystack {
if haystack[i].Key() == needle.Key() {
return true
}
}
return false
}
// diff is a - b, the classical set difference.
func diff(a, b []Endpoint) []Endpoint {
var result []Endpoint
// We assume the slices are small enough that a O(1) check with maps isn't an
// optimization, nor is sorting the slices for early return.
for i := range a {
if isIn(a[i], b) {
continue
}
result = append(result, a[i])
}
return result
}
func difference(old, new []Endpoint) []chunk {
var chunks []chunk
for _, e := range diff(old, new) {
chunks = append(chunks, chunk{del, e})
}
for _, e := range diff(new, old) {
chunks = append(chunks, chunk{add, e})
}
return chunks
}