UNPKG

validate-chord

Version:

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

2 lines (1 loc) • 1.64 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.validateChord=e()}(this,function(){"use strict";var t=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],e=function(e,r){return r="#",e=t[t.indexOf(e)-1].charAt(0),{signature:r,letter:e}},r=function(t){return"b"===t||"#"===t},n=function(t){return!Number.isNaN(t)},o=function(t){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=o.maxOctave,a=void 0===i?8:i,c=o.flatToSharp,d=void 0!==c&&c,f=o.octave,u=void 0!==f&&f,v=u?"1":"0,1",s=new RegExp("^(?!([EB]#)|([CF]b))([A-G]{1})([#|b]{0,1})([0-"+a+"]{"+v+"})$","ig");if(!s.test(t))throw new Error("'"+t+"' is not a valid note");for(var l=t.charAt(0),m="",h=void 0,p=1;p<t.length;p++){var g=t[p];r(g)&&(m=g),n(g)&&(h=parseInt(g))}if("b"===m&&d){var b=e(l,m);m=b.signature,l=b.letter}var j={letter:l,signature:m,octave:h};return Object.keys(j).forEach(function(t){return!j[t]&&delete j[t]}),j},i={"":"major",major:"major",maj:"major",m:"minor",min:"minor",minor:"minor",aug:"augmented",dim:"diminished"},a=function(t){return isNaN(t.charAt(1))?t.slice(0,3):t.slice(0,2)},c=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.maxOctave,n=void 0===r?8:r,c=e.flatToSharp,d=void 0!==c&&c;if("string"!=typeof t)throw new Error("'"+t+"' is not a valid chord");var f=a(t),u=o(f,{maxOctave:n,flatToSharp:d,octave:!0}),v=i[t.split(f)[1].toLowerCase()];if(!v)throw new Error("'"+t.split(f)[1]+"' is not a valid chord type");return Object.keys(u).forEach(function(t){return!u[t]&&delete u[t]}),{note:u,type:v}};return c});