Skip to content

Instantly share code, notes, and snippets.

@adomokos
Created January 5, 2017 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adomokos/df48c3877afd0e4a4c88f080ea9b64b6 to your computer and use it in GitHub Desktop.
Save adomokos/df48c3877afd0e4a4c88f080ea9b64b6 to your computer and use it in GitHub Desktop.
String Calculator in Go
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