github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/math/min.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  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
     9  )
    10  
    11  // MIN returns the smallest (arithmetic mean) of the values in array.
    12  // @param {Int[] | Float[]} array - Array of numbers.
    13  // @return {Float} - The smallest of the values in array.
    14  func Min(_ context.Context, args ...core.Value) (core.Value, error) {
    15  	err := core.ValidateArgs(args, 1, 1)
    16  
    17  	if err != nil {
    18  		return values.None, err
    19  	}
    20  
    21  	err = core.ValidateType(args[0], types.Array)
    22  
    23  	if err != nil {
    24  		return values.None, err
    25  	}
    26  
    27  	arr := args[0].(*values.Array)
    28  
    29  	if arr.Length() == 0 {
    30  		return values.None, nil
    31  	}
    32  
    33  	var min float64
    34  
    35  	arr.ForEach(func(value core.Value, idx int) bool {
    36  		err = core.ValidateType(value, types.Int, types.Float)
    37  
    38  		if err != nil {
    39  			return false
    40  		}
    41  
    42  		fv := toFloat(value)
    43  
    44  		if min > fv || idx == 0 {
    45  			min = fv
    46  		}
    47  
    48  		return true
    49  	})
    50  
    51  	if err != nil {
    52  		return values.None, nil
    53  	}
    54  
    55  	return values.NewFloat(min), nil
    56  }