Files
monkey/object/array.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

83 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 (a *Array) Less(i, j int) bool {
if cmp, ok := a.Elements[i].(Comparable); ok {
return cmp.Compare(a.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]
}