Debian Codegraph @

execution/func_abs.go

raw symbols SCIP
1 package execution
2
3 import (
4 "context"
5 "fmt"
6 "math"
7
8 "github.com/tomwright/dasel/v3/model"
9 )
10
11 // FuncAbs is a function that returns the absolute value of a number.
12 var FuncAbs = NewFunc(
13 "abs",
14 func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) {
15 var input *model.Value
16 if len(args) == 1 {
17 input = args[0]
18 } else {
19 input = data
20 }
21
22 if input.IsInt() {
23 v, err := input.IntValue()
24 if err != nil {
25 return nil, fmt.Errorf("abs could not read int value: %w", err)
26 }
27 if v < 0 {
28 v = -v
29 }
30 return model.NewIntValue(v), nil
31 }
32
33 v, err := input.FloatValue()
34 if err != nil {
35 return nil, fmt.Errorf("abs expects a numeric value: %w", err)
36 }
37 return model.NewFloatValue(math.Abs(v)), nil
38 },
39 ValidateArgsMax(1),
40 )