array: add filter() method

pull/2264/head
Don Alfons Nisnoni 2019-10-08 18:23:17 +08:00 committed by Alexander Medvednikov
parent e10848e0d5
commit fecf3f19c3
3 changed files with 48 additions and 2 deletions

1
.gitignore vendored
View File

@ -29,3 +29,4 @@ vjs
# Thumbnails
._*
.vrepl_temp.v
a.out

View File

@ -329,3 +329,28 @@ pub fn (a []char) index(v char) int {
}
return -1
}
////////////// FILTER //////////////
// Creates a new array with all elements that pass the test implemented by the provided function.
pub fn (a []string) filter(predicate fn(p_val string, p_i int, p_arr []string) bool) []string
{
mut res := []string
for i := 0; i < a.len; i++ {
if predicate(a[i], i, a) {
res << a[i]
}
}
return res
}
pub fn (a []int) filter(predicate fn(p_val int, p_i int, p_arr []int) bool) []int
{
mut res := []int
for i := 0; i < a.len; i++ {
if predicate(a[i], i, a) {
res << a[i]
}
}
return res
}

View File

@ -296,3 +296,23 @@ fn test_in() {
assert !(4 in a)
assert !(0 in a)
}
fn callback_1(val int, index int, arr []int) bool {
return val >= 2
}
fn callback_2(val string, index int, arr []string) bool {
return val.len >= 2
}
fn test_filter() {
a := [1, 2, 3, 4, 5, 6]
b := a.filter(callback_1)
assert b[0] == 2
assert b[1] == 3
c := ['v', 'is', 'awesome']
d := c.filter(callback_2)
assert d[0] == 'is'
assert d[1] == 'awesome'
}