Skip to content
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

Proposal: Add MinByKey and MaxByKey #141

Open
eliaperantoni opened this issue May 20, 2022 · 0 comments
Open

Proposal: Add MinByKey and MaxByKey #141

eliaperantoni opened this issue May 20, 2022 · 0 comments

Comments

@eliaperantoni
Copy link

Say you have a collection and want to find the element that minimizes or maximizes a function.

For example, here I have a slice of person structs and am looking for the one for which the computeAge method returns the lowest value:

type person struct {
	name     string
	birthday time.Time
}

func (p *person) computeAge() int {
	age := time.Now().Year() - p.birthday.Year() - 1
	if p.birthday.YearDay() < time.Now().YearDay() {
		age += 1
	}
	return age
}

func main() {
	people := []person{
		{"Jordan", time.Date(1994, time.October, 2, 0, 0, 0, 0, time.UTC)},
		{"Emily", time.Date(1868, time.March, 26, 0, 0, 0, 0, time.UTC)},
		{"Micheal", time.Date(1999, time.June, 5, 0, 0, 0, 0, time.UTC)},
		{"Nikola", time.Date(2001, time.November, 16, 0, 0, 0, 0, time.UTC)},
		{"Rachel", time.Date(1993, time.April, 1, 0, 0, 0, 0, time.UTC)},
	}

	youngest := lo.MinBy(people, func(a, b person) bool {
		return a.computeAge() < b.computeAge()
	})
	fmt.Println(youngest.name)
}

Using MinBy like this results in 8 calls to computeAge where 5 should have sufficed. Using a custom keying function with MinBy results in many more calls than necessary.


I propose adding a MinByKey and MaxByKey functions that apply the custom keying function to all elements and then return the one that minimizes/maximizes it.

The signatures would be:

func MinByKey[T any, K constraints.Ordered](collection []T, key func(T) K) T
func MaxByKey[T any, K constraints.Ordered](collection []T, key func(T) K) T

Would this contribution be appreciated @samber ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant