I was wondering how would one create a javascript function for transposing music chords.
Since I don\'t expect everyone to be a musician here, I\'ll try to explain how i
function transpose(chord, increment)
{
var cycle = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
var el = chord.charAt(0);
if(chord.length > 1 && chord.charAt(1) == '#')
{
el += "#";
}
var ind = cycle.indexOf(el);
var newInd = (ind + increment + cycle.length) % cycle.length;
var newChord = cycle[newInd];
return newChord + chord.substring(el.length);
}
I'll let you figure out the bass part, since it's really just calling the function twice.
Also, you can add the code here before the function for old browsers that don't support indexOf
.
I put a demo on jsFiddle.
EDIT: The issue was with negative modulus. The above will work as long as long as the negative isn't more than the length (e.g. you can't transpose 100 steps down).