1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-18 23:47:48 +02:00
ferret/pkg/runtime/expressions/operators/range.go

83 lines
1.7 KiB
Go
Raw Normal View History

2018-09-23 01:18:10 +02:00
package operators
import (
"context"
2018-09-23 01:18:10 +02:00
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
"github.com/MontFerret/ferret/pkg/runtime/values/types"
2018-09-23 01:18:10 +02:00
)
type RangeOperator struct {
*baseOperator
}
func NewRangeOperator(
src core.SourceMap,
left core.Expression,
right core.Expression,
) (*RangeOperator, error) {
2018-10-28 07:45:26 +02:00
if left == nil {
2018-09-23 01:18:10 +02:00
return nil, core.Error(core.ErrMissedArgument, "left expression")
}
2018-10-28 07:45:26 +02:00
if right == nil {
2018-09-23 01:18:10 +02:00
return nil, core.Error(core.ErrMissedArgument, "right expression")
}
return &RangeOperator{&baseOperator{src, left, right}}, nil
}
func (operator *RangeOperator) Exec(ctx context.Context, scope *core.Scope) (core.Value, error) {
left, err := operator.left.Exec(ctx, scope)
if err != nil {
return values.None, core.SourceError(operator.src, err)
}
right, err := operator.right.Exec(ctx, scope)
2018-09-23 01:18:10 +02:00
if err != nil {
return values.None, core.SourceError(operator.src, err)
}
return operator.Eval(ctx, left, right)
}
func (operator *RangeOperator) Eval(_ context.Context, left, right core.Value) (core.Value, error) {
err := core.ValidateType(left, types.Int, types.Float)
2018-09-23 01:18:10 +02:00
if err != nil {
return values.None, core.SourceError(operator.src, err)
}
err = core.ValidateType(right, types.Int, types.Float)
2018-09-23 01:18:10 +02:00
if err != nil {
return values.None, core.SourceError(operator.src, err)
}
var start int
var end int
if left.Type() == types.Float {
start = int(left.(values.Float))
} else {
start = int(left.(values.Int))
}
if right.Type() == types.Float {
end = int(right.(values.Float))
} else {
end = int(right.(values.Int))
}
2018-09-23 01:18:10 +02:00
arr := values.NewArray(10)
for i := start; i <= end; i++ {
arr.Push(values.NewInt(i))
2018-09-23 01:18:10 +02:00
}
return arr, nil
}