Skip to content

Commit 76d61ce

Browse files
Improved performance of chords creation for a specific key by creating functions instead of creating them on init (#52)
* improved performance on chords creation for key by creating functions that only create the necessary * fixed unit-tests * converted functions to computed properties
1 parent 8f103c6 commit 76d61ce

File tree

1 file changed

+30
-25
lines changed

1 file changed

+30
-25
lines changed

Sources/Tonic/Key.swift

Lines changed: 30 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,6 @@ public struct Key: Equatable {
1515
/// A note set containing all the notes in the key
1616
public let noteSet: NoteSet
1717

18-
/// All the traditional triads representable root, third, and fifth from each note in the key
19-
public let primaryTriads: [Chord]
20-
21-
/// All chords that fit in the key
22-
public let chords: [Chord]
23-
2418
/// Initialize the key
2519
/// - Parameters:
2620
/// - root: The primary note class of the key, also known as the tonic
@@ -36,7 +30,36 @@ public struct Key: Equatable {
3630
}
3731
}
3832
noteSet = NoteSet(notes: r)
33+
}
34+
35+
/// The type of accidental to use in this key
36+
public var preferredAccidental: Accidental {
37+
if root.accidental == .sharp {
38+
return .sharp
39+
}
40+
if root.accidental == .flat {
41+
return .flat
42+
}
43+
44+
let naturalKeysWithFlats: [Key] = [.F, .d, .g, .c, .f]
45+
if naturalKeysWithFlats.contains(self) {
46+
return .flat
47+
}
48+
return .sharp
49+
}
3950

51+
/// All chords that fit in the key
52+
public var chords: [Chord] {
53+
let table = ChordTable.shared
54+
var chords: [Chord] = []
55+
for (_, chord) in table.chords where chord.noteClassSet.isSubset(of: noteSet.noteClassSet) {
56+
chords.append(Chord(chord.root, type: chord.type))
57+
}
58+
return chords
59+
}
60+
61+
/// All the traditional triads representable root, third, and fifth from each note in the key
62+
public var primaryTriads: [Chord] {
4063
let table = ChordTable.shared
4164

4265
var chords: [Chord] = []
@@ -53,25 +76,7 @@ public struct Key: Equatable {
5376

5477
let primaryTriadsStartingWithC = primaryTriads.sorted(by: { $0.root.letter < $1.root.letter })
5578
let rootPosition = primaryTriadsStartingWithC.firstIndex(where: { $0.root == root }) ?? 0
56-
self.primaryTriads = Array(primaryTriadsStartingWithC.rotatingLeft(positions: rootPosition))
57-
58-
self.chords = chords
59-
}
60-
61-
/// The type of accidental to use in this key
62-
public var preferredAccidental: Accidental {
63-
if root.accidental == .sharp {
64-
return .sharp
65-
}
66-
if root.accidental == .flat {
67-
return .flat
68-
}
69-
70-
let naturalKeysWithFlats: [Key] = [.F, .d, .g, .c, .f]
71-
if naturalKeysWithFlats.contains(self) {
72-
return .flat
73-
}
74-
return .sharp
79+
return Array(primaryTriadsStartingWithC.rotatingLeft(positions: rootPosition))
7580
}
7681
}
7782

0 commit comments

Comments
 (0)