restructure project
This commit is contained in:
52
internal/builtins/find.go
Normal file
52
internal/builtins/find.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package builtins
|
||||
|
||||
import (
|
||||
"monkey/internal/object"
|
||||
"monkey/internal/typing"
|
||||
"sort"
|
||||
)
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Find ...
|
||||
func Find(args ...object.Object) object.Object {
|
||||
if err := typing.Check(
|
||||
"find", args,
|
||||
typing.ExactArgs(2),
|
||||
); err != nil {
|
||||
return newError(err.Error())
|
||||
}
|
||||
|
||||
// find substring in string
|
||||
if haystack, ok := args[0].(*object.String); ok {
|
||||
if err := typing.Check(
|
||||
"find", args,
|
||||
typing.WithTypes(object.STRING_OBJ, object.STRING_OBJ),
|
||||
); err != nil {
|
||||
return newError(err.Error())
|
||||
}
|
||||
|
||||
needle := args[1].(*object.String)
|
||||
index := strings.Index(haystack.Value, needle.Value)
|
||||
return &object.Integer{Value: int64(index)}
|
||||
}
|
||||
|
||||
// find in array
|
||||
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}
|
||||
}
|
||||
|
||||
return newError(
|
||||
"TypeError: find() expected argument #1 to be `array` or `str` got `%s`",
|
||||
args[0].Type(),
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user