Skip to content

Commit 16fa904

Browse files
committed
Refactor redundant logic in MiniApps/Arpeggiator
- rename variable `arpUp` to `isArpDescending` - Simplified `fireTimer()` - Simplified `noteOff(pitch:)`
1 parent 7579888 commit 16fa904

File tree

1 file changed

+18
-36
lines changed

1 file changed

+18
-36
lines changed

Cookbook/CookbookCommon/Sources/CookbookCommon/Recipes/MiniApps/Arpeggiator.swift

Lines changed: 18 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ class ArpeggiatorConductor: ObservableObject, HasAudioEngine {
1414
var midiCallback: CallbackInstrument!
1515

1616
var heldNotes = [Int]()
17-
var arpUp = false
17+
var isArpDescending = false
1818
var currentNote = 0
1919
var sequencerNoteLength = 1.0
2020

@@ -41,50 +41,32 @@ class ArpeggiatorConductor: ObservableObject, HasAudioEngine {
4141
for i in 0...127 {
4242
self.instrument.stop(noteNumber: MIDINoteNumber(i), channel: 0)
4343
}
44+
4445
if self.heldNotes.count < 1 {
4546
return
4647
}
4748

48-
//UP
49-
if !arpUp {
50-
let tempArray = heldNotes
51-
var arrayValue = 0
52-
if tempArray.max() != currentNote {
53-
arrayValue = tempArray.sorted().first(where: { $0 > currentNote }) ?? tempArray.min()!
54-
currentNote = arrayValue
55-
}else{
56-
arpUp = true
57-
arrayValue = tempArray.sorted().last(where: { $0 < currentNote }) ?? tempArray.max()!
58-
currentNote = arrayValue
59-
}
60-
61-
}else{
62-
//DOWN
63-
let tempArray = heldNotes
64-
var arrayValue = 0
65-
if tempArray.min() != currentNote {
66-
arrayValue = tempArray.sorted().last(where: { $0 < currentNote }) ?? tempArray.max()!
67-
currentNote = arrayValue
68-
}else{
69-
arpUp = false
70-
arrayValue = tempArray.sorted().first(where: { $0 > currentNote }) ?? tempArray.min()!
71-
currentNote = arrayValue
72-
}
49+
if !isArpDescending {
50+
if heldNotes.max() != currentNote {
51+
currentNote = heldNotes.filter { $0 > currentNote }.min() ?? heldNotes.min()!
52+
} else {
53+
isArpDescending = true
54+
currentNote = heldNotes.filter { $0 < currentNote }.max() ?? heldNotes.max()!
55+
}
56+
} else {
57+
if heldNotes.min() != currentNote {
58+
currentNote = heldNotes.filter { $0 < currentNote }.max() ?? heldNotes.max()!
59+
} else {
60+
isArpDescending = false
61+
currentNote = heldNotes.filter { $0 > currentNote }.min() ?? heldNotes.min()!
62+
}
7363
}
64+
7465
instrument.play(noteNumber: MIDINoteNumber(currentNote), velocity: 120, channel: 0)
7566
}
7667

7768
func noteOff(pitch: Pitch) {
78-
let mynote = pitch.intValue
79-
80-
//remove notes from an array
81-
for i in heldNotes {
82-
if i == mynote {
83-
heldNotes = heldNotes.filter {
84-
$0 != mynote
85-
}
86-
}
87-
}
69+
heldNotes = heldNotes.filter { $0 != pitch.intValue }
8870
}
8971

9072
init() {

0 commit comments

Comments
 (0)