1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

array: add reduce() method

This commit is contained in:
Don Alfons Nisnoni 2019-10-11 09:12:40 +08:00 committed by Alexander Medvednikov
parent 67ae167013
commit 942c56ca95
2 changed files with 41 additions and 0 deletions

View File

@ -354,3 +354,20 @@ pub fn (a []int) filter(predicate fn(p_val int, p_i int, p_arr []int) bool) []in
} }
return res return res
} }
////////////// REDUCE //////////////
// method executes a reducer function (that you provide) on each element of the array,
// resulting in a single output value.
pub fn (a []int) reduce(
iter fn (accum int, curr int) int,
accum_start int
) int
{
mut _accum := 0
_accum = accum_start
for i := 0; i < a.len; i++ {
_accum = iter(_accum, a[i])
}
return _accum
}

View File

@ -314,3 +314,27 @@ fn test_filter() {
assert d[0] == 'is' assert d[0] == 'is'
assert d[1] == 'awesome' assert d[1] == 'awesome'
} }
fn sum(prev int, curr int) int {
return prev + curr
}
fn sub(prev int, curr int) int {
return prev - curr
}
fn test_reduce() {
a := [1, 2, 3, 4, 5]
b := a.reduce(sum, 0)
c := a.reduce(sum, 5)
d := a.reduce(sum, -1)
assert b == 15
assert c == 20
assert d == 14
e := [1, 2, 3]
f := e.reduce(sub, 0)
g := e.reduce(sub, -1)
assert f == -6
assert g == -7
}