-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathoop.go
67 lines (50 loc) · 1.24 KB
/
oop.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
// Copyright (c) Efficient Go Authors
// Licensed under the Apache License 2.0.
package block
import (
"fmt"
"sort"
"time"
"github.com/google/uuid"
)
// Production-like example of how Go can be used with object-oriented programming paradigm.
// Read more in "Efficient Go"; Example 2-11.
type Block struct {
id uuid.UUID
start, end time.Time
// ...
}
func (b Block) Duration() time.Duration {
return b.end.Sub(b.start)
}
func (b Block) String() string {
return fmt.Sprint(b.id, ": ", b.start.Format(time.RFC3339), "-", b.end.Format(time.RFC3339))
}
type Group struct {
Block
children []uuid.UUID
}
func (g *Group) Merge(b Block) {
if g.end.IsZero() || g.end.Before(b.end) {
g.end = b.end
}
if g.start.IsZero() || g.start.After(b.start) {
g.start = b.start
}
g.children = append(g.children, b.id)
// ...
}
func Compact(blocks ...Block) Block {
sort.Sort(sortable(blocks))
g := &Group{}
g.id = uuid.New()
for _, b := range blocks {
g.Merge(b)
}
return g.Block
}
type sortable []Block
func (s sortable) Len() int { return len(s) }
func (s sortable) Less(i, j int) bool { return s[i].start.Before(s[j].start) }
func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
var _ sort.Interface = sortable{}