Skip to content

πŸš€ cmp: Unleash the Power of Custom Comparisons with the CompareBy Function! πŸ”₯πŸ’₯ #71241

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/cmp/cmp.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,22 @@ func Or[T comparable](vals ...T) T {
}
return zero
}

// CompareBy returns a comparison function for values of type V.
// The comparison is based on a key function that transforms each value
// of type V into a comparable type K (which must satisfy the Ordered constraint).
// The resulting comparison function can be used in sorting or other comparisons.
//
// This is similar to Python's key functions and integrates well with
// other proposed features like Reverse (#65632).
//
// Example usage:
//
// people := []Person{{"Alice", 30}, {"Bob", 25}}
// sort.Slice(people, cmp.CompareBy(func(p Person) int { return p.Age }))
func CompareBy[K Ordered, V any](key func(V) K) func(V, V) int {
return func(a, b V) int {
// Compare the transformed values using the Compare function
return Compare(key(a), key(b))
}
}
27 changes: 27 additions & 0 deletions src/cmp/cmp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,30 @@ func ExampleOr_sort() {
// bar carol 1.00
// baz carol 4.00
}

func TestCompareBy(t *testing.T) {
type Person struct {
Name string
Age int
}

// Key function to extract age for comparison
byAge := cmp.CompareBy(func(p Person) int {
return p.Age
})

// Test data
alice := Person{Name: "Alice", Age: 30}
bob := Person{Name: "Bob", Age: 25}

// Test comparisons
if got := byAge(alice, bob); got <= 0 {
t.Errorf("expected Alice > Bob by age, got %d", got)
}
if got := byAge(bob, alice); got >= 0 {
t.Errorf("expected Bob < Alice by age, got %d", got)
}
if got := byAge(alice, alice); got != 0 {
t.Errorf("expected Alice == Alice by age, got %d", got)
}
}