From ecd08b77ef70b451ea2bb3c9a50d69619cb1f4f0 Mon Sep 17 00:00:00 2001 From: Henry-Sarabia Date: Fri, 15 Feb 2019 00:29:47 -0800 Subject: [PATCH] Add Atoi/Itoa functions and tests --- sliceconv.go | 28 ++++++++++++++++++++++++ sliceconv_test.go | 55 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 sliceconv.go create mode 100644 sliceconv_test.go diff --git a/sliceconv.go b/sliceconv.go new file mode 100644 index 0000000..2576bb0 --- /dev/null +++ b/sliceconv.go @@ -0,0 +1,28 @@ +package sliceconv + +import ( + "github.com/pkg/errors" + "strconv" +) + +func Itoa(ints ...int) []string { + var str []string + for _, i := range ints { + str = append(str, strconv.Itoa(i)) + } + return str +} + +func Atoi(str ...string) ([]int, error) { + var ints []int + for _, s := range str { + i, err := strconv.Atoi(s) + if err != nil { + return nil, errors.Wrap(err, "one or more strings could not be converted to type int") + } + + ints = append(ints, i) + } + + return ints, nil +} diff --git a/sliceconv_test.go b/sliceconv_test.go new file mode 100644 index 0000000..9d24f01 --- /dev/null +++ b/sliceconv_test.go @@ -0,0 +1,55 @@ +package sliceconv + +import ( + "github.com/pkg/errors" + "reflect" + "testing" +) + +func TestItoa(t *testing.T) { + tests := []struct { + name string + ints []int + wantStrings []string + }{ + {"Nil slice", nil, nil}, + {"Empty int slice", []int{}, nil}, + {"Single int", []int{1}, []string{"1"}}, + {"Multiple ints", []int{1, 2, 3}, []string{"1", "2", "3"}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + s := Itoa(test.ints...) + + if !reflect.DeepEqual(s, test.wantStrings) { + t.Errorf("got: <%v>, want: <%v>", s, test.wantStrings) + } + }) + } +} + +func TestAtoi(t *testing.T) { + tests := []struct { + name string + strings []string + wantInts []int + wantErr error + }{ + {"Nil slice", nil, nil, nil}, + {"Empty string slice", []string{}, nil, nil}, + {"Single string", []string{"1"}, []int{1}, nil}, + {"Multiple string", []string{"1", "2", "3"}, []int{1, 2, 3}, nil}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + ints, err := Atoi(test.strings...) + if errors.Cause(err) != test.wantErr { + t.Errorf("got: <%v>, want: <%v>", errors.Cause(err), test.wantErr) + } + + if !reflect.DeepEqual(ints, test.wantInts) { + t.Errorf("got: <%v>, want: <%v>", ints, test.wantInts) + } + }) + } +}