|
| 1 | +// ================================================================= |
| 2 | +// |
| 3 | +// Copyright (C) 2018 Spatial Current, Inc. - All Rights Reserved |
| 4 | +// Released as open source under the MIT License. See LICENSE file. |
| 5 | +// |
| 6 | +// ================================================================= |
| 7 | + |
| 8 | +package dfl |
| 9 | + |
| 10 | +import ( |
| 11 | + "fmt" |
| 12 | + "reflect" |
| 13 | +) |
| 14 | + |
| 15 | +import ( |
| 16 | + "github.com/pkg/errors" |
| 17 | +) |
| 18 | + |
| 19 | +// AddValues adds 2 values and returns the result. |
| 20 | +// The parameters can be an int, int64, float64, string, or []byte. |
| 21 | +// The parameters will be cast as applicable. |
| 22 | +// For example you can add two integers with |
| 23 | +// total := AddNumbers(1, 2) |
| 24 | +// or you could add an int with a float64. |
| 25 | +// total := AddNumbers(1.54345345, 5) |
| 26 | +func AddValues(a interface{}, b interface{}) (interface{}, error) { |
| 27 | + switch a.(type) { |
| 28 | + case string: |
| 29 | + switch b.(type) { |
| 30 | + case string: |
| 31 | + return a.(string) + b.(string), nil |
| 32 | + } |
| 33 | + case []byte: |
| 34 | + a_bytes := a.([]byte) |
| 35 | + switch b.(type) { |
| 36 | + case []byte: |
| 37 | + b_bytes := b.([]byte) |
| 38 | + return append(append(make([]byte, 0, len(a_bytes)+len(b_bytes)), a_bytes...), b_bytes...), nil |
| 39 | + } |
| 40 | + case int: |
| 41 | + switch b.(type) { |
| 42 | + case int: |
| 43 | + return a.(int) + b.(int), nil |
| 44 | + case int64: |
| 45 | + return int64(a.(int)) + b.(int64), nil |
| 46 | + case float64: |
| 47 | + return float64(a.(int)) + b.(float64), nil |
| 48 | + } |
| 49 | + case int64: |
| 50 | + switch b.(type) { |
| 51 | + case int: |
| 52 | + return a.(int64) + int64(b.(int)), nil |
| 53 | + case int64: |
| 54 | + return a.(int64) + b.(int64), nil |
| 55 | + case float64: |
| 56 | + return float64(a.(int64)) + b.(float64), nil |
| 57 | + } |
| 58 | + case float64: |
| 59 | + switch b.(type) { |
| 60 | + case int: |
| 61 | + return a.(float64) + float64(b.(int)), nil |
| 62 | + case int64: |
| 63 | + return a.(float64) + float64(b.(int64)), nil |
| 64 | + case float64: |
| 65 | + return a.(float64) + b.(float64), nil |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return 0, errors.New(fmt.Sprintf("Error adding values %#v (%v) and %#v (%v)", a, reflect.TypeOf(a).String(), b, reflect.TypeOf(b).String())) |
| 70 | +} |
0 commit comments