UNPKG

music21j-port

Version:

A toolkit for computer-aided musicology, Javascript version

1,059 lines (867 loc) 27.8 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Music21j Source: music21/common.js</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.spruce.css"> </head> <body> <div class="container-fluid"> <div class="navbar navbar-fixed-top navbar-inverse"> <div class="navbar-inner"> <a class="brand" href="index.html">Music21j</a> <ul class="nav"> <li class="dropdown"> <a href="namespaces.list.html" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b class="caret"></b></a> <ul class="dropdown-menu "> <li> <a href="music21.html">music21</a> </li> <li> <a href="music21.articulations.html">music21.articulations</a> </li> <li> <a href="music21.audioSearch.html">music21.audioSearch</a> </li> <li> <a href="music21.base.html">music21.base</a> </li> <li> <a href="music21.beam.html">music21.beam</a> </li> <li> <a href="music21.chord.html">music21.chord</a> </li> <li> <a href="music21.clef.html">music21.clef</a> </li> <li> <a href="music21.common.html">music21.common</a> </li> <li> <a href="music21.duration.html">music21.duration</a> </li> <li> <a href="music21.dynamics.html">music21.dynamics</a> </li> <li> <a href="music21.expressions.html">music21.expressions</a> </li> <li> <a href="music21.fromPython.html">music21.fromPython</a> </li> <li> <a href="music21.instrument.html">music21.instrument</a> </li> <li> <a href="music21.interval.html">music21.interval</a> </li> <li> <a href="music21.key.html">music21.key</a> </li> <li> <a href="music21.keyboard.html">music21.keyboard</a> </li> <li> <a href="music21.meter.html">music21.meter</a> </li> <li> <a href="music21.miditools.html">music21.miditools</a> </li> <li> <a href="music21.note.html">music21.note</a> </li> <li> <a href="music21.pitch.html">music21.pitch</a> </li> <li> <a href="music21.prebase.html">music21.prebase</a> </li> <li> <a href="music21.renderOptions.html">music21.renderOptions</a> </li> <li> <a href="music21.roman.html">music21.roman</a> </li> <li> <a href="music21.scale.html">music21.scale</a> </li> <li> <a href="music21.sites.html">music21.sites</a> </li> <li> <a href="music21.stream.html">music21.stream</a> </li> <li> <a href="music21.tempo.html">music21.tempo</a> </li> <li> <a href="music21.tie.html">music21.tie</a> </li> <li> <a href="music21.tinyNotation.html">music21.tinyNotation</a> </li> <li> <a href="music21.vfShow.html">music21.vfShow</a> </li> <li> <a href="music21.webmidi.html">music21.webmidi</a> </li> </ul> </li> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a> <ul class="dropdown-menu "> <li> <a href="music21.articulations.Accent.html">music21.articulations.Accent</a> </li> <li> <a href="music21.articulations.Articulation.html">music21.articulations.Articulation</a> </li> <li> <a href="music21.articulations.DynamicArticulation.html">music21.articulations.DynamicArticulation</a> </li> <li> <a href="music21.articulations.LengthArticulation.html">music21.articulations.LengthArticulation</a> </li> <li> <a href="music21.articulations.Marcato.html">music21.articulations.Marcato</a> </li> <li> <a href="music21.articulations.PitchArticulation.html">music21.articulations.PitchArticulation</a> </li> <li> <a href="music21.articulations.Spiccato.html">music21.articulations.Spiccato</a> </li> <li> <a href="music21.articulations.Staccatissimo.html">music21.articulations.Staccatissimo</a> </li> <li> <a href="music21.articulations.Staccato.html">music21.articulations.Staccato</a> </li> <li> <a href="music21.articulations.StrongAccent.html">music21.articulations.StrongAccent</a> </li> <li> <a href="music21.articulations.Tenuto.html">music21.articulations.Tenuto</a> </li> <li> <a href="music21.articulations.TimbreArticulation.html">music21.articulations.TimbreArticulation</a> </li> <li> <a href="music21.base.Music21Object.html">music21.base.Music21Object</a> </li> <li> <a href="music21.beam.Beam.html">music21.beam.Beam</a> </li> <li> <a href="music21.beam.Beams.html">music21.beam.Beams</a> </li> <li> <a href="music21.chord.Chord.html">music21.chord.Chord</a> </li> <li> <a href="music21.clef.AltoClef.html">music21.clef.AltoClef</a> </li> <li> <a href="music21.clef.BassClef.html">music21.clef.BassClef</a> </li> <li> <a href="music21.clef.Clef.html">music21.clef.Clef</a> </li> <li> <a href="music21.clef.MezzoSopranoClef.html">music21.clef.MezzoSopranoClef</a> </li> <li> <a href="music21.clef.PercussionClef.html">music21.clef.PercussionClef</a> </li> <li> <a href="music21.clef.SopranoClef.html">music21.clef.SopranoClef</a> </li> <li> <a href="music21.clef.TenorClef.html">music21.clef.TenorClef</a> </li> <li> <a href="music21.clef.Treble8vaClef.html">music21.clef.Treble8vaClef</a> </li> <li> <a href="music21.clef.Treble8vbClef.html">music21.clef.Treble8vbClef</a> </li> <li> <a href="music21.clef.TrebleClef.html">music21.clef.TrebleClef</a> </li> <li> <a href="music21.duration.Duration.html">music21.duration.Duration</a> </li> <li> <a href="music21.duration.Tuplet.html">music21.duration.Tuplet</a> </li> <li> <a href="music21.dynamics.Dynamic.html">music21.dynamics.Dynamic</a> </li> <li> <a href="music21.expressions.Expression.html">music21.expressions.Expression</a> </li> <li> <a href="music21.expressions.Fermata.html">music21.expressions.Fermata</a> </li> <li> <a href="music21.fromPython.Converter.html">music21.fromPython.Converter</a> </li> <li> <a href="music21.instrument.Instrument.html">music21.instrument.Instrument</a> </li> <li> <a href="music21.interval.ChromaticInterval.html">music21.interval.ChromaticInterval</a> </li> <li> <a href="music21.interval.DiatonicInterval.html">music21.interval.DiatonicInterval</a> </li> <li> <a href="music21.interval.GenericInterval.html">music21.interval.GenericInterval</a> </li> <li> <a href="music21.interval.Interval.html">music21.interval.Interval</a> </li> <li> <a href="music21.key.Key.html">music21.key.Key</a> </li> <li> <a href="music21.key.KeySignature.html">music21.key.KeySignature</a> </li> <li> <a href="music21.keyboard.BlackKey.html">music21.keyboard.BlackKey</a> </li> <li> <a href="music21.keyboard.Key.html">music21.keyboard.Key</a> </li> <li> <a href="music21.keyboard.Keyboard.html">music21.keyboard.Keyboard</a> </li> <li> <a href="music21.keyboard.WhiteKey.html">music21.keyboard.WhiteKey</a> </li> <li> <a href="music21.meter.TimeSignature.html">music21.meter.TimeSignature</a> </li> <li> <a href="music21.miditools.Event.html">music21.miditools.Event</a> </li> <li> <a href="music21.miditools.MidiPlayer.html">music21.miditools.MidiPlayer</a> </li> <li> <a href="music21.note.GeneralNote.html">music21.note.GeneralNote</a> </li> <li> <a href="music21.note.Lyric.html">music21.note.Lyric</a> </li> <li> <a href="music21.note.Note.html">music21.note.Note</a> </li> <li> <a href="music21.note.NotRest.html">music21.note.NotRest</a> </li> <li> <a href="music21.note.Rest.html">music21.note.Rest</a> </li> <li> <a href="music21.pitch.Accidental.html">music21.pitch.Accidental</a> </li> <li> <a href="music21.pitch.Pitch.html">music21.pitch.Pitch</a> </li> <li> <a href="music21.prebase.ProtoM21Object.html">music21.prebase.ProtoM21Object</a> </li> <li> <a href="music21.renderOptions.RenderOptions.html">music21.renderOptions.RenderOptions</a> </li> <li> <a href="music21.roman.RomanNumeral.html">music21.roman.RomanNumeral</a> </li> <li> <a href="music21.stream.Measure.html">music21.stream.Measure</a> </li> <li> <a href="music21.stream.Part.html">music21.stream.Part</a> </li> <li> <a href="music21.stream.Score.html">music21.stream.Score</a> </li> <li> <a href="music21.stream.Stream.html">music21.stream.Stream</a> </li> <li> <a href="music21.stream.Voice.html">music21.stream.Voice</a> </li> <li> <a href="music21.tempo.Metronome.html">music21.tempo.Metronome</a> </li> <li> <a href="music21.tie.Tie.html">music21.tie.Tie</a> </li> <li> <a href="music21.vfShow.Renderer.html">music21.vfShow.Renderer</a> </li> <li> <a href="music21.vfShow.RenderStack.html">music21.vfShow.RenderStack</a> </li> <li> <a href="Notation.html">Notation</a> </li> <li> <a href="Page.html">Page</a> </li> <li> <a href="Recorder.html">Recorder</a> </li> </ul> </li> <li class="dropdown"> <a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a> <ul class="dropdown-menu "> <li> <a href="global.html#getM21attribute">getM21attribute</a> </li> <li> <a href="global.html#layout">layout</a> </li> <li> <a href="global.html#midiNumDiffFromFrequency">midiNumDiffFromFrequency</a> </li> <li> <a href="global.html#recorderWorkerJs">recorderWorkerJs</a> </li> <li> <a href="global.html#unpickler">unpickler</a> </li> <li> <a href="global.html#warnBanner">warnBanner</a> </li> </ul> </li> </ul> </div> </div> <div class="row-fluid"> <div class="span12"> <div id="main"> <h1 class="page-title">Source: music21/common.js</h1> <section> <article> <pre class="sunlight-highlight-javascript linenums">/** * common functions * * @exports music21/common */ /** * functions that are useful everywhere... * * @namespace music21.common * @memberof music21 */ export const common = {}; /** * concept borrowed from Vex.Flow.Merge, though here the source can be undefined; * http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically * recursive parts used in .clone() * * @function music21.common.merge * @param {Object} destination - object to have attributes placed into * @param {Object} source - object to take attributes from. * @memberof music21.common * @returns {Object} destination */ common.merge = function mergeRecursive(destination, source) { if (source === undefined || source === null) { return destination; } for (const p in source) { if (!{}.hasOwnProperty.call(source, p)) { continue; } try { // Property in destination object set; update its value. if (source[p].constructor === Object) { destination[p] = mergeRecursive(destination[p], source[p]); } else { destination[p] = source[p]; } } catch (e) { // Property in destination object not set; create it and set its value. destination[p] = source[p]; } } return destination; }; common.range = function common_range(start, stop, step) { if (step === undefined) { step = 1; } if (stop === undefined) { stop = start; start = 0; } const count = Math.ceil((stop - start) / step); return Array.apply(0, Array(count)).map((e, i) => i * step + start); }; /** * Mix in another class into this class -- a simple form of multiple inheritance. * See articulations.Marcato for an example. * */ common.mixin = function common_mixin(OtherParent, thisClassOrObject) { let proto = Object.getPrototypeOf(OtherParent); const classProto = Object.getPrototypeOf(thisClassOrObject); while (proto) { for (const key in Object.keys(proto)) { if (!{}.hasOwnProperty.call(proto, key)) { continue; } if (!(key in classProto)) { classProto[key] = proto[key]; } } proto = Object.getPrototypeOf(proto); } }; /** * Aggregation -- closer to true multiple inheritance -- prefers last class's functions. See * https://stackoverflow.com/questions/29879267/es6-class-multiple-inheritance * * not currently used... */ common.aggregation = (baseClass, ...mixins) => { class base extends baseClass { constructor(...args) { super(...args); mixins.forEach(mixin => { copyProps(this, new mixin()); }); } } let copyProps = (target, source) => { // this function copies all properties and symbols, filtering out some special ones Object.getOwnPropertyNames(source) .concat(Object.getOwnPropertySymbols(source)) .forEach(prop => { if ( !prop.match( /^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/ ) ) { Object.defineProperty( target, prop, Object.getOwnPropertyDescriptor(source, prop) ); } }); }; mixins.forEach(mixin => { // outside contructor() to allow aggregation(A,B,C).staticFunction() to be called etc. copyProps(base.prototype, mixin.prototype); copyProps(base, mixin); }); return base; }; /** * posMod - return a modulo value that is not negative * * @param {Int} a value * @param {Int} b modulo * @return {Int} a mod b between 0 and b - 1 */ common.posMod = function posMod(a, b) { return (a % b + b) % b; }; /** * * Returns the statistical mode (most commonly appearing element) * in a. * * In case of tie, returns the first element to reach the maximum * number of occurrences. * * @function music21.common.statisticalMode * @param {Array} a - an array to analyze * @returns {Object} element with the highest frequency in a */ common.statisticalMode = function statisticalMode(a) { if (a.length === 0) { return null; } const modeMap = {}; let maxEl = a[0]; let maxCount = 1; for (let i = 0; i &lt; a.length; i++) { const el = a[i]; if (modeMap[el] == null) { modeMap[el] = 0; } modeMap[el] += 1; if (modeMap[el] > maxCount) { maxEl = el; maxCount = modeMap[el]; } } return maxEl; }; /** * fromRoman - Convert a Roman numeral (upper or lower) to an int. * * @param {string} num roman numeral representation of a number * @return {Int} integer value of roman numeral; */ common.fromRoman = function fromRoman(num) { const inputRoman = num.toUpperCase(); const subtractionValues = [1, 10, 100]; const nums = ['M', 'D', 'C', 'L', 'X', 'V', 'I']; const ints = [1000, 500, 100, 50, 10, 5, 1]; const places = []; for (const c of inputRoman) { if (!nums.includes(c)) { throw new Error( 'Value is not a valid roman numeral: ' + inputRoman ); } } for (let i = 0; i &lt; inputRoman.length; i++) { const c = inputRoman[i]; let value = ints[nums.indexOf(c)]; if (i &lt; inputRoman.length - 1) { const nextValue = ints[nums.indexOf(inputRoman[i + 1])]; if (nextValue > value &amp;&amp; subtractionValues.includes(value)) { value *= -1; } } places.push(value); } let summation = 0; for (const n of places) { summation += n; } return summation; }; /** * toRoman - Convert a number from 1 to 3999 to a roman numeral * * @param {Int} num number to convert * @return {string} as roman numeral */ common.toRoman = function toRoman(num) { if (typeof num !== 'number') { throw new Error('expected integer, got ' + typeof num); } if (num &lt; 0 || num > 4000) { throw new Error('Argument must be between 1 and 3999'); } const ints = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; const nums = [ 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I', ]; let result = ''; for (let i = 0; i &lt; ints.length; i++) { const count = Math.floor(num / ints[i]); result += nums[i].repeat(count); num -= ints[i] * count; } return result; }; /** * Creates a DOMObject of an SVG figure using the correct `document.createElementNS` call. * * @function music21.common.makeSVGright * @param {string} [tag='svg'] - a tag, such as 'rect', 'circle', 'text', or 'svg' * @param {Object} [attrs] - attributes to pass to the tag. * @memberof music21.common * @returns {DOMObject} */ common.makeSVGright = function makeSVGright(tag='svg', attrs) { // see http://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element // normal JQuery does not work. if (attrs === undefined) { attrs = {}; } const el = document.createElementNS('http://www.w3.org/2000/svg', tag); for (const k in attrs) { if (!{}.hasOwnProperty.call(attrs, k)) { continue; } el.setAttribute(k, attrs[k]); } return el; }; /** * Take a number such as 32 and return a string such as "nd" * (for "32nd") etc. * * @function music21.common.ordinalAbbreviation * @param {Int} value * @param {Boolean} [plural=false] - make plural (note that "21st" plural is "21st") * @return {string} */ common.ordinalAbbreviation = function ordinalAbbreviation(value, plural) { let post = ''; const valueHundreths = value % 100; if ( valueHundreths === 11 || valueHundreths === 12 || valueHundreths === 13 ) { post = 'th'; } else { const valueMod = value % 10; if (valueMod === 1) { post = 'st'; } else if (valueMod === 2) { post = 'nd'; } else if (valueMod === 3) { post = 'rd'; } else { post = 'th'; } } if (post !== 'st' &amp;&amp; plural) { post += 's'; } return post; }; /** * Find a rational number approximation of this floating point. * * @function music21.common.rationalize * @param {number} ql - number to rationalize * @param {number} [epsilon=0.001] - how close to get * @param {Int} [maxDenominator=50] - maximum denominator * @returns {object|undefined} {'numerator: numerator, 'denominator': denominator} */ common.rationalize = function rationalize(ql, epsilon, maxDenominator) { epsilon = epsilon || 0.001; maxDenominator = maxDenominator || 50; for (let i = 2; i &lt; maxDenominator; i++) { if (Math.abs(ql * i - Math.round(ql * i)) &lt; epsilon) { const numerator = Math.round(ql * i); const denominator = i; return { numerator, denominator }; } } return undefined; }; /** * Change something that could be a string or number and might * end with "px" to a number. * * "400px" -> 400 * * @function music21.common.stripPx * @param {Int|string} str -- string that might have 'px' at the end or not * @returns {Int} a number to use */ common.stripPx = function stripPx(str) { if (typeof str === 'string') { const pxIndex = str.indexOf('px'); str = str.slice(0, pxIndex); return parseInt(str); } else { return str; } }; /** * Find name in the query string (?name=value) and return value. * * @function music21.common.urlParam * @param {string} name - url parameter to find * @returns {string} may be "" if empty. */ common.urlParam = function urlParam(name) { name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]'); const regex = new RegExp('[\\?&amp;]' + name + '=([^&amp;#]*)'); const results = regex.exec(location.search); return results == null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' ')); }; common.arrayEquals = function arrayEquals(a1, a2) { if (a1.length !== a2.length) { return false; } for (let i = 0; i &lt; a1.length; i++) { if (a1[i] instanceof Array &amp;&amp; a2[i] instanceof Array) { if (!arrayEquals(a1[i], a2[i])) { return false; } } else if (a1[i] !== a2[i]) { return false; } } return true; }; const _singletonCounter = {}; _singletonCounter.value = 0; export class SingletonCounter { call() { const post = _singletonCounter.value; _singletonCounter.value += 1; return post; } } common.SingletonCounter = SingletonCounter; /** * runs a callback with either "visible" or "hidden" as the argument anytime the * window or document state changes. * * Depending on the browser, may be called multiple times with the same argument * for a single event. For instance, Safari calls once on losing focus completely * but twice for a tab change. * * @function music21.common.setWindowVisibilityWatcher * @param {function} callback */ common.setWindowVisibilityWatcher = function setWindowVisibilityWatcher( callback ) { let hidden = 'hidden'; // Standards: if (hidden in document) { document.addEventListener('visibilitychange', windowFocusChanged); } else if ('mozHidden' in document) { hidden = 'mozHidden'; document.addEventListener('mozvisibilitychange', windowFocusChanged); } else if ('webkitHidden' in document) { hidden = 'webkitHidden'; document.addEventListener('webkitvisibilitychange', windowFocusChanged); } else if ('msHidden' in document) { hidden = 'msHidden'; document.addEventListener('msvisibilitychange', windowFocusChanged); } else if ('onfocusin' in document) { // IE 9 and lower: document.onfocusin = document.onfocusout = windowFocusChanged; } // Also catch window... -- get two calls for a tab shift, but one for window losing focus window.onpageshow = window.onpagehide = window.onfocus = window.onblur = windowFocusChanged; function windowFocusChanged(evt) { const v = 'visible'; const h = 'hidden'; const evtMap = { focus: v, focusin: v, pageshow: v, blur: h, focusout: h, pagehide: h, }; evt = evt || window.event; let callbackState = ''; if (evt.type in evtMap) { callbackState = evtMap[evt.type]; } else { callbackState = this[hidden] ? 'hidden' : 'visible'; } callback(callbackState, evt); } // set the initial state const initialState = document.visibilityState === 'visible' ? 'focus' : 'blur'; const initialStateEvent = { type: initialState }; windowFocusChanged(initialStateEvent); }; common.urls = { css: '/css', webResources: '/webResources', midiPlayer: '/webResources/midiPlayer', soundfontUrl: '/src/ext/soundfonts/FluidR3_GM/', }; </pre> </article> </section> </div> <div class="clearfix"></div> <footer> <span class="copyright"> Music21j, Copyright © 2013-2018 Michael Scott Cuthbert and cuthbertLab. </span> <br /> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Wed Jul 4th 2018 using the <a href="https://github.com/terryweiss/docstrap">DocStrap template</a>. </span> </footer> </div> <br clear="both"> </div> </div> <!--<script src="scripts/sunlight.js"></script>--> <script src="scripts/docstrap.lib.js"></script> <script src="scripts/bootstrap-dropdown.js"></script> <script src="scripts/toc.js"></script> <script> $( function () { $( "[id*='$']" ).each( function () { var $this = $( this ); $this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) ); } ); $( "#toc" ).toc( { anchorName : function ( i, heading, prefix ) { return $( heading ).attr( "id" ) || ( prefix + i ); }, selectors : "h1,h2,h3,h4", showAndHide : false, scrollTo : "100px" } ); $( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); $( '.dropdown-toggle' ).dropdown(); // $( ".tutorial-section pre, .readme-section pre" ).addClass( "sunlight-highlight-javascript" ).addClass( "linenums" ); $( ".tutorial-section pre, .readme-section pre" ).each( function () { var $this = $( this ); var example = $this.find( "code" ); exampleText = example.html(); var lang = /{@lang (.*?)}/.exec( exampleText ); if ( lang && lang[1] ) { exampleText = exampleText.replace( lang[0], "" ); example.html( exampleText ); lang = lang[1]; } else { lang = "javascript"; } if ( lang ) { $this .addClass( "sunlight-highlight-" + lang ) .addClass( "linenums" ) .html( example.html() ); } } ); Sunlight.highlightAll( { lineNumbers : true, showMenu : true, enableDoclinks : true } ); } ); </script> <!--Navigation and Symbol Display--> <!--Google Analytics--> </body> </html>