| 1 | package execution |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/tomwright/dasel/v3/model" |
| 8 | ) |
| 9 | |
| 10 | // FuncUnique is a function that removes duplicate values from an array. |
| 11 | var FuncUnique = NewFunc( |
| 12 | "unique", |
| 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("unique expects an array, got %s", input.Type().String()) |
| 23 | } |
| 24 | |
| 25 | res := model.NewSliceValue() |
| 26 | if err := input.RangeSlice(func(i int, value *model.Value) error { |
| 27 | duplicate := false |
| 28 | _ = res.RangeSlice(func(j int, existing *model.Value) error { |
| 29 | equal, err := value.EqualTypeValue(existing) |
| 30 | if err != nil { |
| 31 | return nil |
| 32 | } |
| 33 | if equal { |
| 34 | duplicate = true |
| 35 | } |
| 36 | return nil |
| 37 | }) |
| 38 | if !duplicate { |
| 39 | return res.Append(value) |
| 40 | } |
| 41 | return nil |
| 42 | }); err != nil { |
| 43 | return nil, err |
| 44 | } |
| 45 | |
| 46 | return res, nil |
| 47 | }, |
| 48 | ValidateArgsMax(1), |
| 49 | ) |