Skip to content

Instantly share code, notes, and snippets.

@rajivpo
Created August 6, 2020 02:01
Show Gist options
  • Save rajivpo/6ffc2b760c80b5b7d9f99f827aace85f to your computer and use it in GitHub Desktop.
Save rajivpo/6ffc2b760c80b5b7d9f99f827aace85f to your computer and use it in GitHub Desktop.
var fs = require('fs'); // import for index_emails
function Trie() {
this.head = {};
};
// want to make sure we have valid words
Trie.prototype.validate = function(word) {
if ((word === undefined) || (word === null) || (typeof word !== "string")) throw "invalid input";
}
// basic gist is to check if a node exists in a given sequence (prefix) and if it doesn't create a new one
Trie.prototype.add = function(word) {
this.validate(word)
var node = this.head;
for (var i = 0; i < word.length; i++) {
if(!(word[i] in node)) {
node[word[i]] = {};
}
node = node[word[i]]
};
node.isEnd = true
};
// follow the trie from node to node to see if it has it
Trie.prototype.contains = function(word) {
this.validate(word)
var node = this.head;
for (var i = 0; i < word.length; i++) {
if(!(word[i] in node)) {
return false;
}
node = node[word[i]]
};
return node.isEnd === true;
};
// get a list of file paths (not necessarily in a child dir), add them to the trie
// doing this async would be preferable as it's currently blockinig
Trie.prototype.index_emails = function(path) {
var self = this;
fs.readdirSync(path).forEach(function(dirname) {
self.add(dirname)
})
return self;
}
// TODO
Trie.prototype.test = function(word, trie) {
}
export default Trie
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment