1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-07 14:12:28 +08:00

feat: add IsSortedByKey

This commit is contained in:
dudaodong
2023-02-10 10:10:57 +08:00
parent a7e77fa98d
commit 75b27c6540
3 changed files with 65 additions and 0 deletions

View File

@@ -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

View File

@@ -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}

View File

@@ -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")