2018-08-08 14:37:04 +00:00
|
|
|
package lib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"container/heap"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
)
|
|
|
|
|
2018-08-17 23:44:00 +00:00
|
|
|
type heapItem struct {
|
|
|
|
Value string
|
|
|
|
ScoreVal float64
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *heapItem) Data() interface{} {
|
|
|
|
return h.Value
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *heapItem) Score() float64 {
|
|
|
|
return h.ScoreVal
|
|
|
|
}
|
|
|
|
|
2018-08-08 14:37:04 +00:00
|
|
|
func TestScoreHeap(t *testing.T) {
|
|
|
|
type testCase struct {
|
|
|
|
desc string
|
|
|
|
items map[string]float64
|
2018-08-17 23:44:00 +00:00
|
|
|
expected []*heapItem
|
2018-08-08 14:37:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
cases := []testCase{
|
|
|
|
{
|
|
|
|
desc: "More than K elements",
|
|
|
|
items: map[string]float64{
|
|
|
|
"banana": 3.0,
|
|
|
|
"apple": 2.25,
|
|
|
|
"pear": 2.32,
|
|
|
|
"watermelon": 5.45,
|
|
|
|
"orange": 0.20,
|
|
|
|
"strawberry": 9.03,
|
|
|
|
"blueberry": 0.44,
|
|
|
|
"lemon": 3.9,
|
|
|
|
"cherry": 0.03,
|
|
|
|
},
|
2018-08-17 23:44:00 +00:00
|
|
|
expected: []*heapItem{
|
|
|
|
{Value: "pear", ScoreVal: 2.32},
|
|
|
|
{Value: "banana", ScoreVal: 3.0},
|
|
|
|
{Value: "lemon", ScoreVal: 3.9},
|
|
|
|
{Value: "watermelon", ScoreVal: 5.45},
|
|
|
|
{Value: "strawberry", ScoreVal: 9.03},
|
2018-08-08 14:37:04 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
{
|
|
|
|
desc: "Less than K elements",
|
|
|
|
items: map[string]float64{
|
|
|
|
"eggplant": 9.0,
|
|
|
|
"okra": -1.0,
|
|
|
|
"corn": 0.25,
|
|
|
|
},
|
2018-08-17 23:44:00 +00:00
|
|
|
expected: []*heapItem{
|
|
|
|
{Value: "okra", ScoreVal: -1.0},
|
|
|
|
{Value: "corn", ScoreVal: 0.25},
|
|
|
|
{Value: "eggplant", ScoreVal: 9.0},
|
2018-08-08 14:37:04 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, tc := range cases {
|
|
|
|
t.Run("", func(t *testing.T) {
|
|
|
|
// Create Score heap, push elements into it
|
|
|
|
pq := NewScoreHeap(5)
|
|
|
|
for value, score := range tc.items {
|
2018-08-17 23:44:00 +00:00
|
|
|
heapItem := &heapItem{
|
|
|
|
Value: value,
|
|
|
|
ScoreVal: score,
|
2018-08-08 14:37:04 +00:00
|
|
|
}
|
|
|
|
heap.Push(pq, heapItem)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Take the items out; they arrive in increasing Score order
|
|
|
|
require := require.New(t)
|
|
|
|
require.Equal(len(tc.expected), pq.Len())
|
|
|
|
|
|
|
|
i := 0
|
|
|
|
for pq.Len() > 0 {
|
2018-08-17 23:44:00 +00:00
|
|
|
item := heap.Pop(pq).(*heapItem)
|
2018-08-08 14:37:04 +00:00
|
|
|
require.Equal(tc.expected[i], item)
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|