diff --git a/Sources/Tonic/Key.swift b/Sources/Tonic/Key.swift index 3337384..4baebd1 100644 --- a/Sources/Tonic/Key.swift +++ b/Sources/Tonic/Key.swift @@ -15,12 +15,6 @@ public struct Key: Equatable { /// A note set containing all the notes in the key public let noteSet: NoteSet - /// All the traditional triads representable root, third, and fifth from each note in the key - public let primaryTriads: [Chord] - - /// All chords that fit in the key - public let chords: [Chord] - /// Initialize the key /// - Parameters: /// - root: The primary note class of the key, also known as the tonic @@ -36,7 +30,36 @@ public struct Key: Equatable { } } noteSet = NoteSet(notes: r) + } + + /// The type of accidental to use in this key + public var preferredAccidental: Accidental { + if root.accidental == .sharp { + return .sharp + } + if root.accidental == .flat { + return .flat + } + + let naturalKeysWithFlats: [Key] = [.F, .d, .g, .c, .f] + if naturalKeysWithFlats.contains(self) { + return .flat + } + return .sharp + } + /// All chords that fit in the key + public var chords: [Chord] { + let table = ChordTable.shared + var chords: [Chord] = [] + for (_, chord) in table.chords where chord.noteClassSet.isSubset(of: noteSet.noteClassSet) { + chords.append(Chord(chord.root, type: chord.type)) + } + return chords + } + + /// All the traditional triads representable root, third, and fifth from each note in the key + public var primaryTriads: [Chord] { let table = ChordTable.shared var chords: [Chord] = [] @@ -53,25 +76,7 @@ public struct Key: Equatable { let primaryTriadsStartingWithC = primaryTriads.sorted(by: { $0.root.letter < $1.root.letter }) let rootPosition = primaryTriadsStartingWithC.firstIndex(where: { $0.root == root }) ?? 0 - self.primaryTriads = Array(primaryTriadsStartingWithC.rotatingLeft(positions: rootPosition)) - - self.chords = chords - } - - /// The type of accidental to use in this key - public var preferredAccidental: Accidental { - if root.accidental == .sharp { - return .sharp - } - if root.accidental == .flat { - return .flat - } - - let naturalKeysWithFlats: [Key] = [.F, .d, .g, .c, .f] - if naturalKeysWithFlats.contains(self) { - return .flat - } - return .sharp + return Array(primaryTriadsStartingWithC.rotatingLeft(positions: rootPosition)) } }