github.com/MontFerret/ferret@v0.18.0/pkg/runtime/expressions/literals/object.go (about) 1 package literals 2 3 import ( 4 "context" 5 6 "github.com/MontFerret/ferret/pkg/runtime/core" 7 "github.com/MontFerret/ferret/pkg/runtime/values" 8 "github.com/MontFerret/ferret/pkg/runtime/values/types" 9 ) 10 11 type ( 12 ObjectPropertyAssignment struct { 13 name core.Expression 14 value core.Expression 15 } 16 17 ObjectLiteral struct { 18 properties []*ObjectPropertyAssignment 19 } 20 ) 21 22 func NewObjectPropertyAssignment(name, value core.Expression) (*ObjectPropertyAssignment, error) { 23 if name == nil { 24 return nil, core.Error(core.ErrMissedArgument, "property name expression") 25 } 26 27 if value == nil { 28 return nil, core.Error(core.ErrMissedArgument, "property value expression") 29 } 30 31 return &ObjectPropertyAssignment{name, value}, nil 32 } 33 34 func NewObjectLiteral(props []*ObjectPropertyAssignment) *ObjectLiteral { 35 return &ObjectLiteral{props} 36 } 37 38 func NewObjectLiteralWith(props ...*ObjectPropertyAssignment) *ObjectLiteral { 39 return NewObjectLiteral(props) 40 } 41 42 func (l *ObjectLiteral) Exec(ctx context.Context, scope *core.Scope) (core.Value, error) { 43 obj := values.NewObject() 44 45 for _, el := range l.properties { 46 name, err := el.name.Exec(ctx, scope) 47 48 if err != nil { 49 return values.None, err 50 } 51 52 val, err := el.value.Exec(ctx, scope) 53 54 if err != nil { 55 return values.None, err 56 } 57 58 if name.Type() != types.String { 59 return values.None, core.TypeError(name.Type(), types.String) 60 } 61 62 obj.Set(name.(values.String), val) 63 } 64 65 return obj, nil 66 }