JSFiddle - React, Tailwind, and code Playground

by Job van der Zwan

JavaScript

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});