Skip to content

Instantly share code, notes, and snippets.

@oscarryz
Last active December 12, 2015 08:58
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 oscarryz/4747501 to your computer and use it in GitHub Desktop.
Save oscarryz/4747501 to your computer and use it in GitHub Desktop.
stringcalculator in go
package calculator
import (
"errors"
"fmt"
"strconv"
"strings"
)
func Add(numbers string) (int, error) {
separators := ",\n"
if strings.HasPrefix(numbers, "//") {
if nli := strings.Index(numbers, "\n"); nli > 1 {
separators = numbers[2 : nli+1]
numbers = numbers[nli:len(numbers)]
}
}
splitter := func(r rune) bool {
return strings.ContainsRune(separators, r)
}
result := 0
negatives := make([]int, 0)
for _, v := range strings.FieldsFunc(numbers, splitter) {
i, e := strconv.Atoi(v)
if e == nil && i >= 0 {
result += i
} else if i < 0 {
negatives = append(negatives, i)
} else {
return 0, nil
}
}
if len(negatives) > 0 {
return 0, errors.New(fmt.Sprintf("negatives not allowed %v", negatives))
}
return result, nil
}
package calculator
import (
"strconv"
"testing"
)
func assert(input string, expected int, t *testing.T) {
if output, _ := Add(input); output != expected {
t.Errorf("Add(\"%v\") = %v, want %v", input, output, expected)
}
}
func TestEmpty(t *testing.T) {
assert("", 0, t)
}
func TestAdd(t *testing.T) {
assert("1", 1, t)
}
func TestSingleNumber(t *testing.T) {
a := []int{1, 2, 3, 10, 100, 1000, 10000}
for _, v := range a {
assert(strconv.Itoa(v), v, t)
}
}
func TestInvalidInput(t *testing.T) {
assert("a", 0, t)
}
func TestTwoNumbers(t *testing.T) {
assert("1,2", 3, t)
}
func TestMoreNumbers(t *testing.T) {
assert("1,2,3,4,10,100", 120, t)
}
func TestNewLine(t *testing.T) {
assert("1\n2,3", 6, t)
}
func TestSpecifyDelimeter(t *testing.T) {
assert("//;\n1;2", 3, t)
}
func TestNegatives(t *testing.T) {
if _, e := Add("-1,-12"); e.Error() != "negatives not allowed [-1 -12]" {
t.Errorf("Expecting error message: 'negatives not allowed [-1 -12]' got: '%s'", e.Error())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment