File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -75,3 +75,22 @@ func Or[T comparable](vals ...T) T {
75
75
}
76
76
return zero
77
77
}
78
+
79
+ // CompareBy returns a comparison function for values of type V.
80
+ // The comparison is based on a key function that transforms each value
81
+ // of type V into a comparable type K (which must satisfy the Ordered constraint).
82
+ // The resulting comparison function can be used in sorting or other comparisons.
83
+ //
84
+ // This is similar to Python's key functions and integrates well with
85
+ // other proposed features like Reverse (#65632).
86
+ //
87
+ // Example usage:
88
+ //
89
+ // people := []Person{{"Alice", 30}, {"Bob", 25}}
90
+ // sort.Slice(people, cmp.CompareBy(func(p Person) int { return p.Age }))
91
+ func CompareBy [K Ordered , V any ](key func (V ) K ) func (V , V ) int {
92
+ return func (a , b V ) int {
93
+ // Compare the transformed values using the Compare function
94
+ return Compare (key (a ), key (b ))
95
+ }
96
+ }
Original file line number Diff line number Diff line change @@ -176,3 +176,30 @@ func ExampleOr_sort() {
176
176
// bar carol 1.00
177
177
// baz carol 4.00
178
178
}
179
+
180
+ func TestCompareBy (t * testing.T ) {
181
+ type Person struct {
182
+ Name string
183
+ Age int
184
+ }
185
+
186
+ // Key function to extract age for comparison
187
+ byAge := cmp .CompareBy (func (p Person ) int {
188
+ return p .Age
189
+ })
190
+
191
+ // Test data
192
+ alice := Person {Name : "Alice" , Age : 30 }
193
+ bob := Person {Name : "Bob" , Age : 25 }
194
+
195
+ // Test comparisons
196
+ if got := byAge (alice , bob ); got <= 0 {
197
+ t .Errorf ("expected Alice > Bob by age, got %d" , got )
198
+ }
199
+ if got := byAge (bob , alice ); got >= 0 {
200
+ t .Errorf ("expected Bob < Alice by age, got %d" , got )
201
+ }
202
+ if got := byAge (alice , alice ); got != 0 {
203
+ t .Errorf ("expected Alice == Alice by age, got %d" , got )
204
+ }
205
+ }
You can’t perform that action at this time.
0 commit comments