Skip to content

Instantly share code, notes, and snippets.

@maythiago
Created July 27, 2020 22:17
Show Gist options
  • Select an option

  • Save maythiago/a35a3018bcd95a1d2aaa0e1ce9641ff0 to your computer and use it in GitHub Desktop.

Select an option

Save maythiago/a35a3018bcd95a1d2aaa0e1ce9641ff0 to your computer and use it in GitHub Desktop.
package main
import (
"regexp"
"strconv"
)
func Add(valueString string) int {
if valueString == "" {
return 0
}
re := regexp.MustCompile("^(//.*\n)")
delimiter := "[,\n]"
if re.MatchString(valueString) {
delimiter = string(valueString[2])
valueString = re.ReplaceAllString(valueString, "")
}
re = regexp.MustCompile(delimiter)
value := re.Split(valueString, -1)
sum := 0
for i := 0; i < len(value); i++ {
value, _ := strconv.Atoi(value[i])
if value < 0 {
panic("negatives not allowed")
}
sum += value
}
return sum
}
func main() {
Add("")
}
package main
import "testing"
func TestEmptyShouldReturnZero(t *testing.T) {
value := Add("")
want := 0
if value != want {
t.Errorf("value %q want %q", value, want)
}
}
func TestSingleValueShouldReturnSingleInt(t *testing.T) {
value := Add("1")
want := 1
if value != want {
t.Errorf("value %q want %q", value, want)
}
}
func TestTwoValuesShouldReturnSum(t *testing.T) {
value := Add("1,2")
want := 3
if value != want {
t.Errorf("value %q want %q", value, want)
}
}
func TestNValuesShouldReturnSum(t *testing.T) {
value := Add("1,2,3,4,5,6,7,8,9")
want := 45
if value != want {
t.Errorf("value %q want %q", value, want)
}
}
func TestNValuesShouldReturnSumWithSpace(t *testing.T) {
value := Add("1\n2,3")
want := 6
if value != want {
t.Errorf("value %q want %q", value, want)
}
}
func TestShouldCustomizeDemilimiter(t *testing.T) {
value := Add("//;\n1;2")
want := 3
if value != want {
t.Errorf("value %q want %q", value, want)
}
}
func TestShouldNotAllowNegativeNumber(t *testing.T) {
defer func() {
if r := recover(); r != "negatives not allowed" {
t.Error()
}
}()
Add("-1")
}
https://kata-log.rocks/string-calculator-kata
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment