-
Notifications
You must be signed in to change notification settings - Fork 66
/
utils.js
71 lines (54 loc) · 1.23 KB
/
utils.js
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
/*
This operation is O(N)
*/
exports.makeHash = function (list) {
var obj = {};
list.forEach(function(item){
obj[item] = item;
});
return obj;
};
/*
I believe JS' "sort" is based off of merge sort, which is O(log N)
*/
exports.sortList = function(list){
return Array.prototype.slice.apply(list).sort(function(a, b){
return b.length - a.length;
});
};
/*
Excluding the respective time complexities of JS' "split", "splice", or "join",
this operation is O(N) in respect to the word being considered.
The "hash" lookup via 'hasOwnProperty' is O(1).
*/
var findCompound = function(word, list, hash){
var bool = false;
(function recurse (str, frag) {
if (hash[word]){
delete hash[word];
}
if (frag === word){
bool = true;
return;
}
for (var i=1; i<=str.length; i++){
var substr = str.slice(0, i);
if (hash.hasOwnProperty(substr)){
recurse(str.slice(i), frag.concat(substr))
}
}
})(word, "")
return bool;
};
/*
Worst case of this entire operation, is O(N^2),
if the compound word is found at the end of the list.
*/
exports.findCompoundInList = function(list, hash){
for (var i=0; i<list.length; i++){
if ( findCompound(list[i], list, hash) ){
return list[i]
break;
}
}
};