File: collection_utils.go

package info (click to toggle)
golang-github-approvals-go-approval-tests 0.0~git20180620.6ae1ec6-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 296 kB
  • sloc: xml: 16; makefile: 3
file content (77 lines) | stat: -rw-r--r-- 1,622 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package utils

import (
	"fmt"
	"reflect"
	"sort"
	"strings"
)

// PrintMap prints a map
func PrintMap(m interface{}) string {
	var outputText string

	v := reflect.ValueOf(m)
	if v.Kind() != reflect.Map {
		outputText = fmt.Sprintf("error while printing map\nreceived a %T\n  %s\n", m, m)
	} else {

		keys := v.MapKeys()
		var xs []string

		for _, k := range keys {
			xs = append(xs, fmt.Sprintf("[%s]=%s", k, v.MapIndex(k)))
		}

		sort.Strings(xs)
		if len(xs) == 0 {
			outputText = "len(map) == 0"
		} else {
			outputText = strings.Join(xs, "\n")
		}
	}

	return outputText
}

// PrintArray prints an array
func PrintArray(m interface{}) string {
	var outputText string

	switch reflect.TypeOf(m).Kind() {
	case reflect.Slice:
		var xs []string

		slice := reflect.ValueOf(m)
		for i := 0; i < slice.Len(); i++ {
			xs = append(xs, fmt.Sprintf("[%d]=%s", i, slice.Index(i)))
		}

		if len(xs) == 0 {
			outputText = "len(array) == 0"
		} else {
			outputText = strings.Join(xs, "\n")
		}
	default:
		outputText = fmt.Sprintf("error while printing array\nreceived a %T\n  %s\n", m, m)
	}

	return outputText
}

// MapToString maps a collection to a string collection
func MapToString(collection interface{}, transform func(x interface{}) string) []string {
	switch reflect.TypeOf(collection).Kind() {
	case reflect.Slice:
		var xs []string

		slice := reflect.ValueOf(collection)
		for i := 0; i < slice.Len(); i++ {
			xs = append(xs, transform(slice.Index(i).Interface()))
		}

		return xs
	default:
		panic(fmt.Sprintf("error while mapping array to string\nreceived a %T\n  %s\n", collection, collection))
	}
}