-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathparse.go
109 lines (94 loc) · 2.11 KB
/
parse.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package musictheory
import (
"fmt"
"regexp"
"strconv"
)
var (
pitch = regexp.MustCompile("([ABCDEFG])(bb|b|#|x)?(\\d+)")
interval = regexp.MustCompile("([-+])?([PAdMm]|perf|maj|min|aug|dim)(\\d+)")
)
// MustParsePitch parses and returns a Pitch in scientific pitch notation or panics
func MustParsePitch(str string) Pitch {
pitch, err := ParsePitch(str)
if err != nil {
panic(err)
}
return pitch
}
// ParsePitch parses and returns a Pitch in scientific pitch notation
func ParsePitch(str string) (Pitch, error) {
matches := pitch.FindStringSubmatch(str)
if len(matches) < 1 {
return Pitch{}, fmt.Errorf("no matches found")
}
class := matches[1]
modifier := matches[2]
octave, err := strconv.Atoi(matches[3])
if err != nil {
return Pitch{}, err
}
classIndex, err := classNameIndex(class)
if err != nil {
return Pitch{}, err
}
modifierOffset, err := modifierNameOffset(modifier)
if err != nil {
return Pitch{}, err
}
return NewPitch(classIndex+1, modifierOffset, octave), nil
}
func classNameIndex(name string) (int, error) {
for i, n := range pitchNames {
if n == name {
return i, nil
}
}
return 0, fmt.Errorf("unknown class name: %s", name)
}
func modifierNameOffset(name string) (int, error) {
for i, a := range modifierNames {
if a == name {
return i - 2, nil
}
}
return 0, fmt.Errorf("unknown modifier: %s", name)
}
func ParseInterval(str string) (Interval, error) {
matches := interval.FindStringSubmatch(str)
if len(matches) < 1 {
return Interval{}, fmt.Errorf("no matches found")
}
quality := matches[2]
polarity := "+"
if len(matches[1]) > 0 {
polarity = matches[1]
}
step, _ := strconv.Atoi(polarity + matches[3])
var interval Interval
switch quality {
case "perf":
fallthrough
case "P":
interval = Perfect(step)
case "aug":
fallthrough
case "A":
interval = Augmented(step)
case "maj":
fallthrough
case "M":
interval = Major(step)
case "min":
fallthrough
case "m":
interval = Minor(step)
case "dim":
fallthrough
case "d":
interval = Diminished(step)
default:
return Interval{}, fmt.Errorf("invalid quality")
}
return interval, nil
}