1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/pkg/runtime/expressions/literals/object.go
Tim Voronov 549b4abd3b
Feature/#5 collect keyword alt (#141)
Implemented COLLECT key word
2018-10-24 21:30:05 -04:00

61 lines
1.2 KiB
Go

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")
}
return &ObjectPropertyAssignment{name, value}, nil
}
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
}
val, err := el.value.Exec(ctx, scope)
if err != nil {
return values.None, err
}
if name.Type() != core.StringType {
return values.None, core.TypeError(name.Type(), core.StringType)
}
obj.Set(name.(values.String), val)
}
return obj, nil
}