mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-05 13:22:26 +08:00
feat: add IsAscending, Isdescending
This commit is contained in:
@@ -830,6 +830,30 @@ func Shuffle[T any](slice []T) []T {
|
||||
return slice
|
||||
}
|
||||
|
||||
// IsAscending checks if a slice is ascending order.
|
||||
// Play: todo
|
||||
func IsAscending[T constraints.Ordered](slice []T) bool {
|
||||
for i := 1; i < len(slice); i++ {
|
||||
if slice[i-1] > slice[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Isdescending checks if a slice is descending order.
|
||||
// Play: todo
|
||||
func Isdescending[T constraints.Ordered](slice []T) bool {
|
||||
for i := 1; i < len(slice); i++ {
|
||||
if slice[i-1] < slice[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
@@ -685,6 +685,38 @@ func ExampleReverse() {
|
||||
// [d c b a]
|
||||
}
|
||||
|
||||
func ExampleIsAscending() {
|
||||
|
||||
result1 := IsAscending([]int{1, 2, 3, 4, 5})
|
||||
result2 := IsAscending([]int{5, 4, 3, 2, 1})
|
||||
result3 := IsAscending([]int{2, 1, 3, 4, 5})
|
||||
|
||||
fmt.Println(result1)
|
||||
fmt.Println(result2)
|
||||
fmt.Println(result3)
|
||||
|
||||
// Output:
|
||||
// true
|
||||
// false
|
||||
// false
|
||||
}
|
||||
|
||||
func ExampleIsdescending() {
|
||||
|
||||
result1 := Isdescending([]int{5, 4, 3, 2, 1})
|
||||
result2 := Isdescending([]int{1, 2, 3, 4, 5})
|
||||
result3 := Isdescending([]int{2, 1, 3, 4, 5})
|
||||
|
||||
fmt.Println(result1)
|
||||
fmt.Println(result2)
|
||||
fmt.Println(result3)
|
||||
|
||||
// Output:
|
||||
// true
|
||||
// false
|
||||
// false
|
||||
}
|
||||
|
||||
func ExampleSort() {
|
||||
nums := []int{1, 4, 3, 2, 5}
|
||||
|
||||
|
||||
@@ -603,6 +603,22 @@ func TestDifferenceBy(t *testing.T) {
|
||||
assert.Equal([]int{1, 2}, DifferenceBy(s1, s2, addOne))
|
||||
}
|
||||
|
||||
func TestIsAscending(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestIsAscending")
|
||||
|
||||
assert.Equal(true, IsAscending([]int{1, 2, 3, 4, 5}))
|
||||
assert.Equal(false, IsAscending([]int{5, 4, 3, 2, 1}))
|
||||
assert.Equal(false, IsAscending([]int{2, 1, 3, 4, 5}))
|
||||
}
|
||||
|
||||
func TestIsdescending(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestIsdescending")
|
||||
|
||||
assert.Equal(true, Isdescending([]int{5, 4, 3, 2, 1}))
|
||||
assert.Equal(false, Isdescending([]int{1, 2, 3, 4, 5}))
|
||||
assert.Equal(false, Isdescending([]int{2, 1, 3, 4, 5}))
|
||||
}
|
||||
|
||||
func TestSort(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestSort")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user