mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
* Adding some new funky functions which I find useful Created a Tuple struct as some of the new functions require you to return a new slice with two fields which is the result of the new functions Created the Join, JoinProjection, Range, SumMap, Zip functions, ecah fuction is documented with how it works and had a unit test or maybe more * Added in an OrderBy function * Documentation comment for OrderBy which I missed out * Adding a Unit test for JoinProject function Updated the comments on the Join & OrderBy functions so they make a little more sense. Covered an extra test case with the Join test, where the left set has more data than the right and so the Right handside array of the join is empty
26 lines
614 B
Go
26 lines
614 B
Go
package underscore
|
|
|
|
// 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
|
|
// func (left Person, right Person) bool { return left.Age > right.Age }
|
|
func OrderBy[T any](list []T, predicate func(T, T) bool) []T {
|
|
swaps := true
|
|
var tmp T
|
|
|
|
//todo: replace with a faster algorithm, this one is pretty simple
|
|
for swaps {
|
|
swaps = false
|
|
|
|
for i := 0; i < len(list)-1; i++ {
|
|
if predicate(list[i], list[i+1]) {
|
|
swaps = true
|
|
tmp = list[i]
|
|
|
|
list[i] = list[i+1]
|
|
list[i+1] = tmp
|
|
}
|
|
}
|
|
}
|
|
|
|
return list
|
|
}
|