1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/pkg/stdlib/arrays/nth.go
2018-10-14 13:06:27 -04:00

40 lines
1.0 KiB
Go

package arrays
import (
"context"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
)
// Nth returns the element of an array at a given position.
// It is the same as anyArray[position] for positive positions, but does not support negative positions.
// @param array (Array) - An array with elements of arbitrary type.
// @param index (Int) - Position of desired element in array, positions start at 0.
// @returns (Read) - The array element at the given position.
// If position is negative or beyond the upper bound of the array, then NONE will be returned.
func Nth(_ context.Context, args ...core.Value) (core.Value, error) {
err := core.ValidateArgs(args, 2, 2)
if err != nil {
return values.None, err
}
err = core.ValidateType(args[0], core.ArrayType)
if err != nil {
return values.None, err
}
err = core.ValidateType(args[1], core.IntType)
if err != nil {
return values.None, err
}
arr := args[0].(*values.Array)
idx := args[1].(values.Int)
return arr.Get(idx), nil
}