github.com/haraldrudell/parl@v0.4.176/pqs/priority-queue_test.go (about) 1 /* 2 © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package pqs 7 8 import ( 9 "strconv" 10 "testing" 11 12 "github.com/haraldrudell/parl" 13 ) 14 15 func TestNewRanking(t *testing.T) { 16 type entity struct{ value int } 17 value1 := 1 18 value2 := 2 19 value3 := 3 20 value4 := 4 21 entity1 := entity{value: value1} 22 entity2 := entity{value: value3} 23 entity3 := entity{value: value2} 24 entityStringMap := map[*entity]string{ 25 &entity1: "entity1", 26 &entity2: "entity2", 27 &entity3: "entity3", 28 } 29 ranker := func(entityN *entity) (rank int) { 30 return entityN.value 31 } 32 exp1 := []*entity{&entity2, &entity3, &entity1} 33 exp2 := []*entity{&entity1, &entity2, &entity3} 34 exp3 := []*entity{&entity1} 35 expLength := 3 36 37 var ranking parl.PriorityQueue[entity, int] 38 var pmapsRanking *PriorityQueue[entity, int] 39 var ok bool 40 var rankList []*entity 41 var length int 42 isSameRanking := func(a, b []*entity) (isSame bool) { 43 if len(a) != len(b) { 44 return 45 } 46 for i, entityp := range a { 47 if entityp != b[i] { 48 return 49 } 50 } 51 return true 52 } 53 makeListPrintable := func(entities []*entity) (result []string) { 54 result = make([]string, len(entities)) 55 for i, entityp := range entities { 56 // strconv.Quote prints empty strings real well 57 result[i] = strconv.Quote(entityStringMap[entityp]) 58 } 59 return 60 } 61 62 ranking = NewPriorityQueue(ranker) 63 if pmapsRanking, ok = ranking.(*PriorityQueue[entity, int]); !ok { 64 t.Error("type asserton failed") 65 t.FailNow() 66 } 67 68 // AddOrUpdate 69 ranking.AddOrUpdate(&entity1) 70 ranking.AddOrUpdate(&entity2) 71 ranking.AddOrUpdate(&entity3) 72 entity1.value = value4 73 if length = len(pmapsRanking.m); length != expLength { 74 t.Errorf("bad map length1 %d exp %d", length, expLength) 75 } 76 if pmapsRanking.queue.Length(); length != expLength { 77 t.Errorf("bad Length1 %d exp %d", length, expLength) 78 } 79 if rankList = ranking.List(); !isSameRanking(rankList, exp1) { 80 t.Errorf("bad list1 %v exp %v", makeListPrintable(rankList), makeListPrintable(exp1)) 81 } 82 83 // List 84 ranking.AddOrUpdate(&entity1) 85 if length = len(pmapsRanking.m); length != expLength { 86 t.Errorf("bad length2 %d exp %d", length, expLength) 87 } 88 if rankList = ranking.List(); !isSameRanking(rankList, exp2) { 89 t.Errorf("bad list2 %v exp %v", makeListPrintable(rankList), makeListPrintable(exp2)) 90 } 91 92 if rankList = ranking.List(1); !isSameRanking(rankList, exp3) { 93 t.Errorf("bad list3 %v exp %v", makeListPrintable(rankList), makeListPrintable(exp3)) 94 } 95 96 // rankNode 97 entity2.value = value1 98 ranking.AddOrUpdate(&entity2) 99 entity1.value = value1 100 ranking.AddOrUpdate(&entity1) 101 entity3.value = value1 102 ranking.AddOrUpdate(&entity3) 103 }