-
Notifications
You must be signed in to change notification settings - Fork 1
/
algorithm.js
60 lines (56 loc) · 1.71 KB
/
algorithm.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
exports.traversal = {};
function defaultEnumerator(container, onEachItem) {
var val, i;
if (Array.isArray(container)) {
for (i = 0; i<container.length; ++i) {
val = onEachItem(container[i]);
if (val) return val;
}
} else {
var keys = Object.keys(container);
for (i = 0; i<keys.length; ++i) {
val = onEachItem(container[keys[i]]);
if (val) return val;
}
}
}
function defaultReverseEnumerator(container, onEachItem) {
var val, i;
if (Array.isArray(container)) {
for (i=container.length; i--; ) {
val = onEachItem(container[i]);
if (val) return val;
}
} else {
var keys = Object.keys(container);
for (i = keys.length; i--; ) {
val = onEachItem(container[keys[i]]);
if (val) return val;
}
}
}
/** if onEachItem return true, the function will return and traversal terminates */
exports.bfsTree = function(root, onEachItem, getContainer, forEach) {
forEach = forEach || defaultEnumerator;
getContainer = getContainer || function(e){return e;};
var queue = [root];
while (queue.length > 0) {
var node = queue.shift();
var val = onEachItem(node);
if (val) return val;
var children = getContainer(node);
if (children) forEach(children, function(child) { queue.push(child); });
}
};
exports.dfsTree = function(root, onEachItem, getContainer, forEach) {
forEach = forEach || defaultReverseEnumerator;
getContainer = getContainer || function(e){return e;};
var stack = [root];
while (stack.length > 0) {
var node = stack.pop();
var val = onEachItem(node);
if (val) return val;
var children = getContainer(node);
if (children) forEach(children, function(child) { stack.push(child); });
}
};