-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
161 lines (129 loc) · 2.45 KB
/
index.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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
/*!
*
* Traverse-object
*
* MIT License.
*
*/
/**
* Module dependencies.
*/
var type = require('type'),
indexof = require('indexof');
/**
* Traverse.
*/
function Traverse() {}
/**
* Proto.
*/
var proto = Traverse.prototype;
/**
* Depth-first iterator.
*/
proto.depth = iterator('depth');
/**
* Breadth-first iterator.
*/
proto.breadth = iterator('breadth');
/**
* Filter bind.
*
* @param {Function} filter
* @return {Object}
* @api public
*/
proto.filter = function(filter) {
if (this.filters) {
this.filters.push(filter);
return this;
}
else {
var traverse = new Traverse();
traverse.filters = [filter];
return traverse;
}
};
/**
* Exports.
*/
exports = module.exports = new Traverse();
exports.Traverse = Traverse;
/**
* Iterator strategy.
*
* @param {String} method
* @api private
*/
function iterator(method) {
// determine strategy type
var isBreadth = 'breadth' == method;
/**
* Iterator runner.
*
* @param {Object} target
* @param {Function} fn
* @param {Function} [filter]
* @api public
*/
return function runner(target, fn, filter, visited, queue, flush) {
if (isBreadth && !queue) {
queue = [];
flush = true;
}
var filters = this.filters;
if (filters) {
if (filter) filters = filters.concat([filter]);
filter = all(filters);
}
else {
filter = filter || pass;
}
visited = visited || [];
visited.push(target);
for (var key in target) {
var item = target[key];
if (filter(key, item)) {
fn.call(target, key, item);
if ('object' == type(item)
&& !~indexof(visited, item)
) {
if (isBreadth) queue.push(item);
else runner.call(this, item, fn, null, visited);
}
}
}
if (flush && queue) {
var c = queue.slice(),
len = c.length,
last = len - 1;
queue = [];
for (var i = 0; i < len; i++) {
runner.call(this, c[i], fn, null, visited, queue, last == i);
}
}
};
}
/**
* All filters factory.
*
* @param {Array} filters
* @return {Function}
* @api private
*/
function all(filters) {
return function filter(key, item) {
for (var i = 0; i < filters.length; i++) {
var result = filters[i](key, item);
if (!result) return false;
}
return true;
};
}
/**
* Pass filter.
*
* @return {Boolean}
* @api private
*/
function pass() { return true; }