words = ['foo', 'bar', 'baz', 'bee'];
var charCodeArray = [[]];
// Data structure for a node:
// [ [array of indices], < char, node, char, node, ... >]
for (var i = 0; i < words.length; i++) {
var word = words[i];
var node = charCodeArray;
nextchar:
for (var j = 0; j < word.length; j++) {
var char = word.charCodeAt(j);
for (var k = 1; k < node.length; k += 2){
if (node[k] == char) {
node = node[k+1];
node[0].push(i);
continue nextchar;
}
}
var newNode = [[i]];
node.push(char);
node.push(newNode);
node = newNode;
}
}
function findMatches(prefix, trie, list){
var node = trie, retList = [];
nextSearchChar:
for (var i = 0; i < prefix.length; i++){
var char = prefix.charCodeAt(i);
for (var j = 1; j < node.length; j += 2){
if (node[j] == char){
node = node[j+1]
continue nextSearchChar;
}
}
// we only come here if there is
// no matching char in the trie
return retList;
}
var indices = node[0];
for (var i = 0; i < indices.length; i++){
retList.push(list[indices[i]]);
}
return retList;
}
var testMatches1 = findMatches('ba', charCodeArray, words);
var testMatches2 = findMatches('fo', charCodeArray, words);
console.log({charCodeArray, testMatches1, testMatches2});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.