-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
41 lines (38 loc) · 938 Bytes
/
index.js
File metadata and controls
41 lines (38 loc) · 938 Bytes
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
const walk = require('./lib/walk');
const walkSync = require('./lib/walkSync');
/**
* 转义正则
*
* @param {string} str
* @returns
*/
function escapeRegexp(str) {
return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
}
/**
* 遍历目录
*
* @param {function} walker
*/
function wrap(walker) {
/**
* @param {string} path
* @param {RegExp|string|string[]} [pattern=/./]
* @param {number} [depth=0]
*/
return (path, pattern = /./, depth = 0) => {
if (pattern instanceof RegExp) {
// nothing to do
} else if (typeof pattern === 'string') {
pattern = RegExp(`${escapeRegexp(pattern)}$`, 'i');
} else if (pattern instanceof Array) {
pattern = `(?:${pattern.map(escapeRegexp).join('|')})$`;
pattern = RegExp(pattern, 'i');
} else {
pattern = /./;
}
return walker(path, pattern, depth);
};
}
module.exports = wrap(walk);
module.exports.sync = wrap(walkSync);