-
Notifications
You must be signed in to change notification settings - Fork 0
/
course.go
48 lines (42 loc) · 1.25 KB
/
course.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package opendata
import (
"fmt"
"regexp"
"strconv"
"strings"
)
// Course is a normalized struct for course and section ID.
type Course struct{ string }
func validCourse(course string) bool {
if len(course) <= 0 {
return false
}
switch course[len(course)-1] {
case 'A', 'B', 'a', 'b':
course = course[:len(course)-1]
}
num, err := strconv.Atoi(course)
if err != nil || num <= 0 {
return false
}
return num <= 9999
}
// NewCourse generates a new Course instance based on course subject, number, and section ID.
func NewCourse(subject, number, section string) *Course {
subject = strings.ToUpper(strings.TrimSpace(subject))
section = strings.ToUpper(strings.TrimSpace(section))
if len(subject) > 4 || len(subject) <= 1 || !validCourse(number) || len(section) != 3 {
return nil
}
return &Course{fmt.Sprintf("%s%04s%s", subject, number, section)}
}
var courseRegex = regexp.MustCompile(`^([a-zA-Z]{2,4})\s*-?(\d{2,4}[abAB]?)-?([\da-zA-Z]{3})$`)
// ParseCourse generates a new Course instance based on course ID string using regex to match.
// ParseCourse("MUSC0050003")
func ParseCourse(course string) *Course {
match := courseRegex.FindStringSubmatch(course)
if len(match) != 4 {
return nil
}
return NewCourse(match[1], match[2], match[3])
}