github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xcontainer/priority_queue/comparable.go (about) 1 package priority_queue 2 3 import ( 4 "container/heap" 5 6 "github.com/go-board/x-go/types" 7 8 "github.com/go-board/x-go/xsort" 9 ) 10 11 type maxComparableHeap struct{ xsort.ComparableSlice } 12 13 func (m *maxComparableHeap) Less(i, j int) bool { 14 return !m.ComparableSlice.Less(i, j) 15 } 16 17 func (m *maxComparableHeap) Push(x interface{}) { 18 m.ComparableSlice = append(m.ComparableSlice, x.(types.Comparable)) 19 } 20 21 func (m *maxComparableHeap) Pop() interface{} { 22 if m.Len() == 0 { 23 return nil 24 } 25 p := (m.ComparableSlice)[len(m.ComparableSlice)-1] 26 m.ComparableSlice = m.ComparableSlice[:len(m.ComparableSlice)-1] 27 return p 28 } 29 30 type minComparableHeap struct{ xsort.ComparableSlice } 31 32 func (m *minComparableHeap) Push(x interface{}) { 33 m.ComparableSlice = append(m.ComparableSlice, x.(types.Comparable)) 34 } 35 36 func (m *minComparableHeap) Pop() interface{} { 37 if m.Len() == 0 { 38 return nil 39 } 40 p := (m.ComparableSlice)[len(m.ComparableSlice)-1] 41 m.ComparableSlice = m.ComparableSlice[:len(m.ComparableSlice)-1] 42 return p 43 } 44 45 func NewComparablePriorityQueue(max bool, items ...types.Comparable) *PriorityQueue { 46 var h heap.Interface 47 if max { 48 h = &maxComparableHeap{items} 49 } else { 50 h = &minComparableHeap{items} 51 } 52 return NewPriorityQueue(h) 53 }