// Package phonenumber is for NANP phone number handling.
package phonenumber
import (
"fmt"
"strings"
"unicode"
)
// Number parses input and validates it. Returns 10 digits on success, error otherwise.
func Number(input string) (string, error) {
out := strings.Builder{}
for _, ch := range input {
if unicode.IsDigit(ch) {
if out.Len() == 0 && ch == '1' {
continue
}
if out.Len() == 0 && ch == '0' {
return "", fmt.Errorf("area code must not start with 0")
}
if out.Len() == 3 && (ch == '0' || ch == '1') {
return "", fmt.Errorf("exchange code must not start with 0 or 1")
}
out.WriteRune(ch)
}
}
if out.Len() != 10 {
return "", fmt.Errorf("input must contain 10/11 digits")
}
return out.String(), nil
}
// AreaCode returns the area code only.
func AreaCode(input string) (string, error) {
out, err := Number(input)
if err != nil {
return "", err
}
return out[:3], nil
}
// Format returns input in (NXX) NXX-XXXX style.
func Format(input string) (string, error) {
out, err := Number(input)
if err != nil {
return "", err
}
return "(" + out[:3] + ") " + out[3:6] + "-" + out[6:], nil
}