Skip to content

Instantly share code, notes, and snippets.

@bohoffi
Created May 19, 2017 12:04
Show Gist options
  • Save bohoffi/637f3261d7f7d3a65fda8ee15b24f97a to your computer and use it in GitHub Desktop.
Save bohoffi/637f3261d7f7d3a65fda8ee15b24f97a to your computer and use it in GitHub Desktop.
Shows how to calculate a note's position on a fretboard (e.g. guitar or bass) providing the note's key (e.g. 'e/4'), a string tuning and a maximum fret limit.
type Tuning = string[];
// provide the standard 6-string guitar tuning (high to low)
const standardTuning: Tuning = ['E4', 'B3', 'G3', 'D3', 'A2', 'E2'];
// provide a limit for the fretboard length (24 frets => 0 to 24)
const maxFretLimit: number = 24;
interface FretBoardNote {
string: number;
fret: number;
}
interface StringBaseNote {
baseNoteKey: string;
baseNoteKeyScaleIndex: number;
string: number;
}
class Scale {
static getScale(): string[] {
return [1, 2, 3, 4, 5, 6, 7].reduce((scale: string[], octave: number) => {
return scale.concat(Scale.getOctaveScale(octave));
}, ['A0', 'A#0', 'B0']).concat('C8');
}
private static getOctaveScale(octave: number): string[] {
return ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'].map((step: string) => `${step}${octave}`);
}
}
export const getStringFretsByNoteTuning = (noteKey: string, tuning: Tuning, maxFrets: number = 24): FretBoardNote[] => {
if (noteKey.indexOf('/') !== -1) {
noteKey = noteKey.replace('/', '');
}
noteKey = noteKey.toUpperCase();
const scale = Scale.getScale();
const stringBaseNotes: StringBaseNote[] = tuning.map((baseNoteKey: string, index: number) => {
return {baseNoteKey: baseNoteKey, baseNoteKeyScaleIndex: scale.indexOf(baseNoteKey), string: index + 1};
});
const noteKeyScaleIndex = scale.indexOf(noteKey);
const filteredBase = stringBaseNotes
// filter by string tuning base note (index)
.filter((sbnd: StringBaseNote) => sbnd.baseNoteKeyScaleIndex <= noteKeyScaleIndex)
// filter by max fret
.filter((sbnd: StringBaseNote) => scale.slice(sbnd.baseNoteKeyScaleIndex).indexOf(noteKey) <= maxFrets);
return filteredBase.map((fb: StringBaseNote) => {
return {string: fb.string, fret: scale.slice(fb.baseNoteKeyScaleIndex).indexOf(noteKey)};
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment