validate-note
Version:
🎼 Validates a note (scientific pitch notation) and throws errors if needed
55 lines (41 loc) • 1.55 kB
JavaScript
import convertFlatToSharp from './lib/convertFlatToSharp';
var isSignature = function isSignature(value) {
return value === 'b' || value === '#';
};
var isOctave = function isOctave(value) {
return !Number.isNaN(value);
};
export default (function (note) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _ref$maxOctave = _ref.maxOctave;
var maxOctave = _ref$maxOctave === undefined ? 8 : _ref$maxOctave;
var _ref$flatToSharp = _ref.flatToSharp;
var flatToSharp = _ref$flatToSharp === undefined ? false : _ref$flatToSharp;
var _ref$octave = _ref.octave;
var rOct = _ref$octave === undefined ? false : _ref$octave;
var oct = rOct ? '1' : '0,1';
var 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');
var letter = note.charAt(0);
var signature = '';
var octave = void 0;
for (var i = 1; i < note.length; i++) {
var part = note[i];
if (isSignature(part)) signature = part;
if (isOctave(part)) octave = parseInt(part);
}
if (signature === 'b' && flatToSharp) {
var _convertFlatToSharp = convertFlatToSharp(letter, signature);
signature = _convertFlatToSharp.signature;
letter = _convertFlatToSharp.letter;
}
var obj = {
letter: letter,
signature: signature,
octave: octave
};
Object.keys(obj).forEach(function (key) {
return !obj[key] && delete obj[key];
});
return obj;
});