| 1 | package execution |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/tomwright/dasel/v3/model" |
| 8 | ) |
| 9 | |
| 10 | // FuncAdd is a function that adds the given values together. |
| 11 | var FuncAdd = NewFunc( |
| 12 | "add", |
| 13 | func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) { |
| 14 | var foundInts, foundFloats int |
| 15 | var intRes int64 |
| 16 | var floatRes float64 |
| 17 | for _, arg := range args { |
| 18 | if arg.IsFloat() { |
| 19 | foundFloats++ |
| 20 | v, err := arg.FloatValue() |
| 21 | if err != nil { |
| 22 | return nil, fmt.Errorf("error getting float value: %w", err) |
| 23 | } |
| 24 | floatRes += v |
| 25 | continue |
| 26 | } |
| 27 | if arg.IsInt() { |
| 28 | foundInts++ |
| 29 | v, err := arg.IntValue() |
| 30 | if err != nil { |
| 31 | return nil, fmt.Errorf("error getting int value: %w", err) |
| 32 | } |
| 33 | intRes += v |
| 34 | continue |
| 35 | } |
| 36 | return nil, fmt.Errorf("expected int or float, got %s", arg.Type()) |
| 37 | } |
| 38 | if foundFloats > 0 { |
| 39 | return model.NewFloatValue(floatRes + float64(intRes)), nil |
| 40 | } |
| 41 | return model.NewIntValue(intRes), nil |
| 42 | }, |
| 43 | ValidateArgsMin(1), |
| 44 | ) |