mirror of
https://github.com/vlang/v.git
synced 2025-09-15 07:22:27 +03:00
arrays: add more util functions and tests for them - find_first, find_last, join_to_string (#18784)
This commit is contained in:
parent
7d6e15fa66
commit
e7e5a07aa2
2 changed files with 120 additions and 0 deletions
|
@ -404,3 +404,71 @@ fn test_map_of_counts() {
|
|||
assert map_of_counts(['abc', 'def', 'abc']) == {'abc': 2, 'def': 1}
|
||||
// vfmt on
|
||||
}
|
||||
|
||||
struct FindTest {
|
||||
name string
|
||||
age int
|
||||
}
|
||||
|
||||
const test_structs = [FindTest{'one', 1}, FindTest{'two', 2},
|
||||
FindTest{'three', 3}, FindTest{'one', 4}]
|
||||
|
||||
fn test_find_first() {
|
||||
// element in array
|
||||
a := [1, 2, 3, 4, 5]
|
||||
assert find_first[int](a, fn (arr int) bool {
|
||||
return arr == 3
|
||||
})? == 3, 'find element couldnt find the right element'
|
||||
|
||||
// find struct
|
||||
find_by_name := find_first(arrays.test_structs, fn (arr FindTest) bool {
|
||||
return arr.name == 'one'
|
||||
})?
|
||||
assert find_by_name == FindTest{'one', 1}
|
||||
|
||||
// not found
|
||||
if _ := find_first(arrays.test_structs, fn (arr FindTest) bool {
|
||||
return arr.name == 'nothing'
|
||||
})
|
||||
{
|
||||
assert false
|
||||
} else {
|
||||
assert true
|
||||
}
|
||||
}
|
||||
|
||||
fn test_find_last() {
|
||||
// // element in array
|
||||
a := [1, 2, 3, 4, 5]
|
||||
assert find_last[int](a, fn (arr int) bool {
|
||||
return arr == 3
|
||||
})? == 3, 'find element couldnt find the right element'
|
||||
|
||||
// find struct
|
||||
find_by_name := find_last(arrays.test_structs, fn (arr FindTest) bool {
|
||||
return arr.name == 'one'
|
||||
})?
|
||||
assert find_by_name == FindTest{'one', 4}
|
||||
|
||||
// not found
|
||||
if _ := find_last(arrays.test_structs, fn (arr FindTest) bool {
|
||||
return arr.name == 'nothing'
|
||||
})
|
||||
{
|
||||
assert false
|
||||
} else {
|
||||
assert true
|
||||
}
|
||||
}
|
||||
|
||||
fn test_join_to_string() {
|
||||
assert join_to_string[FindTest](arrays.test_structs, ':', fn (it FindTest) string {
|
||||
return it.name
|
||||
}) == 'one:two:three:one'
|
||||
assert join_to_string[FindTest](arrays.test_structs, '', fn (it FindTest) string {
|
||||
return it.name
|
||||
}) == 'onetwothreeone'
|
||||
assert join_to_string[int]([]int{}, ':', fn (it int) string {
|
||||
return '1'
|
||||
}) == ''
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue