github.com/mailgun/holster/v4@v4.20.0/collections/priority_queue_test.go (about) 1 /* 2 Copyright 2017 Mailgun Technologies Inc 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 package collections_test 17 18 import ( 19 "fmt" 20 "testing" 21 22 "github.com/mailgun/holster/v4/collections" 23 "github.com/stretchr/testify/assert" 24 ) 25 26 func toPtr(i int) interface{} { 27 return &i 28 } 29 30 func toInt(i interface{}) int { 31 return *(i.(*int)) 32 } 33 34 func TestPeek(t *testing.T) { 35 mh := collections.NewPriorityQueue() 36 37 el := &collections.PQItem{ 38 Value: toPtr(1), 39 Priority: 5, 40 } 41 42 mh.Push(el) 43 assert.Equal(t, 1, toInt(mh.Peek().Value)) 44 assert.Equal(t, 1, mh.Len()) 45 46 el = &collections.PQItem{ 47 Value: toPtr(2), 48 Priority: 1, 49 } 50 mh.Push(el) 51 assert.Equal(t, 2, mh.Len()) 52 assert.Equal(t, 2, toInt(mh.Peek().Value)) 53 assert.Equal(t, 2, toInt(mh.Peek().Value)) 54 assert.Equal(t, 2, mh.Len()) 55 56 el = mh.Pop() 57 58 assert.Equal(t, 2, toInt(el.Value)) 59 assert.Equal(t, 1, mh.Len()) 60 assert.Equal(t, 1, toInt(mh.Peek().Value)) 61 62 mh.Pop() 63 assert.Equal(t, 0, mh.Len()) 64 } 65 66 func TestUpdate(t *testing.T) { 67 mh := collections.NewPriorityQueue() 68 x := &collections.PQItem{ 69 Value: toPtr(1), 70 Priority: 4, 71 } 72 y := &collections.PQItem{ 73 Value: toPtr(2), 74 Priority: 3, 75 } 76 z := &collections.PQItem{ 77 Value: toPtr(3), 78 Priority: 8, 79 } 80 mh.Push(x) 81 mh.Push(y) 82 mh.Push(z) 83 assert.Equal(t, 2, toInt(mh.Peek().Value)) 84 85 mh.Update(z, 1) 86 assert.Equal(t, 3, toInt(mh.Peek().Value)) 87 88 mh.Update(x, 0) 89 assert.Equal(t, 1, toInt(mh.Peek().Value)) 90 } 91 92 func ExampleNewPriorityQueue() { 93 queue := collections.NewPriorityQueue() 94 95 queue.Push(&collections.PQItem{ 96 Value: "thing3", 97 Priority: 3, 98 }) 99 100 queue.Push(&collections.PQItem{ 101 Value: "thing1", 102 Priority: 1, 103 }) 104 105 queue.Push(&collections.PQItem{ 106 Value: "thing2", 107 Priority: 2, 108 }) 109 110 // Pops item off the queue according to the priority instead of the Push() order 111 item := queue.Pop() 112 113 fmt.Printf("Item: %s", item.Value.(string)) 114 115 // Output: Item: thing1 116 }