mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
arrays: sorting functions for immutable arrays
This commit is contained in:
@ -218,6 +218,26 @@ pub fn sum[T](array []T) !T {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// sorted returns a sorted clone of the array
|
||||||
|
// Example: arrays.sorted([6, 2, 1, 0, 3]) // => [0, 1, 2, 3, 6]
|
||||||
|
pub fn sorted[T](array []T) []T {
|
||||||
|
mut cloned := array.clone()
|
||||||
|
cloned.sort(a < b)
|
||||||
|
sorted := cloned.clone()
|
||||||
|
|
||||||
|
return sorted
|
||||||
|
}
|
||||||
|
|
||||||
|
// sorted_with_compare returns a sorted clone of the array, sorted with the provided sorting function
|
||||||
|
// Example: arrays.sorted([6, 2, 1, 0, 3]) // => [0, 1, 2, 3, 6]
|
||||||
|
pub fn sorted_with_compare[T](array []T, callback fn (&T, &T) int) []T {
|
||||||
|
mut cloned := array.clone()
|
||||||
|
cloned.sort_with_compare(callback)
|
||||||
|
sorted := cloned.clone()
|
||||||
|
|
||||||
|
return sorted
|
||||||
|
}
|
||||||
|
|
||||||
// reduce sets `acc = array[0]`, then successively calls `acc = reduce_op(acc, elem)` for each remaining element in `array`.
|
// reduce sets `acc = array[0]`, then successively calls `acc = reduce_op(acc, elem)` for each remaining element in `array`.
|
||||||
// returns the accumulated value in `acc`.
|
// returns the accumulated value in `acc`.
|
||||||
// returns an error if the array is empty.
|
// returns an error if the array is empty.
|
||||||
|
@ -155,6 +155,35 @@ fn test_sum() {
|
|||||||
assert sum[int]([]int{}) or { 0 } == 0
|
assert sum[int]([]int{}) or { 0 } == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn test_sorted() {
|
||||||
|
ints := [5, 1, 3, 4, 2]
|
||||||
|
ints_sorted := [1, 2, 3, 4, 5]
|
||||||
|
|
||||||
|
assert sorted[int](ints) == ints_sorted
|
||||||
|
|
||||||
|
strings := ['a', 'c', 'd', 'b', 'e']
|
||||||
|
strings_sorted := ['a', 'b', 'c', 'd', 'e']
|
||||||
|
|
||||||
|
assert sorted[string](strings) == strings_sorted
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_sorted_with_compare() {
|
||||||
|
strings := ['a', 'c', 'd', 'b', 'e']
|
||||||
|
strings_sorted := ['e', 'd', 'c', 'b', 'a']
|
||||||
|
|
||||||
|
descending_string_sort_fn := fn (a &string, b &string) int {
|
||||||
|
if *a > *b {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
if *a < *b {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
assert sorted_with_compare[string](strings, descending_string_sort_fn) == strings_sorted
|
||||||
|
}
|
||||||
|
|
||||||
fn test_reduce() {
|
fn test_reduce() {
|
||||||
x := [1, 2, 3, 4, 5]
|
x := [1, 2, 3, 4, 5]
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user