Skip to content

Instantly share code, notes, and snippets.

@InsulaVentus
Created August 30, 2019 09:21
Show Gist options
  • Save InsulaVentus/bb448713868c2e73cfbb451038ed0d13 to your computer and use it in GitHub Desktop.
Save InsulaVentus/bb448713868c2e73cfbb451038ed0d13 to your computer and use it in GitHub Desktop.
package record
import (
"errors"
"fmt"
"strings"
"unicode"
)
// LicensePlate represents a license plate that can be attempted normalized.
type LicensePlate struct {
string
}
const maxLength = 8
// NewLicensePlate returns a new LicensePlate
func NewLicensePlate(s string) *LicensePlate {
return &LicensePlate{s}
}
// Normalize returns a pointer reference to a new uppercase LicensePlate without whitespace.
// If the LicensePlate cannot be normalized, an error is returned.
// A LicensePlate cannot be normalized if:
// It has more than 8 non-whitespace characters, contains special characters or
// contains no alphanumerics (digits and letters).
func (lp *LicensePlate) Normalize() (nlp *LicensePlate, err error) {
if len(lp.string) == 0 {
return nil, errors.New("empty string")
}
var b strings.Builder
b.Grow(len(lp.string))
runes := 0
for index, r := range lp.string {
if unicode.IsDigit(r) || unicode.IsLetter(r) {
if runes < maxLength {
b.WriteRune(unicode.ToUpper(r))
runes++
} else {
return nil, fmt.Errorf("more than %d characters", maxLength)
}
} else if !unicode.IsSpace(r) {
return nil, fmt.Errorf("invalid character %#U at byte position %d", r, index)
}
}
if b.Len() == 0 {
return nil, errors.New("no alphanumerics")
}
return &LicensePlate{b.String()}, nil
}
func (lp *LicensePlate) String() string {
return lp.string
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment