Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Worked out the bugs in trie. Have a test suite to prove it ;-)

  • Loading branch information...
commit 690542cac5296703a448c8b7061501916e19f256 1 parent 0f8494d
@matthewmueller authored
Showing with 49 additions and 20 deletions.
  1. +21 −4 tests/find.coffee
  2. +28 −16 trie.js
View
25 tests/find.coffee
@@ -10,11 +10,30 @@ findTest = (trie, query, expected) ->
assert.equal result, expected
tests =
+ "" : false
"A" : "Afghanistan"
"Al" : "Albania"
"B" : false
-
-
+ "C" : false
+ "Cu" : "Cuba"
+ "D" : "Denmark"
+ "Do" : "Dominica"
+ "Dominican" : "Dominican Republic"
+ "Eg" : "Egypt"
+ "Eq" : "Equatorial Guinea"
+ "F" : false
+ "Fi" : "Fiji"
+ "H" : "Haiti"
+ "Ha" : "Haiti"
+ "Hai" : "Haiti"
+ "Hait" : "Haiti"
+ "Haiti" : "Haiti"
+ "K" : "Kazakhstan"
+ "P" : false
+ "Pa" : "Pakistan"
+ "Pap" : "Papua New Guinea"
+ "Pu" : "Puerto Rico"
+ "Y" : "Yemen"
test =
"when searching the trie..." :
@@ -32,8 +51,6 @@ for query, expected of tests
_.extend test["when searching the trie..."], expectedFuncs
-console.log test
-
# Add the test to the batch
suite.addBatch test
View
44 trie.js
@@ -13,6 +13,14 @@
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
}
+ var size = function(obj) {
+ var size = 0, key;
+ for (key in obj) {
+ if (obj.hasOwnProperty(key)) size++;
+ }
+ return size;
+ }
+
trie.traverse = function(word, on_match) {
var T = data,
w = word,
@@ -109,44 +117,46 @@
trie.find = function(query) {
var matched;
var upto = '';
+
+ if(!query) {
+ return false;
+ }
+
trie.traverse(query, function(character, match) {
upto += character;
matched = match;
});
var remaining = query.substr(upto.length, query.length);
- // console.log("Remaining: " + remaining);
- if(!upto) {
+
+ var entered = false;
+
+ if (!upto) {
for(var word in trie.data) {
wordSlice = word.substr(0, query.length);
if(remaining === wordSlice) {
return word;
}
}
- return "";
}
-
-
- var entered = false;
+
for(match in matched) {
entered = true;
- if (remaining == "") {
- return upto + match;
- }
- // console.log("Remaining:", remaining);
- // console.log('up to :', upto);
+
var matchSlice = match.substr(0, remaining.length);
- // console.log("Match Slice: ", matchSlice);
-
if (remaining === matchSlice) {
- return upto + match;
+ if(size(match) === 1) {
+ return false;
+ } else {
+ return upto + match;
+ }
}
}
if(!entered && !remaining) {
return query;
} else {
- return '';
+ return false;
}
}
@@ -160,8 +170,10 @@
return trie;
}
- if(module) {
+ if (typeof module !== 'undefined' && module.exports) {
module.exports = trie;
+ } else {
+ context.trie = trie;
}
})(this);
Please sign in to comment.
Something went wrong with that request. Please try again.