Skip to content

Commit

Permalink
Add Atoi/Itoa functions and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Henry-Sarabia committed Feb 15, 2019
0 parents commit ecd08b7
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
28 changes: 28 additions & 0 deletions sliceconv.go
Original file line number Diff line number Diff line change
@@ -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
}
55 changes: 55 additions & 0 deletions sliceconv_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}

0 comments on commit ecd08b7

Please sign in to comment.