github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/math/rand.go (about)

     1  package math
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/MontFerret/ferret/pkg/runtime/core"
     7  	"github.com/MontFerret/ferret/pkg/runtime/values"
     8  )
     9  
    10  // RAND return a pseudo-random number between 0 and 1.
    11  // @param {Int | Float} [max] - Upper limit.
    12  // @param {Int | Float} [min] - Lower limit.
    13  // @return {Float} - A number greater than 0 and less than 1.
    14  func Rand(_ context.Context, args ...core.Value) (core.Value, error) {
    15  	err := core.ValidateArgs(args, 0, 2)
    16  
    17  	if err != nil {
    18  		return values.None, err
    19  	}
    20  
    21  	if len(args) == 0 {
    22  		return values.NewFloat(core.RandomDefault()), nil
    23  	}
    24  
    25  	var max float64
    26  	var min float64
    27  
    28  	max = float64(values.ToFloat(args[0]))
    29  
    30  	if len(args) > 1 {
    31  		min = float64(values.ToFloat(args[1]))
    32  	} else {
    33  		max, min = core.NumberBoundaries(max)
    34  	}
    35  
    36  	return values.NewFloat(core.Random(max, min)), nil
    37  }