Skip to content

Commit 7b6bcc3

Browse files
committed
🚀 cmp: Unleash the Power of Custom Comparisons with the CompareBy Function! 🔥💥
1 parent 44a6f81 commit 7b6bcc3

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

‎src/cmp/cmp.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,3 +75,22 @@ func Or[T comparable](vals ...T) T {
7575
}
7676
return zero
7777
}
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+
}

‎src/cmp/cmp_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,3 +176,30 @@ func ExampleOr_sort() {
176176
// bar carol 1.00
177177
// baz carol 4.00
178178
}
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+
}

0 commit comments

Comments
 (0)