diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index 9b3be586b7..f0bff62c93 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -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 +} diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index 18ab034807..2719d1391f 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -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 +}