From a197836c1db6fcf3cd2caec927c665ee014972a9 Mon Sep 17 00:00:00 2001 From: Andy Long Date: Sat, 3 Sep 2022 16:04:30 +0100 Subject: [PATCH] Added in an OrderBy function --- orderBy.go | 22 ++++++++++++++++++++++ orderBy_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 orderBy.go create mode 100644 orderBy_test.go diff --git a/orderBy.go b/orderBy.go new file mode 100644 index 0000000..b61093d --- /dev/null +++ b/orderBy.go @@ -0,0 +1,22 @@ +package underscore + +func OrderBy[T any](list []T, predicate func(T, T) bool) []T { + swaps := true + var tmp T + + 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 +} diff --git a/orderBy_test.go b/orderBy_test.go new file mode 100644 index 0000000..ac0d802 --- /dev/null +++ b/orderBy_test.go @@ -0,0 +1,31 @@ +package underscore_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + u "github.com/rjNemo/underscore" +) + +func Test_OrderBy_Asc(t *testing.T) { + set := u.Range(5, 0) + want := u.Range(0, 5) + + result := u.OrderBy(set, func(left int, right int) bool { + return left > right + }) + + assert.Equal(t, want, result) +} + +func Test_OrderBy_Desc(t *testing.T) { + set := u.Range(0, 5) + want := u.Range(5, 0) + + result := u.OrderBy(set, func(left int, right int) bool { + return left < right + }) + + assert.Equal(t, want, result) +}