-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathProblem4.js
More file actions
52 lines (44 loc) · 1.38 KB
/
Problem4.js
File metadata and controls
52 lines (44 loc) · 1.38 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
/*
T9 Autocomplete
Convert a prefix into a list of words starting with that prefix
*/
var ds = require('./ds');
var Trie = ds.Trie;
var insertWord = function (trie, word) {
// TODO: Implement
};
var getWordsFromPrefix = function (trie, prefix) {
// TODO: Implement
};
/////////////////////////////////////////////////////////////
// HELPERS
/////////////////////////////////////////////////////////////
// Takes the Array of words and adds each one into a trie
var insertWords = function (words) {
return words.reduce(function (trie, word) {
insertWord(trie, word);
return trie;
}, new Trie(null) /* ROOT OF TRIE */);
};
var getStartNode = function (trie, prefix) {
// Returns the trie that the prefix ends on, not the next one.
if (prefix.length === 1) {
return trie;
}
if (trie.children[prefix[0]]) {
return getStartNode(trie.children[prefix[0]], prefix.slice(1));
} else {
// If no corresponding children, just return the trie
return trie;
}
};
/////////////////////////////////////////////////////////////
// TESTS
/////////////////////////////////////////////////////////////
var dict = require('./test/problem4cases').dict;
var prefixes = require('./test/problem4cases').prefixes;
var loadedDict = insertWords(dict);
prefixes.forEach(function (prefix) {
console.log('Prefix', prefix);
console.log(getWordsFromPrefix(loadedDict, prefix));
});