Skip to content

Commit 7a1cd4a

Browse files
committed
feat: list_index()-function
1 parent 7cd11ae commit 7a1cd4a

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-1
lines changed

src/_builtins.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
use crate::builtin::Builtin;
77

88
/*GENERATE cargo run -- src/_builtins.tok -- `find src -name "*.rs"` */
9-
pub static BUILTINS: [Builtin; 70] = [
9+
pub static BUILTINS: [Builtin; 71] = [
1010
Builtin {
1111
name: "Float",
1212
func: crate::value::token::tokay_token_float,
@@ -183,6 +183,10 @@ pub static BUILTINS: [Builtin; 70] = [
183183
name: "list_iadd",
184184
func: crate::value::list::List::tokay_method_list_iadd,
185185
},
186+
Builtin {
187+
name: "list_index",
188+
func: crate::value::list::List::tokay_method_list_index,
189+
},
186190
Builtin {
187191
name: "list_len",
188192
func: crate::value::list::List::tokay_method_list_len,

src/value/list.rs

+20
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,26 @@ impl List {
382382

383383
Ok(list)
384384
});
385+
386+
/** Find `item` in `list` and return its offset.
387+
388+
In case `item` is not in the list, -1 is returned.
389+
*/
390+
tokay_method!("list_index : @list, item", {
391+
let list = list.borrow();
392+
393+
if let Some(list) = list.object::<List>() {
394+
if let Some(index) = list
395+
.list
396+
.iter()
397+
.position(|val| *val.borrow() == *item.borrow())
398+
{
399+
return Ok(value![index]);
400+
}
401+
}
402+
403+
Ok(value![-1])
404+
});
385405
}
386406

387407
impl std::ops::Deref for List {

tests/list_index.tok

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#testmode:repl
2+
3+
l = 1,2,3
4+
l.index(2)
5+
l.index(4)
6+
7+
l = "Esel", "Frank", (42, 5)
8+
l.index("Esel")
9+
l.index((42, 5))
10+
l.index(9)
11+
12+
#---
13+
14+
#1
15+
#-1
16+
#0
17+
#2
18+
#-1

0 commit comments

Comments
 (0)