Created
January 5, 2017 03:42
-
-
Save adomokos/df48c3877afd0e4a4c88f080ea9b64b6 to your computer and use it in GitHub Desktop.
String Calculator in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package string_calculator | |
import ( | |
"github.com/stretchr/testify/assert" | |
"strconv" | |
"strings" | |
"testing" | |
) | |
func Convert(params ...string) int { | |
if len(params) == 1 { | |
return convert(params[0], ",") | |
} | |
if len(params) == 2 { | |
return convert(params[0], params[1]) | |
} | |
return 0 | |
} | |
func convert(input string, separator string) int { | |
if input == "" { | |
return 0 | |
} | |
parts := strings.Split(input, separator) | |
result := 0 | |
for _, part := range parts { | |
i, err := strconv.Atoi(part) | |
if err != nil { | |
panic(err) | |
} | |
result += i | |
} | |
return result | |
} | |
func TestEmptyString(t *testing.T) { | |
assert.Equal(t, 0, Convert("")) | |
} | |
func TestSingleDigit(t *testing.T) { | |
assert.Equal(t, 1, Convert("1")) | |
} | |
func TestTwoNumbers(t *testing.T) { | |
assert.Equal(t, 3, Convert("1,2")) | |
} | |
func TestThreeNumbers(t *testing.T) { | |
assert.Equal(t, 6, Convert("1,2,3")) | |
} | |
func TestPipeSeparator(t *testing.T) { | |
assert.Equal(t, 6, Convert("1|2|3", "|")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment