-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.go
58 lines (47 loc) · 962 Bytes
/
heap.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
package heaptimer
import (
"container/heap"
"time"
)
type Node struct {
Value interface{}
ExpireAt time.Time
}
type Heap []*Node
func NewHeap() *Heap {
container := &Heap{}
heap.Init(container)
return container
}
func (container Heap) Len() int { return len(container) }
func (container Heap) Less(i, j int) bool {
return container[i].ExpireAt.Before(container[j].ExpireAt)
}
func (container Heap) Swap(i, j int) {
container[i], container[j] = container[j], container[i]
}
func (container *Heap) Push(x interface{}) {
item := x.(*Node)
*container = append(*container, item)
}
func (container *Heap) Pop() interface{} {
old := *container
n := len(old)
x := old[n-1]
*container = old[0 : n-1]
return x
}
func (container *Heap) Head() *Node {
n := len(*container)
if n > 0 {
return (*container)[0]
}
return nil
}
func (container *Heap) Tail() *Node {
n := len(*container)
if n > 0 {
return (*container)[n-1]
}
return nil
}