Files
monkey/builtins/find.go
Chuck Smith b4ba660704
Some checks failed
Build / build (push) Successful in 10m31s
Test / build (push) Failing after 39m25s
rearrange builtins
2024-03-24 14:00:22 -04:00

37 lines
890 B
Go

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])
}
}