mirror of
https://github.com/vlang/v.git
synced 2025-09-13 22:42: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
|
@ -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