Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️ refactor(accidental): extract parsable symbols from parse #216

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 17 additions & 13 deletions lib/src/note/accidental.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ final class Accidental implements Comparable<Accidental> {
static const String _flatSymbol = '♭';
static const String _doubleFlatSymbol = '𝄫';

static int? _semitonesFromSymbol(String symbol) => switch (symbol) {
_doubleSharpSymbol || 'x' => 2,
_sharpSymbol || '#' => 1,
_naturalSymbol || '' => 0,
_flatSymbol || 'b' => -1,
_doubleFlatSymbol => -2,
_ => null,
};

/// Parse [source] as an [Accidental] and return its value.
///
/// If the [source] string does not contain a valid [Accidental], a
Expand All @@ -40,19 +49,14 @@ final class Accidental implements Comparable<Accidental> {
/// ```
factory Accidental.parse(String source) {
// Safely split UTF-16 code units using `runes`.
final semitones = source.runes.fold(
0,
(acc, rune) =>
acc +
switch (String.fromCharCode(rune)) {
_doubleSharpSymbol || 'x' => 2,
_sharpSymbol || '#' => 1,
_naturalSymbol || '' => 0,
_flatSymbol || 'b' => -1,
_doubleFlatSymbol => -2,
_ => throw FormatException('Invalid Accidental', source),
},
);
final semitones = source.runes.fold(0, (acc, rune) {
final symbolSemitones = _semitonesFromSymbol(String.fromCharCode(rune));
if (symbolSemitones == null) {
throw FormatException('Invalid Accidental', source);
}

return acc + symbolSemitones;
});

return Accidental(semitones);
}
Expand Down