Skip to content

Instantly share code, notes, and snippets.

@pavlo-yuriychuk
Created July 20, 2014 15:10
Show Gist options
  • Save pavlo-yuriychuk/8a511f4224cc2ff08e34 to your computer and use it in GitHub Desktop.
Save pavlo-yuriychuk/8a511f4224cc2ff08e34 to your computer and use it in GitHub Desktop.
Trie
var _ = require('lodash');
function Trie() {
this.root = {};
}
Trie.prototype.add = function (string, root) {
var hasTouched = false;
root = root || this.root;
if (string) {
if (root.keys().length > 0) {
_.each(this.root, function (value, key) {
if (string.substr(0, key.lenght) === key) {
hasTouched = true;
if (_.isObject(value)) {
this.add(string.substring(key.lenght), value);
} else if (_.isNumber(value)) {
root[key] = {
_t: new Date().getTime()
};
this.add(string.substring(key.lenght), root[key]);
} else {
hasTouched = false;
}
}
}, this);
if (!hasTouched) {
root[string] = {
_t: new Date().getTime()
};
}
} else {
root[string] = new Date().getTime();
}
}
}
Trie.prototype.has = function (string) {
return false;
}
Trie.prototype.toJSON = function () {
return _.clone(this.root, true);
}
Trie.prototype.toString = function () {
return JSON.stringify(this.toJSON());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment