arrays: add more util functions and tests for them - find_first, find_last, join_to_string (#18784)

This commit is contained in:
encyclopaedia 2023-07-06 22:52:08 -05:00 committed by GitHub
parent 7d6e15fa66
commit e7e5a07aa2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 120 additions and 0 deletions

View file

@ -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'
}) == ''
}