Skip to content

Commit

Permalink
arrays: add a partition function, that splits a given array, based on…
Browse files Browse the repository at this point in the history
… a criteria, passed as a callback fn (#19417)
  • Loading branch information
prashanth-hegde committed Sep 23, 2023
1 parent 5905f63 commit 04d28f2
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
15 changes: 15 additions & 0 deletions vlib/arrays/arrays.v
Expand Up @@ -728,3 +728,18 @@ pub fn join_to_string[T](array []T, separator string, transform fn (elem T) stri
}
return sb.str()
}

// partition splits the original array into pair of lists,
// where first list contains elements for which predicate yielded true,
// while second list contains elements for which predicate yielded false
pub fn partition[T](array []T, predicate fn (elem T) bool) ([]T, []T) {
mut matching, mut non_matching := []T{}, []T{}
for item in array {
if predicate(item) {
matching << item
} else {
non_matching << item
}
}
return matching, non_matching
}
17 changes: 17 additions & 0 deletions vlib/arrays/arrays_test.v
Expand Up @@ -481,3 +481,20 @@ fn test_join_to_string() {
return '1'
}) == ''
}

fn test_partition() {
a := [1, 2, 3, 4, 5, 6, 7, 8]
lower, upper := partition(a, fn (it int) bool {
return it < 5
})
assert lower.len == 4
assert upper.len == 4
assert lower == [1, 2, 3, 4]
assert upper == [5, 6, 7, 8]

lower2, upper2 := partition(a, fn (it int) bool {
return it < 1
})
assert lower2.len == 0
assert upper2.len == 8
}

0 comments on commit 04d28f2

Please sign in to comment.