array: add index() method

pull/2231/head^2
Don Alfons Nisnoni 2019-10-05 04:07:19 +08:00 committed by Alexander Medvednikov
parent 19c7b95d00
commit 68bcf6830c
2 changed files with 66 additions and 1 deletions

View File

@ -290,3 +290,42 @@ fn compare_ints(a, b &int) int {
pub fn (a mut []int) sort() {
a.sort_with_compare(compare_ints)
}
// Looking for an array index based on value.
// If there is, it will return the index and if not, it will return `-1`
// TODO: Implement for all types
pub fn (a []string) index(v string) int {
for i := 0; i < a.len; i++ {
if a[i] == v {
return i
}
}
return -1
}
pub fn (a []int) index(v int) int {
for i := 0; i < a.len; i++ {
if a[i] == v {
return i
}
}
return -1
}
pub fn (a []byte) index(v byte) int {
for i := 0; i < a.len; i++ {
if a[i] == v {
return i
}
}
return -1
}
pub fn (a []char) index(v char) int {
for i := 0; i < a.len; i++ {
if a[i] == v {
return i
}
}
return -1
}

View File

@ -147,7 +147,7 @@ fn test_push_many() {
}
fn test_reverse() {
mut a := [1, 2, 3, 4]
mut a := [1, 2, 3, 4]
mut b := ['test', 'array', 'reverse']
c := a.reverse()
d := b.reverse()
@ -249,3 +249,29 @@ fn test_single_element() {
assert a[1] == 2
println(a)
}
fn test_find_index() {
// string
a := ['v', 'is', 'great']
assert a.index('v') == 0
assert a.index('is') == 1
assert a.index('gre') == -1
// int
b := [1, 2, 3, 4]
assert b.index(1) == 0
assert b.index(4) == 3
assert b.index(5) == -1
// byte
c := [0x22, 0x33, 0x55]
assert c.index(0x22) == 0
assert c.index(0x55) == 2
assert c.index(0x99) == -1
// char
d := [`a`, `b`, `c`]
assert d.index(`b`) == 1
assert d.index(`c`) == 2
assert d.index(`u`) == -1
}