| 1 | package execution |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/tomwright/dasel/v3/model" |
| 8 | ) |
| 9 | |
| 10 | // FuncLast is a function that returns the last element of an array. |
| 11 | var FuncLast = NewFunc( |
| 12 | "last", |
| 13 | func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) { |
| 14 | var input *model.Value |
| 15 | if len(args) == 1 { |
| 16 | input = args[0] |
| 17 | } else { |
| 18 | input = data |
| 19 | } |
| 20 | |
| 21 | if !input.IsSlice() { |
| 22 | return nil, fmt.Errorf("last expects an array, got %s", input.Type().String()) |
| 23 | } |
| 24 | |
| 25 | length, err := input.SliceLen() |
| 26 | if err != nil { |
| 27 | return nil, err |
| 28 | } |
| 29 | if length == 0 { |
| 30 | return model.NewNullValue(), nil |
| 31 | } |
| 32 | |
| 33 | return input.GetSliceIndex(length - 1) |
| 34 | }, |
| 35 | ValidateArgsMax(1), |
| 36 | ) |