Skip to content

Commit

Permalink
refactor(scale_pattern): ♻️ extract static bit-related methods
Browse files Browse the repository at this point in the history
  • Loading branch information
albertms10 committed Mar 26, 2024
1 parent 8005d35 commit 49a3937
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions lib/src/scale/scale_pattern.dart
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,11 @@ final class ScalePattern {
return major;
}

static int _bitAt(int sequence, int index) => sequence & 1 << index;

static int _toBit(int sequence, Scalable<PitchClass> scalable) =>
sequence | 1 << scalable.semitones;

/// Creates a new [ScalePattern] from a binary [sequence] in integer form.
///
/// This method and [ScalePattern.toBinary] are inverses of each other.
Expand All @@ -267,19 +272,17 @@ final class ScalePattern {
factory ScalePattern.fromBinary(int sequence, [int? descendingSequence]) {
assert(sequence > 0, 'Sequence must be greater than 0');

int bitAt(int sequence, int index) => sequence & 1 << index;

final degrees = [
for (int i = 0; i < chromaticDivisions; i++)
if (bitAt(sequence, i) != 0) PitchClass(i),
if (_bitAt(sequence, i) != 0) PitchClass(i),
PitchClass.c,
];
final descendingDegrees = descendingSequence == null
? null
: [
PitchClass.c,
for (int i = chromaticDivisions - 1; i >= 0; i--)
if (bitAt(descendingSequence, i) != 0) PitchClass(i),
if (_bitAt(descendingSequence, i) != 0) PitchClass(i),
];

return Scale(degrees, descendingDegrees).pattern;
Expand All @@ -299,16 +302,13 @@ final class ScalePattern {
/// ScalePattern.melodicMinor.toBinary() == (101010101101.b, 10110101101.b)
/// ```
(int sequence, int? descendingSequence) toBinary() {
int toBit(int sequence, Scalable<PitchClass> scalable) =>
sequence | 1 << scalable.semitones;

final scale = on(PitchClass.c);
final sequence = scale.degrees.fold(0, toBit);
final sequence = scale.degrees.fold(0, _toBit);
final cachedDescending = scale.descendingDegrees;
final descendingSequence =
cachedDescending.reversed.isEnharmonicWith(scale.degrees)
? null
: cachedDescending.fold(0, toBit);
: cachedDescending.fold(0, _toBit);

return (sequence, descendingSequence);
}
Expand Down

0 comments on commit 49a3937

Please sign in to comment.