Files
monkey/object/array.go
Chuck Smith fea9fb9f64
Some checks failed
Build / build (push) Successful in 14m31s
Test / build (push) Failing after 17m13s
array builtins
2024-03-24 16:29:18 -04:00

80 lines
1.5 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) 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) Equal(other Object) bool {
if obj, ok := other.(*Array); ok {
if len(ao.Elements) != len(obj.Elements) {
return false
}
for i, el := range ao.Elements {
cmp, ok := el.(Comparable)
if !ok {
return false
}
if !cmp.Equal(obj.Elements[i]) {
return false
}
}
return true
}
return false
}
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]
}
func (ao *Array) Less(i, j int) bool {
if cmp, ok := ao.Elements[i].(Comparable); ok {
return cmp.Less(ao.Elements[j])
}
return false
}