From 75b27c6540b35ed17d488ee01774225792273590 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Fri, 10 Feb 2023 10:10:57 +0800 Subject: [PATCH] feat: add IsSortedByKey --- slice/slice.go | 28 ++++++++++++++++++++++++++++ slice/slice_example_test.go | 21 +++++++++++++++++++++ slice/slice_test.go | 16 ++++++++++++++++ 3 files changed, 65 insertions(+) diff --git a/slice/slice.go b/slice/slice.go index af97e77..980fc89 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -860,6 +860,34 @@ func IsSorted[T constraints.Ordered](slice []T) bool { return IsAscending(slice) || IsDescending(slice) } +// IsSortedByKey checks if a slice is sorted by iteratee function. +// Play: todo +func IsSortedByKey[T any, K constraints.Ordered](slice []T, iteratee func(item T) K) bool { + size := len(slice) + + isAscending := func(data []T) bool { + for i := 0; i < size-1; i++ { + if iteratee(data[i]) > iteratee(data[i+1]) { + return false + } + } + + return true + } + + isDescending := func(data []T) bool { + for i := 0; i < size-1; i++ { + if iteratee(data[i]) < iteratee(data[i+1]) { + return false + } + } + + return true + } + + return isAscending(slice) || isDescending(slice) +} + // Sort sorts a slice of any ordered type(number or string), use quick sort algrithm. // default sort order is ascending (asc), if want descending order, set param `sortOrder` to `desc`. // Play: https://go.dev/play/p/V9AVjzf_4Fk diff --git a/slice/slice_example_test.go b/slice/slice_example_test.go index 73afbd9..dc663c0 100644 --- a/slice/slice_example_test.go +++ b/slice/slice_example_test.go @@ -733,6 +733,27 @@ func ExampleIsSorted() { // false } +func ExampleIsSortedByKey() { + result1 := IsSortedByKey([]string{"a", "ab", "abc"}, func(s string) int { + return len(s) + }) + result2 := IsSortedByKey([]string{"abc", "ab", "a"}, func(s string) int { + return len(s) + }) + result3 := IsSortedByKey([]string{"abc", "a", "ab"}, func(s string) int { + return len(s) + }) + + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + + // Output: + // true + // true + // false +} + func ExampleSort() { nums := []int{1, 4, 3, 2, 5} diff --git a/slice/slice_test.go b/slice/slice_test.go index 8c72eb1..1c28f87 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -627,6 +627,22 @@ func TestIsSorted(t *testing.T) { assert.Equal(false, IsSorted([]int{2, 1, 3, 4, 5})) } +func TestIsSortedByKey(t *testing.T) { + assert := internal.NewAssert(t, "TestIsSortedByKey") + + assert.Equal(true, IsSortedByKey([]string{"a", "ab", "abc"}, func(s string) int { + return len(s) + })) + + assert.Equal(true, IsSortedByKey([]string{"abc", "ab", "a"}, func(s string) int { + return len(s) + })) + + assert.Equal(false, IsSortedByKey([]string{"abc", "a", "ab"}, func(s string) int { + return len(s) + })) +} + func TestSort(t *testing.T) { assert := internal.NewAssert(t, "TestSort")