1
0
mirror of https://github.com/MontFerret/ferret.git synced 2025-01-04 03:02:02 +02:00
ferret/pkg/runtime/expressions/literals/object.go

61 lines
1.2 KiB
Go
Raw Normal View History

2018-09-18 22:42:38 +02:00
package literals
import (
"context"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
)
type (
ObjectPropertyAssignment struct {
name core.Expression
value core.Expression
}
ObjectLiteral struct {
properties []*ObjectPropertyAssignment
}
)
func NewObjectPropertyAssignment(name, value core.Expression) (*ObjectPropertyAssignment, error) {
if name == nil {
return nil, core.Error(core.ErrMissedArgument, "property name expression")
}
if value == nil {
return nil, core.Error(core.ErrMissedArgument, "property value expression")
}
2018-09-18 22:42:38 +02:00
return &ObjectPropertyAssignment{name, value}, nil
2018-09-18 22:42:38 +02:00
}
func NewObjectLiteralWith(props ...*ObjectPropertyAssignment) *ObjectLiteral {
return &ObjectLiteral{props}
}
func (l *ObjectLiteral) Exec(ctx context.Context, scope *core.Scope) (core.Value, error) {
obj := values.NewObject()
for _, el := range l.properties {
name, err := el.name.Exec(ctx, scope)
if err != nil {
return values.None, err
2018-09-18 22:42:38 +02:00
}
val, err := el.value.Exec(ctx, scope)
if err != nil {
return values.None, err
2018-09-18 22:42:38 +02:00
}
if name.Type() != core.StringType {
return values.None, core.TypeError(name.Type(), core.StringType)
2018-09-18 22:42:38 +02:00
}
obj.Set(name.(values.String), val)
}
return obj, nil
}