-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTrie.js
More file actions
101 lines (82 loc) · 1.75 KB
/
Trie.js
File metadata and controls
101 lines (82 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
function TrieNode(data)
{
this.data = data || '';
this.fullword = false;
this.children = [];
}
function Trie()
{
this.root = null;
}
Trie.prototype.createroot = function() {
this.root = new TrieNode('.');
};
Trie.prototype.insert = function(str) {
var current = this.root;
for (var i=0; i < str.length; i++)
{
var foundIndex = -1;
var found = current.children.some(
function (element, index)
{
return element.data === str[i] ? (foundIndex = index, true) : false;
});
// If found
if (found)
{
current = current.children[foundIndex];
}
else
{
var newNode = new TrieNode(str[i]);
current.children.push(newNode);
current = newNode;
}
}
current.fullword = true;
};
Trie.prototype.exists = function(str)
{
var current = this.root;
var wordExists = false;
for (var i=0; i < str.length; i++)
{
var foundIndex = -1;
var found = current.children.some(
function (element, index)
{
return element.data === str[i] ? (foundIndex = index, true) : false;
});
// If found
if (found)
{
current = current.children[foundIndex];
}
else
{
current = null;
wordExists = false;
break;
}
}
if (current != null && current.fullword)
{
wordExists = true;
}
return wordExists;
};
var names = ["ann", "anna", "ammy", "emma", "rob", "roger"];
var tree = new Trie();
tree.createroot();
names.forEach(function (item)
{
tree.insert(item);
});
names.forEach(function (item)
{
var str = tree.exists(item) ? " exists " : " does not exist";
console.log(item + " " + str);
});
console.log(tree.exists("annay"));
console.log(tree.exists("Jonathan"));
console.log(tree);