-
Notifications
You must be signed in to change notification settings - Fork 1
/
text-transform-filter.js
53 lines (48 loc) · 1.36 KB
/
text-transform-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
const {Transform} = require('stream');
class TextTransformFilter extends Transform {
constructor(options) {
super({writableObjectMode: true, readableObjectMode: true});
options = options || {};
/* @typedef {Object} FilterOp
* @property {number} index
* @property {string} op
* @property {number} value
*/
this.filterOps = options.filterOps || [];
}
_transform(data, encoding, callback) {
if (this.filterOps.length > 0) {
const filteredItems = data.items.filter((item) => {
const transform = item.transform;
return this.filterOps.every((op) => {
return this.compare(transform, op);
});
});
this.push(Object.assign({}, data, {items: filteredItems}));
} else {
this.push(data);
}
callback();
}
compare(transform, comparator) {
switch (comparator.op) {
case '<':
return transform[comparator.index] < comparator.value;
break;
case '<=':
return transform[comparator.index] <= comparator.value;
break;
case '>':
return transform[comparator.index] > comparator.value;
break;
case '>=':
return transform[comparator.index] >= comparator.value;
break;
default:
throw new Exception(`invalid operator ${comparator.op}`);
}
}
}
module.exports = {
TextTransformFilter
};