Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@deanlandolt
Created September 20, 2011 16:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deanlandolt/1229524 to your computer and use it in GitHub Desktop.
Save deanlandolt/1229524 to your computer and use it in GitHub Desktop.
object traversal optimization and indexing
var notes = [{
"note": "A",
"chords": [
{
"chord": "maj7",
"strings": {
"1": 0,
"2": 3,
"3": 2,
"4": 0,
"5": 1,
"6": 2
}
},
{
"chord": "min",
"strings": {
"1": 0,
"2": 3,
"3": 2,
"4": 0,
"5": 1,
"6": 2
}
}
]
},{
"note": "B",
"chords": [
{
"chord": "maj7",
"strings": {
"1": 0,
"2": 3,
"3": 2,
"4": 0,
"5": 1,
"6": 2
}
},
{
"chord": "min",
"strings": {
"1": 0,
"2": 3,
"3": 2,
"4": 0,
"5": 1,
"6": 2
}
}
]
}];
// corrected and optimized original getChord implementation
function getChord( myNotes, theNote, theChord ) {
var i = myNotes.length,
notesObj, theChords, j;
while(i--) {
notesObj = myNotes[i];
if (notesObj.note == theNote) {
theChords = myNotes[i].chords;
var j = theChords.length;
while(j--) {
chordObj = theChords[j]
if (chordObj.chord == theChord) {
return chordObj.strings;
}
}
};
}
}
// build chord/note index
function buildChordIndex( myNotes ) {
var chordIndex = [],
i = myNotes.length,
noteObj, note, chordList, j, chordObj, chord;
while (i--) {
noteObj = myNotes[i];
note = noteObj.note;
chordList = noteObj.chords;
j = chordList.length;
while(j--) {
chordObj = chordList[j];
chord = chordObj.chord;
// assumes standard 12 notes for efficiency, should be no conflict
// but add a separator if necessary
chordIndex[ note + chord ] = [ i, j ];
}
}
return chordIndex;
}
// uses the index instead of traversing
function getChordIndexed( myNotes, myIndex, theNote, theChord ) {
var indexValue = myIndex[theNote + theChord];
return myNotes[ indexValue[0] ].chords[ indexValue[1] ].strings;
}
console.log( getChord( notes, "A", "maj7" ) );
var chordIndex = buildChordIndex(notes);
console.log( getChordIndexed( notes, chordIndex, "A", "maj7" ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment