mirror of
https://github.com/vlang/v.git
synced 2025-09-13 14:32:26 +03:00
arrays: add arrays.each, arrays.each_indexed, and tests for them
This commit is contained in:
parent
3de43b82e0
commit
b81a5325ef
2 changed files with 59 additions and 0 deletions
|
@ -11,6 +11,7 @@ import strings
|
|||
// - window - get snapshots of the window of the given size sliding along array with the given step, where each snapshot is an array
|
||||
// - group - merge two arrays by interleaving e.g. arrays.group([1,3,5], [2,4,6]) => [[1,2],[3,4],[5,6]]
|
||||
// - flatten - reduce dimensionality of array by one. e.g. arrays.flatten([[1,2],[3,4],[5,6]]) => [1,2,3,4,5,6]
|
||||
// - each - call a callback fn, for each element of the array, similar to a.map(), but unlike it, the callback should not return anything
|
||||
|
||||
// min returns the minimum value in the array
|
||||
// Example: arrays.min([1, 2, 3, 0, 9])! // => 0
|
||||
|
@ -743,3 +744,18 @@ pub fn partition[T](array []T, predicate fn (elem T) bool) ([]T, []T) {
|
|||
}
|
||||
return matching, non_matching
|
||||
}
|
||||
|
||||
// each calls the callback fn `cb`, for each element of the given array `a`
|
||||
pub fn each[T](a []T, cb fn (elem T)) {
|
||||
for item in a {
|
||||
cb(item)
|
||||
}
|
||||
}
|
||||
|
||||
// each_indexed calls the callback fn `cb`, for each element of the given array `a`,
|
||||
// passing it both the index of the current element, and the element itself
|
||||
pub fn each_indexed[T](a []T, cb fn (i int, e T)) {
|
||||
for idx, item in a {
|
||||
cb(idx, item)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -498,3 +498,46 @@ fn test_partition() {
|
|||
assert lower2.len == 0
|
||||
assert upper2.len == 8
|
||||
}
|
||||
|
||||
fn test_each() {
|
||||
a := [99, 1, 2, 3, 4, 5, 6, 7, 8, 1001]
|
||||
mut control_sum := 0
|
||||
for x in a {
|
||||
control_sum += x
|
||||
}
|
||||
//
|
||||
each(a, fn (x int) {
|
||||
println(x)
|
||||
})
|
||||
mut sum := 0
|
||||
mut psum := &sum
|
||||
each(a, fn [mut psum] (x int) {
|
||||
unsafe {
|
||||
*psum += x
|
||||
}
|
||||
})
|
||||
assert control_sum == sum
|
||||
}
|
||||
|
||||
fn test_each_indexed() {
|
||||
a := [99, 1, 2, 3, 4, 5, 6, 7, 8, 1001]
|
||||
mut control_sum := 0
|
||||
f := fn (idx int, x int) int {
|
||||
return (idx + 1) * 1000_000 + x
|
||||
}
|
||||
for idx, x in a {
|
||||
control_sum += f(idx, x)
|
||||
}
|
||||
//
|
||||
each_indexed(a, fn (idx int, x int) {
|
||||
println('idx: ${idx}, x: ${x}')
|
||||
})
|
||||
mut sum := 0
|
||||
mut psum := &sum
|
||||
each_indexed(a, fn [mut psum, f] (idx int, x int) {
|
||||
unsafe {
|
||||
*psum += f(idx, x)
|
||||
}
|
||||
})
|
||||
assert control_sum == sum
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue