// Package wordy parses the question and answers it.
package wordy
import (
"strconv"
"strings"
)
// Answer gives the answer for input question.
func Answer(input string) (int, bool) {
input = strings.Replace(input, "by", "", -1)
input = strings.TrimRight(input, "?")
// drop "What is"
fields := strings.Fields(input)[2:]
if len(fields) == 0 {
return 0, false
}
var res int64
for i, f := range fields {
if i == 0 {
var err error
res, err = strconv.ParseInt(f, 10, 64)
if err != nil {
return 0, false
}
} else if i%2 != 0 {
// there is no next item in slice to parse
if i+1 >= len(fields) {
return 0, false
}
tmp, err := strconv.ParseInt(fields[i+1], 10, 64)
if err != nil {
return 0, false
}
switch f {
case "plus":
res += tmp
case "minus":
res -= tmp
case "multiplied":
res *= tmp
case "divided":
res /= tmp
default:
return 0, false
}
}
}
return int(res), true
}