Skip to content

Commit

Permalink
improved notes function, added additional test (#28)
Browse files Browse the repository at this point in the history
* improved notes function, added additional test

* cleanup
  • Loading branch information
SebastianBoldt authored Jan 28, 2024
1 parent 1103db6 commit 95ed13e
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
31 changes: 29 additions & 2 deletions Sources/Tonic/Chord.swift
Original file line number Diff line number Diff line change
Expand Up @@ -154,13 +154,40 @@ extension Chord {
/// - Parameter octave: initial octave of the chord for inversion 0
/// - Returns: All notes in that chord
public func notes(octave: Int) -> [Note] {
var notes = noteClasses.map {
Note($0.letter, accidental: $0.accidental, octave: octave)
// This array will store all the notes with the correct octaves
var notes: [Note] = []
// Convert the root note class to a note object
let rootNote = Note(root.letter, accidental: root.accidental, octave: octave)
// append the note to the array of our notes
notes.append(rootNote)

// Iterate over all intervals
for interval in self.type.intervals {
// Create the next note by using the shiftup function
if let shifted = rootNote.shiftUp(interval) {
notes.append(shifted)
}
}

// Stores all shifted notes
var shiftedNotes: [Note] = []

// Iterate over all inversion steps
for step in 0..<inversion {
// increase the right index of the base chord depending on the inversion
let index = step % notes.count
notes[index].octave += 1

// if the last note still is higher increase by one again
// This usually happens if a chord is longer than 2 Octaves
if let last = shiftedNotes.last ?? notes.last {
if notes[index].intValue < last.intValue {
notes[index].octave += 1
}
}
// Append the note with the right octave to a new array to we have a properly
// sorted array in the end
shiftedNotes.append(notes[index])
}

return notes.sorted()
Expand Down
24 changes: 24 additions & 0 deletions Tests/TonicTests/ChordTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -221,4 +221,28 @@ class ChordTests: XCTestCase {
"Notes should match expected notes for 1st inversion"
)
}

func testNotesWithMultipleOctaveChordInversion() {
// Arrange
let chord = Chord(.C, type: .majorThirteenth, inversion: 1)
let expectedNotes = [
Note(.E, octave: 4),
Note(.G, octave: 4),
Note(.B, octave: 4),
Note(.D, octave: 5),
Note(.F, octave: 5),
Note(.A, octave: 5),
Note(.C, octave: 6),
]

// Act
let notes = chord.notes(octave: 4)

// Assert
XCTAssertEqual(
notes,
expectedNotes,
"Notes should match expected notes for 1st inversion"
)
}
}

0 comments on commit 95ed13e

Please sign in to comment.