xgo/objects/immutable_map.go

106 lines
2 KiB
Go
Raw Normal View History

2019-01-17 12:56:05 +03:00
package objects
import (
"fmt"
"strings"
"github.com/d5/tengo/compiler/token"
)
2019-01-18 12:57:14 +03:00
// ImmutableMap represents an immutable map object.
2019-01-18 12:43:46 +03:00
type ImmutableMap struct {
2019-01-17 12:56:05 +03:00
Value map[string]Object
}
// TypeName returns the name of the type.
2019-01-18 12:43:46 +03:00
func (o *ImmutableMap) TypeName() string {
return "immutable-map"
2019-01-17 12:56:05 +03:00
}
2019-01-18 12:43:46 +03:00
func (o *ImmutableMap) String() string {
2019-01-17 12:56:05 +03:00
var pairs []string
for k, v := range o.Value {
pairs = append(pairs, fmt.Sprintf("%s: %s", k, v.String()))
}
return fmt.Sprintf("{%s}", strings.Join(pairs, ", "))
}
// BinaryOp returns another object that is the result of
// a given binary operator and a right-hand side object.
2019-01-18 12:43:46 +03:00
func (o *ImmutableMap) BinaryOp(op token.Token, rhs Object) (Object, error) {
2019-01-17 12:56:05 +03:00
return nil, ErrInvalidOperator
}
// Copy returns a copy of the type.
2019-01-18 12:43:46 +03:00
func (o *ImmutableMap) Copy() Object {
2019-01-17 12:56:05 +03:00
c := make(map[string]Object)
for k, v := range o.Value {
c[k] = v.Copy()
}
2019-01-26 01:54:58 +03:00
return &Map{Value: c}
2019-01-17 12:56:05 +03:00
}
// IsFalsy returns true if the value of the type is falsy.
2019-01-18 12:43:46 +03:00
func (o *ImmutableMap) IsFalsy() bool {
2019-01-17 12:56:05 +03:00
return len(o.Value) == 0
}
// IndexGet returns the value for the given key.
func (o *ImmutableMap) IndexGet(index Object) (res Object, err error) {
strIdx, ok := ToString(index)
if !ok {
err = ErrInvalidIndexType
return
}
val, ok := o.Value[strIdx]
if !ok {
val = UndefinedValue
}
2019-01-17 12:56:05 +03:00
return val, nil
2019-01-17 12:56:05 +03:00
}
// Equals returns true if the value of the type
// is equal to the value of another object.
2019-01-18 12:43:46 +03:00
func (o *ImmutableMap) Equals(x Object) bool {
2019-01-26 01:54:58 +03:00
var xVal map[string]Object
switch x := x.(type) {
case *Map:
xVal = x.Value
case *ImmutableMap:
xVal = x.Value
default:
2019-01-17 12:56:05 +03:00
return false
}
2019-01-26 01:54:58 +03:00
if len(o.Value) != len(xVal) {
2019-01-17 12:56:05 +03:00
return false
}
for k, v := range o.Value {
2019-01-26 01:54:58 +03:00
tv := xVal[k]
2019-01-17 12:56:05 +03:00
if !v.Equals(tv) {
return false
}
}
return true
}
2019-01-24 00:36:03 +03:00
// Iterate creates an immutable map iterator.
func (o *ImmutableMap) Iterate() Iterator {
var keys []string
for k := range o.Value {
keys = append(keys, k)
}
2019-01-26 01:54:58 +03:00
return &MapIterator{
2019-01-24 00:36:03 +03:00
v: o.Value,
k: keys,
l: len(keys),
}
}