validate-note
Version:
🎼 Validates a note (scientific pitch notation) and throws errors if needed
74 lines (53 loc) • 2.04 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.validateNote = factory());
}(this, (function () { 'use strict';
var notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
var convertFlatToSharp = (function (letter, signature) {
signature = '#';
letter = notes[notes.indexOf(letter) - 1].charAt(0);
return { signature: signature, letter: letter };
});
var isSignature = function isSignature(value) {
return value === 'b' || value === '#';
};
var isOctave = function isOctave(value) {
return !Number.isNaN(value);
};
var index = (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;
});
return index;
})));