mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
array: add filter() method
This commit is contained in:
parent
e10848e0d5
commit
fecf3f19c3
1
.gitignore
vendored
1
.gitignore
vendored
@ -29,3 +29,4 @@ vjs
|
|||||||
# Thumbnails
|
# Thumbnails
|
||||||
._*
|
._*
|
||||||
.vrepl_temp.v
|
.vrepl_temp.v
|
||||||
|
a.out
|
||||||
|
@ -329,3 +329,28 @@ pub fn (a []char) index(v char) int {
|
|||||||
}
|
}
|
||||||
return -1
|
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
|
||||||
|
}
|
||||||
|
@ -296,3 +296,23 @@ fn test_in() {
|
|||||||
assert !(4 in a)
|
assert !(4 in a)
|
||||||
assert !(0 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'
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user