rearrange builtins
This commit is contained in:
36
builtins/find.go
Normal file
36
builtins/find.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package builtins
|
||||
|
||||
import "monkey/object"
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Find ...
|
||||
func Find(args ...object.Object) object.Object {
|
||||
if len(args) != 2 {
|
||||
return newError("wrong number of arguments. got=%d, want=2",
|
||||
len(args))
|
||||
}
|
||||
|
||||
if haystack, ok := args[0].(*object.String); ok {
|
||||
if needle, ok := args[1].(*object.String); ok {
|
||||
index := strings.Index(haystack.Value, needle.Value)
|
||||
return &object.Integer{Value: int64(index)}
|
||||
} else {
|
||||
return newError("expected arg #2 to be `str` got got=%T", args[1])
|
||||
}
|
||||
} else if haystack, ok := args[0].(*object.Array); ok {
|
||||
needle := args[1]
|
||||
index := -1
|
||||
for i, el := range haystack.Elements {
|
||||
if cmp, ok := el.(object.Comparable); ok && cmp.Equal(needle) {
|
||||
index = i
|
||||
break
|
||||
}
|
||||
}
|
||||
return &object.Integer{Value: int64(index)}
|
||||
} else {
|
||||
return newError("expected arg #1 to be `str` or `array` got got=%T", args[0])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user