UNPKG

validate-note

Version:

🎼 Validates a note (scientific pitch notation) and throws errors if needed

51 lines (36 loc) • 1.13 kB
// @flow import convertFlatToSharp from './lib/convertFlatToSharp'; type options = { maxOctave: number, flatToSharp: boolean, octave: boolean }; const isSignature = value => (value === `b` || value === `#`); const isOctave = value => !Number.isNaN(value); export default (note: string, { maxOctave = 8, flatToSharp = false, octave: rOct = false }: options = {}): Object => { const oct = rOct ? `1` : `0,1`; const regex = new RegExp(`^(?!([EB]#)|([CF]b))([A-G]{1})([#|b]{0,1})([0-${maxOctave}]{${oct}})$`, `ig`); if (!regex.test(note)) throw new Error(`'${note}' is not a valid note`); let letter: string = note.charAt(0); let signature: string = ``; let octave: number; for (let i = 1;i < note.length;i ++) { const part: any = note[i]; if (isSignature(part)) signature = part; if (isOctave(part)) octave = parseInt(part); } if (signature === `b` && flatToSharp) { ({signature, letter} = convertFlatToSharp(letter, signature)); } const obj = { letter, signature, octave }; Object.keys(obj).forEach(key => (!obj[key]) && delete obj[key]); return obj; };