mirror of
https://github.com/vlang/v.git
synced 2025-09-13 14:32:26 +03:00
arrays: add a partition function, that splits a given array, based on a criteria, passed as a callback fn (#19417)
This commit is contained in:
parent
5905f63e95
commit
04d28f2a74
2 changed files with 32 additions and 0 deletions
|
@ -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
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue