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/2f372184e78d0ddb48fe to your computer and use it in GitHub Desktop.
Save olslash/2f372184e78d0ddb48fe to your computer and use it in GitHub Desktop.
T9 blogpost - 6
Trie.prototype.getSuggestions = function(keyString, suggestionDepth) {
// Traverse the tree based on the key digits in keyString, to find the
// node where relevant words are stored.
var result = [];
var node = this;
for(var i = 0; i < keyString.length; i++) {
var thisKey = keyString[i];
if(!node.children.hasOwnProperty(thisKey)) { break; }
node = node.children[thisKey];
}
// Add all the words to the result.
result = result.concat(node.words.map(function(wordTuple) {
return wordTuple[0];
}));
// If suggestionDepth is > 0, the caller is asking for recommendations of
// words longer than the number of keys pressed.
// We traverse down every possible branch from the point we previously
// arrived at, adding words to the result as we go and stopping when we
// reach the specified depth.
return suggestionDepth > 0 ?
result.concat(getDeeperSuggestions(node, suggestionDepth)) :
result;
// todo: Improvement: If the current string of numbers has no results,
// even if suggestionDepth is 0, we should dig deeper to find some.
function getDeeperSuggestions(root, maxDepth) {
// ...
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment