OLD | NEW |
(Empty) | |
| 1 // Copyright 2017 The LUCI Authors. All rights reserved. |
| 2 // Use of this source code is governed under the Apache License, Version 2.0 |
| 3 // that can be found in the LICENSE file. |
| 4 |
| 5 package sortby |
| 6 |
| 7 import ( |
| 8 "sort" |
| 9 "testing" |
| 10 |
| 11 . "github.com/smartystreets/goconvey/convey" |
| 12 ) |
| 13 |
| 14 type CoolStruct struct { |
| 15 A int |
| 16 B int |
| 17 C int |
| 18 } |
| 19 |
| 20 type CoolStructSlice []CoolStruct |
| 21 |
| 22 func (s CoolStructSlice) Len() int { return len(s) } |
| 23 func (s CoolStructSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } |
| 24 |
| 25 // these could be defined inline inside of the Less function, too. |
| 26 func (s CoolStructSlice) LessA(i, j int) bool { return s[i].A < s[j].A } |
| 27 func (s CoolStructSlice) LessB(i, j int) bool { return s[i].B < s[j].B } |
| 28 func (s CoolStructSlice) LessC(i, j int) bool { return s[i].C < s[j].C } |
| 29 |
| 30 func (s CoolStructSlice) Less(i, j int) bool { |
| 31 return Chain{s.LessA, s.LessB, nil, s.LessC}.Use(i, j) |
| 32 } |
| 33 |
| 34 func TestSortBy(t *testing.T) { |
| 35 t.Parallel() |
| 36 |
| 37 Convey("sortby", t, func() { |
| 38 s := CoolStructSlice{ |
| 39 {194, 771, 222}, |
| 40 {209, 28, 300}, |
| 41 {413, 639, 772}, |
| 42 {14, 761, 759}, |
| 43 {866, 821, 447}, |
| 44 {447, 373, 817}, |
| 45 {132, 510, 149}, |
| 46 {778, 513, 156}, |
| 47 {713, 831, 596}, |
| 48 {288, 83, 898}, |
| 49 {679, 688, 903}, |
| 50 {864, 100, 199}, |
| 51 {229, 975, 648}, |
| 52 {381, 290, 156}, |
| 53 {447, 290, 156}, // intentionally partially equal |
| 54 {311, 614, 434}, |
| 55 } |
| 56 |
| 57 sort.Sort(s) |
| 58 |
| 59 So(s, ShouldResemble, CoolStructSlice{ |
| 60 {14, 761, 759}, |
| 61 {132, 510, 149}, |
| 62 {194, 771, 222}, |
| 63 {209, 28, 300}, |
| 64 {229, 975, 648}, |
| 65 {288, 83, 898}, |
| 66 {311, 614, 434}, |
| 67 {381, 290, 156}, |
| 68 {413, 639, 772}, |
| 69 {447, 290, 156}, |
| 70 {447, 373, 817}, |
| 71 {679, 688, 903}, |
| 72 {713, 831, 596}, |
| 73 {778, 513, 156}, |
| 74 {864, 100, 199}, |
| 75 {866, 821, 447}, |
| 76 }) |
| 77 }) |
| 78 } |
OLD | NEW |