EMAIL US
team@nowjs.com

IRC
#nowjs on Freenode

MAILING LIST
NowJS

TWITTER
@NowJSTeam

GET ON NPM
npm install now

Countries of the World:

Client Code


 $(document).ready(function() {
  $('#autocomplete').keyup(function autocomplete(event) {
    //checking if the delete key was pressed
    if(event.which == 8) {
      event.preventDefault();
      return;
    }   
    now.getGuess($('#autocomplete').val());
  }); 
});

now.receiveGuess = function(guess) {
  var val = $('#autocomplete').val();
//  var subGuess = guess.substring(val.length);
  if(guess) {
    $('#autocomplete').val(val + guess);
    $('#autocomplete')[0].selectionStart = val.length;
    $('#autocomplete')[0].selectionEnd = guess.length + val.length;
  }
}; 

Server Code (the important stuff)


everyone.now.getGuess = function(val) {
  val = val.toLowerCase();
  var guesses = trie.retrieve(val);
  this.now.receiveGuess(guesses[0]);
};

More Server Code

We use an implementation of a trie for fast autocomplete.


 function Trie(vertex) {
  this.root = vertex;
  this.addWord = function(vertex, word) {
    if(!word.length) {
        return;
    } else {
      vertex.words.push(word);
      if(!(word[0] in vertex.children)) {
        vertex.children[word[0]] = new Vertex(word[0]);
      }
      this.addWord(vertex.children[word[0]], word.substring(1));
      return;
    }
  }

  this.retrieve = function(prefix) {
    var vertex = this.root;
    while(prefix.length) {
      vertex = vertex.children[prefix[0]];
      prefix = prefix.substring(1);
      if(!vertex) {
        return ''; 
      }   
    }   
    return vertex.words;
  }
}

function Vertex(val) {
  this.children = {};
  this.words = [];
  this.val = val;
} 

In our case, the trie is created by loading a list of country names from a text file.


var countries;
var fs = require('fs');
var rootVert = new Vertex('');
var trie = new Trie(rootVert);
fs.readFile('/Users/zachw/Sites/nowjs-examples/countries.txt', function(err, data) {
  countries = data.toString().split('\n');
  for(var i in countries) {
    var country = countries[i].toLowerCase();
    trie.addWord(rootVert, country);
  }
});