Skip to content

Commit

Permalink
Merge pull request #16 from kilmc/fix-get-key
Browse files Browse the repository at this point in the history
[fix] Make getKey more resilliant to unknown keys
  • Loading branch information
kilmc authored Sep 21, 2023
2 parents b8ddb06 + e0e1d72 commit 7f0fcb3
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/clean-tips-clap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@kilmc/music-fns": patch
---

Make getKey more resilliant
4 changes: 4 additions & 0 deletions src/keys/getKey.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,8 @@ describe('getKey', () => {
expect(result?.minor.notes).toEqual(minorNotes);
expect(result?.chords.map((chord) => chord.name)).toEqual(chordNames);
});

it('handles unknown keys', () => {
expect(getKey('X dorian')).toBe(undefined);
});
});
3 changes: 3 additions & 0 deletions src/keys/getKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ type KeyInfo = {

export const getKey = (key: string): KeyInfo | undefined => {
const [pitch, mode] = extractScaleName(key) || [];

if (pitch === undefined && mode === undefined) return undefined;

const friendlyModeName = getFriendlyModeName(mode);
if (mode === undefined || pitch === undefined) return undefined;

Expand Down
7 changes: 3 additions & 4 deletions src/scale/extractName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@ export const extractScaleName = (
): [string, TScaleType | Mode] | undefined => {
const regex = new RegExp(/([A-G](?:b|#)?) (.*)/);
const [pitchClass, scale] = name.match(regex)?.slice(1, 3) || [];
const normalScale = scale.toLowerCase().replaceAll(' ', '-');

if ((pitchClass || scale) === undefined) {
console.log('Not a scale');
}
if ((pitchClass || scale) === undefined) return undefined;

const normalScale = scale.toLowerCase().replaceAll(' ', '-');

if (normalScale === 'ionian') {
return [pitchClass, 'major'];
Expand Down

0 comments on commit 7f0fcb3

Please sign in to comment.