Skip to content

Instantly share code, notes, and snippets.

@oisdk
Last active August 3, 2017 16:30
Show Gist options
  • Save oisdk/89ad9eca33bff85e3017 to your computer and use it in GitHub Desktop.
Save oisdk/89ad9eca33bff85e3017 to your computer and use it in GitHub Desktop.
enum Sharp: Int { case C = 0, G, D, A, E, B, F }
func sKeyForNote(n: Sharp) -> [Sharp] {
return (0..<n.rawValue)
.map{ n in (n + 6) % 7 }
.flatMap(Sharp.init)
}
enum Flat: Int { case F = 1, B, E, A, D, G }
func fKeyForNote(n: Flat) -> [Flat] {
return (0..<n.rawValue)
.map{ n in (n + 2) % 5 }
.flatMap(Flat.init)
}
enum Note: Int { case C = 0, G, D, A, E, B, FS, F, BF, EF, AF, DF, GF }
enum Scale {
case Sharps([Sharp]), Flats([Flat])
}
extension Note {
var key: Scale {
return
Sharp
.init(rawValue: rawValue)
.map(sKeyForNote)
.map(Scale.Sharps) ??
Flat
.init(rawValue: rawValue - 6)
.map(fKeyForNote)
.map(Scale.Flats)!
}
}
extension Flat: CustomStringConvertible {
var description: String {
switch self {
case .A: return "A♭"
case .B: return "B♭"
case .D: return "D♭"
case .E: return "E♭"
case .F: return "F♭"
case .G: return "G♭"
}
}
}
extension Sharp: CustomStringConvertible {
var description: String {
switch self {
case .A: return "A♯"
case .B: return "C"
case .C: return "C♯"
case .D: return "D♯"
case .E: return "F"
case .F: return "F♯"
case .G: return "G♯"
}
}
}
Note.A.key // Sharps([F♯, C♯, G♯])
Note.B.key // Sharps([F♯, C♯, G♯, D♯, A♯])
Note.C.key // Sharps([])
Note.D.key // Sharps([F♯, C♯])
Note.E.key // Sharps([F♯, C♯, G♯, D♯])
Note.F.key // Flats([B♭])
Note.G.key // Sharps([F♯])
Note.FS.key // Sharps([F♯, C♯, G♯, D♯, A♯, F])
Note.AF.key // Flats([B♭, E♭, A♭])
Note.BF.key // Flats([B♭, E♭])
Note.DF.key // Flats([B♭, E♭, A♭, F♭])
Note.EF.key // Flats([B♭, E♭, A♭])
Note.GF.key // Flats([B♭, E♭, A♭, F♭, B♭])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment