From 7a31831ea528b4a8711af155ffcb443724f2a934 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20=C5=A0ulovsk=C3=BD?= Date: Sat, 4 Mar 2023 21:40:12 +0100 Subject: [PATCH] arrays: sorting functions for immutable arrays --- vlib/arrays/arrays.v | 20 ++++++++++++++++++++ vlib/arrays/arrays_test.v | 29 +++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/vlib/arrays/arrays.v b/vlib/arrays/arrays.v index fb3360e172..1e94ba887a 100644 --- a/vlib/arrays/arrays.v +++ b/vlib/arrays/arrays.v @@ -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`. // returns the accumulated value in `acc`. // returns an error if the array is empty. diff --git a/vlib/arrays/arrays_test.v b/vlib/arrays/arrays_test.v index 6180e505db..b17e4bed96 100644 --- a/vlib/arrays/arrays_test.v +++ b/vlib/arrays/arrays_test.v @@ -155,6 +155,35 @@ fn test_sum() { 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() { x := [1, 2, 3, 4, 5]