diff --git a/pkg/runtime/core/helpers.go b/pkg/runtime/core/helpers.go index 0b0573d8..a9cce820 100644 --- a/pkg/runtime/core/helpers.go +++ b/pkg/runtime/core/helpers.go @@ -1,6 +1,10 @@ package core -import "reflect" +import ( + "math" + "math/rand" + "reflect" +) func IsNil(input interface{}) bool { val := reflect.ValueOf(input) @@ -24,3 +28,18 @@ func IsNil(input interface{}) bool { return false } } + +func NumberBoundaries(input float64) (max float64, min float64) { + min = input / 2 + max = input * 2 + + return +} + +func Random(max float64, min float64) float64 { + r := rand.Float64() + i := r * (max - min + 1) + out := math.Floor(i) + min + + return out +} diff --git a/pkg/stdlib/math/rand.go b/pkg/stdlib/math/rand.go index c5fb31f7..186bc811 100644 --- a/pkg/stdlib/math/rand.go +++ b/pkg/stdlib/math/rand.go @@ -9,13 +9,42 @@ import ( ) // Rand return a pseudo-random number between 0 and 1. +// @param max (Float|Int, optional) - Upper limit. +// @param min (Float|Int, optional) - Lower limit. // @returns (Float) - A number greater than 0 and less than 1. func Rand(_ context.Context, args ...core.Value) (core.Value, error) { - err := core.ValidateArgs(args, 0, 0) + err := core.ValidateArgs(args, 0, 2) if err != nil { return values.None, err } - return values.NewFloat(rand.Float64()), nil + if len(args) == 0 { + return values.NewFloat(rand.Float64()), nil + } + + var max float64 + var min float64 + + arg1, err := values.ToFloat(args[0]) + + if err != nil { + return values.None, err + } + + max = float64(arg1) + + if len(args) > 1 { + arg2, err := values.ToFloat(args[1]) + + if err != nil { + return values.None, err + } + + min = float64(arg2) + } else { + max, min = core.NumberBoundaries(max) + } + + return values.NewFloat(core.Random(max, min)), nil } diff --git a/pkg/stdlib/utils/wait.go b/pkg/stdlib/utils/wait.go index 1459f97d..5f535c48 100644 --- a/pkg/stdlib/utils/wait.go +++ b/pkg/stdlib/utils/wait.go @@ -6,28 +6,23 @@ import ( "github.com/MontFerret/ferret/pkg/runtime/core" "github.com/MontFerret/ferret/pkg/runtime/values" - "github.com/MontFerret/ferret/pkg/runtime/values/types" ) // Wait pauses the execution for a given period. -// @param timeout (Int) - Integer value indication for how long to pause. -func Wait(_ context.Context, inputs ...core.Value) (core.Value, error) { - err := core.ValidateArgs(inputs, 1, 1) +// @param timeout (Float|Int) - Number value which indicates for how long to stop an execution. +func Wait(_ context.Context, args ...core.Value) (core.Value, error) { + err := core.ValidateArgs(args, 1, 1) if err != nil { return values.None, nil } - arg := values.ZeroInt - - err = core.ValidateType(inputs[0], types.Int) + arg, err := values.ToInt(args[0]) if err != nil { return values.None, err } - arg = inputs[0].(values.Int) - time.Sleep(time.Millisecond * time.Duration(arg)) return values.None, nil