Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.