exercism/go/phone-number/phonenumber.go

45 lines
919 B
Go
Raw Normal View History

2016-08-23 20:47:19 +00:00
package phonenumber
import (
"errors"
"strings"
)
// Number takes a number and validates it
func Number(num string) (string, error) {
num = strings.Map(func(r rune) rune {
if r >= '0' && r <= '9' {
return r
}
return -1
}, num)
// A number can be 11 digits long, if it starts with a 1
// but ignore that one.
if len(num) == 11 && num[0] == '1' {
num = num[1:]
}
if len(num) != 10 {
return "", errors.New("Invalid Number")
}
return num, nil
}
// AreaCode takes a number, validates it, and returns the area code
func AreaCode(num string) (string, error) {
num, err := Number(num)
if err != nil {
return "", err
}
return num[:3], nil
}
// Format takes a number, validates it and returns it in the format
// (nnn) nnn-nnnn
func Format(num string) (string, error) {
num, err := Number(num)
if err != nil {
return "", err
}
return "(" + num[:3] + ") " + num[3:6] + "-" + num[6:], nil
}