-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfilter.js
63 lines (49 loc) · 1.31 KB
/
filter.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
let filters = {};
class Filter {
static tokenize (signature) {
if (typeof signature !== 'string') {
throw new Error('Cannot tokenize non-string filter signature');
}
let [head, ...rest] = signature.split(':');
rest = rest.join(':');
rest = rest.length === 0 ? [] : rest.split(',');
return [head, ...rest];
}
static get (signature) {
const signatureType = typeof signature;
if (signatureType === 'function') {
return signature;
}
if (signatureType === 'string') {
signature = Filter.tokenize(signature);
}
if (!Array.isArray(signature)) {
throw new Error(`Unknown filter by ${signatureType}`);
}
const [fn, ...args] = signature;
if (fn in filters === false) {
try {
filters[fn] = require('./filters/' + fn);
} catch (err) {
filters[fn] = null;
}
}
if (!filters[fn]) {
let normalizedSignature = 'unknown';
try {
normalizedSignature = JSON.stringify(signature);
} catch (err) {
// noop
}
throw new Error(`Filter ${fn} not found <${signatureType}(${normalizedSignature})>`);
}
return filters[fn](...args);
}
static put (name, filter) {
filters[name] = filter;
}
static reset () {
filters = {};
}
}
module.exports = Filter;