array: add reduce() method
parent
67ae167013
commit
942c56ca95
|
@ -354,3 +354,20 @@ pub fn (a []int) filter(predicate fn(p_val int, p_i int, p_arr []int) bool) []in
|
|||
}
|
||||
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
|
||||
}
|
||||
|
|
|
@ -314,3 +314,27 @@ fn test_filter() {
|
|||
assert d[0] == 'is'
|
||||
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
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue