xgo/objects/immutable_map.go

78 lines
1.5 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:43:46 +03:00
// ImmutableMap represents a module map object.
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-18 12:43:46 +03:00
return &ImmutableMap{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
}
// Get returns the value for the given key.
2019-01-18 12:43:46 +03:00
func (o *ImmutableMap) Get(key string) (Object, bool) {
2019-01-17 12:56:05 +03:00
val, ok := o.Value[key]
return val, ok
}
// 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 {
t, ok := x.(*ImmutableMap)
2019-01-17 12:56:05 +03:00
if !ok {
return false
}
if len(o.Value) != len(t.Value) {
return false
}
for k, v := range o.Value {
tv := t.Value[k]
if !v.Equals(tv) {
return false
}
}
return true
}