Skip to content

Commit

Permalink
Merge 74e9062 into 1028adf
Browse files Browse the repository at this point in the history
  • Loading branch information
albertms10 committed Mar 7, 2024
2 parents 1028adf + 74e9062 commit 5dae506
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
33 changes: 33 additions & 0 deletions lib/src/scale/scale_pattern.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import 'package:meta/meta.dart' show immutable;
import '../harmony/chord_pattern.dart';
import '../interval/interval.dart';
import '../interval/interval_class.dart';
import '../music.dart';
import '../note/pitch_class.dart';
import '../scalable.dart';
import 'scale.dart';
import 'scale_degree.dart';
Expand Down Expand Up @@ -249,6 +251,37 @@ final class ScalePattern {
return major;
}

/// Creates a new [ScalePattern] from a binary [sequence] in integer form.
///
/// This method and [ScalePattern.toBinary] are inverses of each other.
///
/// Example:
/// ```dart
/// ScalePattern.fromBinary(int.parse('101010110101', radix: 2))
/// == ScalePattern.major
/// ```
factory ScalePattern.fromBinary(int sequence) {
assert(sequence > 0, 'Sequence must be greater than 0');

return Scale([
for (int i = 0; i < chromaticDivisions; i++)
if (sequence & 1 << i != 0) PitchClass(i),
PitchClass.c,
]).pattern;
}

/// Returns the binary representation of this [ScalePattern].
///
/// This method and [ScalePattern.fromBinary] are inverses of each other.
///
/// Example:
/// ```dart
/// ScalePattern.major.toBinary() == int.parse('101010110101', radix: 2)
/// ```
int toBinary() => on(PitchClass.c)
.degrees
.fold(0, (sequence, scalable) => sequence | 1 << scalable.semitones);

/// The length of this [ScalePattern].
///
/// Example:
Expand Down
26 changes: 26 additions & 0 deletions test/src/scale/scale_pattern_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,32 @@ void main() {
});
});

group('.fromBinary()', () {
test('creates a new ScalePattern from a binary sequence', () {
expect(
ScalePattern.fromBinary(int.parse('101010110101', radix: 2)),
ScalePattern.major,
);
expect(
ScalePattern.fromBinary(int.parse('111111111111', radix: 2)),
ScalePattern.chromatic,
);
});
});

group('.toBinary()', () {
test('returns the binary representation of this ScalePattern', () {
expect(
ScalePattern.major.toBinary(),
int.parse('101010110101', radix: 2),
);
expect(
ScalePattern.chromatic.toBinary(),
int.parse('111111111111', radix: 2),
);
});
});

group('.length', () {
test('returns the length of this ScalePattern', () {
expect(ScalePattern.minorPentatonic.length, 5);
Expand Down

0 comments on commit 5dae506

Please sign in to comment.