Files
monkey/builtins/find.go
Chuck Smith 1c99d2198b
Some checks failed
Build / build (push) Successful in 10m48s
Test / build (push) Failing after 17m11s
Simplified Equality
2024-03-24 17:11:48 -04:00

39 lines
1003 B
Go

package builtins
import (
"monkey/object"
"sort"
)
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].(object.Comparable)
i := sort.Search(len(haystack.Elements), func(i int) bool {
return needle.Compare(haystack.Elements[i]) == 0
})
if i < len(haystack.Elements) && needle.Compare(haystack.Elements[i]) == 0 {
return &object.Integer{Value: int64(i)}
}
return &object.Integer{Value: -1}
} else {
return newError("expected arg #1 to be `str` or `array` got got=%T", args[0])
}
}