| 1 |
package utils |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"reflect" |
| 6 |
"sort" |
| 7 |
"strings" |
| 8 |
) |
| 9 |
|
| 10 |
// PrintMap prints a map |
| 11 |
func PrintMap(m interface{}) string { |
| 12 |
var outputText string |
| 13 |
|
| 14 |
v := reflect.ValueOf(m) |
| 15 |
if v.Kind() != reflect.Map { |
| 16 |
outputText = fmt.Sprintf("error while printing map\nreceived a %T\n %s\n", m, m) |
| 17 |
} else { |
| 18 |
|
| 19 |
keys := v.MapKeys() |
| 20 |
var xs []string |
| 21 |
|
| 22 |
for _, k := range keys { |
| 23 |
xs = append(xs, fmt.Sprintf("[%s]=%s", k, v.MapIndex(k))) |
| 24 |
} |
| 25 |
|
| 26 |
sort.Strings(xs) |
| 27 |
if len(xs) == 0 { |
| 28 |
outputText = "len(map) == 0" |
| 29 |
} else { |
| 30 |
outputText = strings.Join(xs, "\n") |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
return outputText |
| 35 |
} |
| 36 |
|
| 37 |
// PrintArray prints an array |
| 38 |
func PrintArray(m interface{}) string { |
| 39 |
var outputText string |
| 40 |
|
| 41 |
switch reflect.TypeOf(m).Kind() { |
| 42 |
case reflect.Slice: |
| 43 |
var xs []string |
| 44 |
|
| 45 |
slice := reflect.ValueOf(m) |
| 46 |
for i := 0; i < slice.Len(); i++ { |
| 47 |
xs = append(xs, fmt.Sprintf("[%d]=%s", i, slice.Index(i))) |
| 48 |
} |
| 49 |
|
| 50 |
if len(xs) == 0 { |
| 51 |
outputText = "len(array) == 0" |
| 52 |
} else { |
| 53 |
outputText = strings.Join(xs, "\n") |
| 54 |
} |
| 55 |
default: |
| 56 |
outputText = fmt.Sprintf("error while printing array\nreceived a %T\n %s\n", m, m) |
| 57 |
} |
| 58 |
|
| 59 |
return outputText |
| 60 |
} |
| 61 |
|
| 62 |
// MapToString maps a collection to a string collection |
| 63 |
func MapToString(collection interface{}, transform func(x interface{}) string) []string { |
| 64 |
switch reflect.TypeOf(collection).Kind() { |
| 65 |
case reflect.Slice: |
| 66 |
var xs []string |
| 67 |
|
| 68 |
slice := reflect.ValueOf(collection) |
| 69 |
for i := 0; i < slice.Len(); i++ { |
| 70 |
xs = append(xs, transform(slice.Index(i).Interface())) |
| 71 |
} |
| 72 |
|
| 73 |
return xs |
| 74 |
default: |
| 75 |
panic(fmt.Sprintf("error while mapping array to string\nreceived a %T\n %s\n", collection, collection)) |
| 76 |
} |
| 77 |
} |