Skip to content

Instantly share code, notes, and snippets.

@olslash
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olslash/1c1b057264874378d225 to your computer and use it in GitHub Desktop.
Save olslash/1c1b057264874378d225 to your computer and use it in GitHub Desktop.
T9 blogpost - 5
function insertWordIntoListByFrequency(list, word, useFrequency) {
var wordToInsert = [word, useFrequency]; // Store word in a tuple.
var wordsLength = list.length;
if(wordsLength === 0) {
// Handle the case where this node has no words yet
list.push(wordToInsert);
} else {
// Find where to insert this word among others, based on its
// frequency property.
// todo: this could be faster with binary search.
for(var i = 0; i < wordsLength; i++) {
var comparedFrequency = list[i][1];
var insertFrequency = wordToInsert[1];
if(insertFrequency >= comparedFrequency) {
// If i see a word with lower useFrequency than mine,
// insert before it.
list.splice(i, 0, wordToInsert);
return;
}
}
// If we've reached here, we've looked at the last word on this node
// and our word's frequency is less than it.
// Put my word at the end of the list.
list.splice(i + 1, 0, wordToInsert);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment