-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathscale.go
60 lines (52 loc) · 1.42 KB
/
scale.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
package musictheory
// Scale is a series of Pitches
type Scale []Pitch
// Transpose transposes a scale by the specified Interval
func (s Scale) Transpose(i Interval) Scale {
scale := Scale{}
for _, transposer := range s {
scale = append(scale, transposer.Transpose(i))
}
return scale
}
// NewScale returns a Scale built using a set of intervals
func NewScale(root Pitch, intervals []Interval, octaves int) Scale {
var (
scale = Scale{}
originalRoot = root
descending = (octaves < 0)
)
// Begin at the base of our octave shift
if descending {
root = root.Transpose(Octave(octaves))
}
for i := 0; i < abs(octaves); i++ {
for j, v := range intervals {
// Ignore the tonic which will become the *last* item in the slice
// once reversed. This is to maintain consistency with ascending
// scales: they don't include the final octave of the tonic.
if descending && i == 0 && j == 0 {
continue
}
scale = append(scale, root.Transpose(v))
}
root = root.Transpose(Octave(1))
}
// Add the original tonic to the end. It's about to become the beginning of
// the slice once it's reversed. Reversing the list produces our descending
// scale.
if descending {
scale = append(scale, originalRoot)
for i := len(scale)/2 - 1; i >= 0; i-- {
opp := len(scale) - 1 - i
scale[i], scale[opp] = scale[opp], scale[i]
}
}
return scale
}
func abs(v int) int {
if v < 0 {
return -v
}
return v
}