|
| 1 | +// Package calc provides some utility functions for calculation. |
| 2 | +// |
| 3 | +// Calc 包提供一些计算相关的工具函数。 |
| 4 | +package calc |
| 5 | + |
| 6 | +import ( |
| 7 | + "fmt" |
| 8 | + |
| 9 | + jsonvalue "github.com/Andrew-M-C/go.jsonvalue" |
| 10 | +) |
| 11 | + |
| 12 | +var emptyValue = &jsonvalue.V{} |
| 13 | + |
| 14 | +// ConcatStrings finds every string-typed sub value of a and b, and concatenates them into a new JSON value. |
| 15 | +// |
| 16 | +// ConcatStrings 找到 a 和 b 的所有 string 类型的子值,并将它们拼接成一个新的 JSON 值。 |
| 17 | +func ConcatStrings(a, b *jsonvalue.V) (*jsonvalue.V, error) { |
| 18 | + if a.ValueType() != b.ValueType() { |
| 19 | + return emptyValue, fmt.Errorf("%w: input parameters have different types", jsonvalue.ErrParameterError) |
| 20 | + } |
| 21 | + |
| 22 | + var res *jsonvalue.V |
| 23 | + |
| 24 | + switch a.ValueType() { |
| 25 | + case jsonvalue.String: |
| 26 | + // for string type, simply concatenate them |
| 27 | + return jsonvalue.NewString(a.String() + b.String()), nil |
| 28 | + |
| 29 | + case jsonvalue.Object: |
| 30 | + // for object type, iterate and concatenate each string-typed sub value |
| 31 | + res = jsonvalue.NewObject() |
| 32 | + // and go on |
| 33 | + |
| 34 | + case jsonvalue.Array: |
| 35 | + // for array type, iterate and concatenate each string-typed sub value |
| 36 | + res = jsonvalue.NewArray() |
| 37 | + // and go on |
| 38 | + |
| 39 | + default: |
| 40 | + return emptyValue, fmt.Errorf( |
| 41 | + "%w: only string, object and array type are supported", jsonvalue.ErrParameterError, |
| 42 | + ) |
| 43 | + } |
| 44 | + |
| 45 | + // Walk a |
| 46 | + a.Walk(func(path jsonvalue.Path, v *jsonvalue.V) bool { |
| 47 | + // if not string type, simply set it |
| 48 | + if v.ValueType() != jsonvalue.String { |
| 49 | + res.MustSet(v).At(path) |
| 50 | + return true |
| 51 | + } |
| 52 | + |
| 53 | + // if string type, just concatenate if |
| 54 | + strB := b.MustGet(path).String() |
| 55 | + res.MustSet(v.String() + strB).At(path) |
| 56 | + return true |
| 57 | + }) |
| 58 | + |
| 59 | + // Walk b |
| 60 | + b.Walk(func(path jsonvalue.Path, v *jsonvalue.V) bool { |
| 61 | + if _, err := res.Get(path); err != nil { |
| 62 | + res.MustSet(v).At(path) // value not exists, set it |
| 63 | + } |
| 64 | + return true |
| 65 | + }) |
| 66 | + |
| 67 | + return res, nil |
| 68 | +} |
0 commit comments