Skip to content

Commit

Permalink
feat: implement list->indexOf()
Browse files Browse the repository at this point in the history
  • Loading branch information
Melkor333 committed Dec 12, 2023
1 parent b87c12e commit 5c948c4
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 3 deletions.
21 changes: 21 additions & 0 deletions builtin/method_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from core import vm
from frontend import typed_args
from mycpp.mylib import log
from ysh import val_ops

_ = log

Expand Down Expand Up @@ -75,3 +76,23 @@ def Call(self, rd):
li.reverse()

return value.Null

class IndexOf(vm._Callable):

def __init__(self):
# type: () -> None
pass

def Call(self, rd):
# type: (typed_args.Reader) -> value_t

li = rd.PosList()
needle = rd.PosValue()
rd.Done()
for i in range(len(li)):
try:
if val_ops.ExactlyEqual(li[i], needle, -1):
return value.Int(i)
except:
pass
return value.Int(-1)
2 changes: 1 addition & 1 deletion core/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@ def Main(
'pop': method_list.Pop(),
'insert': None, # insert object before index
'remove': None, # insert object before index
'find': None, # return first index of value, or -1
'indexOf': method_list.IndexOf(), # return first index of value, or -1
# Python list() has index(), which raises ValueError
# But this is consistent with Str->find(), and doesn't
# use exceptions
Expand Down
4 changes: 3 additions & 1 deletion doc/ref/chap-type-method.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ Respects unicode.

### extend()

### find()
### indexOf()

Returns -1 if element is not in the index.

### insert()

Expand Down
2 changes: 1 addition & 1 deletion doc/ref/toc-ysh.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ X [Builtin Sub] _buffer
X trim() X trimLeft() X trimRight()
X trimPrefix() X trimSuffix()
upper() lower() # ascii or unicode
[List] append() pop() extend() X find()
[List] append() pop() extend() indexOf()
X insert() X remove() reverse()
[Dict] keys() values() X get() X erase()
X inc() X accum()
Expand Down
14 changes: 14 additions & 0 deletions spec/ysh-methods.test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,20 @@ setvar is_a_val = "xyz"
(Bool) True
## END

#### Lis->indexOf
var items = [1, '2', 3, { 'a': 5 }]

write -- $[items->indexOf('a')]
write -- $[items->indexOf(1)]
write -- $[items->indexOf('2')]
write -- $[items->indexOf({'a': 5})]
## STDOUT:
-1
0
1
3
## END

#### List->join
var items = [1, 2, 3]

Expand Down

0 comments on commit 5c948c4

Please sign in to comment.