diff --git a/.gitignore b/.gitignore index d6a836f4ac..b7fb1d2d09 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,4 @@ vjs # Thumbnails ._* .vrepl_temp.v +a.out diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index f0bff62c93..7eeb86f586 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -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 +} diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index 9ba751236c..2b528908cb 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -286,7 +286,7 @@ fn test_multi() { // TODO //b := [ [[1,2,3],[4,5,6]], [[1,2]] ] //assert b[0][0][0] == 1 -} +} fn test_in() { a := [1,2,3] @@ -295,4 +295,24 @@ fn test_in() { assert 3 in a 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' +}