Files
monkey/object/array.go
Chuck Smith 6d234099d1
Some checks failed
Build / build (push) Successful in 11m16s
Test / build (push) Failing after 17m0s
type checking and error handling for builtins improved.
2024-03-25 16:18:08 -04:00

113 lines
2.1 KiB
Go

package object
import (
"bytes"
"strings"
)
// Array is the array literal type that holds a slice of Object(s)
type Array struct {
Elements []Object
}
func (ao *Array) Type() ObjectType {
return ARRAY_OBJ
}
func (ao *Array) Bool() bool {
return len(ao.Elements) > 0
}
func (a *Array) PopLeft() Object {
if len(a.Elements) > 0 {
e := a.Elements[0]
a.Elements = a.Elements[1:]
return e
}
return &Null{}
}
func (a *Array) PopRight() Object {
if len(a.Elements) > 0 {
e := a.Elements[(len(a.Elements) - 1)]
a.Elements = a.Elements[:(len(a.Elements) - 1)]
return e
}
return &Null{}
}
func (a *Array) Prepend(obj Object) {
a.Elements = append([]Object{obj}, a.Elements...)
}
func (a *Array) Append(obj Object) {
a.Elements = append(a.Elements, obj)
}
func (ao *Array) Inspect() string {
var out bytes.Buffer
var elements []string
for _, e := range ao.Elements {
elements = append(elements, e.Inspect())
}
out.WriteString("[")
out.WriteString(strings.Join(elements, ", "))
out.WriteString("]")
return out.String()
}
func (ao *Array) String() string {
return ao.Inspect()
}
func (ao *Array) Less(i, j int) bool {
if cmp, ok := ao.Elements[i].(Comparable); ok {
return cmp.Compare(ao.Elements[j]) == -1
}
return false
}
func (ao *Array) Compare(other Object) int {
if obj, ok := other.(*Array); ok {
if len(ao.Elements) != len(obj.Elements) {
return -1
}
for i, el := range ao.Elements {
cmp, ok := el.(Comparable)
if !ok {
return -1
}
if cmp.Compare(obj.Elements[i]) != 0 {
return cmp.Compare(obj.Elements[i])
}
}
return 0
}
return -1
}
func (ao *Array) Copy() *Array {
elements := make([]Object, len(ao.Elements))
for i, e := range ao.Elements {
elements[i] = e
}
return &Array{Elements: elements}
}
func (ao *Array) Reverse() {
for i, j := 0, len(ao.Elements)-1; i < j; i, j = i+1, j-1 {
ao.Elements[i], ao.Elements[j] = ao.Elements[j], ao.Elements[i]
}
}
func (ao *Array) Len() int {
return len(ao.Elements)
}
func (ao *Array) Swap(i, j int) {
ao.Elements[i], ao.Elements[j] = ao.Elements[j], ao.Elements[i]
}