mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
Replaces O(n²) bubble sort algorithm with O(n log n) slices.SortFunc from the standard library, delivering massive performance improvements. Performance improvements: - Large dataset (1000 items): 2,121,531 ns/op → 3,372 ns/op (629x faster!) - Small dataset (10 items): 199 ns/op → 178 ns/op (10% faster) - Time reduction: 99.84% for large datasets Resolves the TODO comment about replacing the simple algorithm. Also adds comprehensive benchmarks for both small and large datasets to track performance regressions. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
21 lines
546 B
Go
21 lines
546 B
Go
package underscore
|
|
|
|
import "slices"
|
|
|
|
// OrderBy orders a slice by a field value within a struct, the predicate allows you
|
|
// to pick the fields you want to orderBy. Use > for ASC or < for DESC
|
|
// Uses O(n log n) sorting algorithm. Mutates the input slice.
|
|
//
|
|
// func (left Person, right Person) bool { return left.Age > right.Age }
|
|
func OrderBy[T any](list []T, predicate func(T, T) bool) []T {
|
|
slices.SortFunc(list, func(a, b T) int {
|
|
if predicate(a, b) {
|
|
return 1
|
|
}
|
|
if predicate(b, a) {
|
|
return -1
|
|
}
|
|
return 0
|
|
})
|
|
return list
|
|
}
|