Add filterSet.visitTargets and filterSet.visitFields methods.
[mkws-moved-to-github.git] / src / mkws-filter.js
1 // Factory function for sets of filters.
2 function filterSet(team) {
3     var m_team = team;
4     var m_list = [];
5
6     var that = {};
7
8     that.list = function() {
9         return m_list;
10     };
11
12     that.add = function(filter) {
13         m_list.push(filter);
14     };
15
16     that.visitTargets = function(callback) {
17         for (var i in m_list) {
18             var filter = m_list[i];
19             if (filter.id) {
20                 callback(filter.id, filter.name);
21             }
22         }
23     };
24
25     that.visitFields = function(callback) {
26         for (var i in m_list) {
27             var filter = m_list[i];
28             if (!filter.id) {
29                 callback(filter.field, filter.value);
30             }
31         }
32     };
33
34     that.removeMatching = function(matchFn) {
35         var newList = [];
36         for (var i in m_list) {
37             var filter = m_list[i];
38             if (matchFn(filter)) {
39                 m_team.log("removeMatching() removing filter " + $.toJSON(filter));
40             } else {
41                 m_team.log("removeMatching() keeping filter " + $.toJSON(filter));
42                 newList.push(filter);
43             }
44         }
45         m_list = newList;
46     };
47
48     that.targetFiltered = function(id) {
49         for (var i = 0; i < m_list.length; i++) {
50             if (m_list[i].id === id ||
51                 m_list[i].id === 'pz:id=' + id) {
52                 return true;
53             }
54         }
55         return false;
56     }
57
58     that.pp2filter = function() {
59         var res = "";
60
61         for (var i in m_list) {
62             var filter = m_list[i];
63             if (filter.id) {
64                 if (res) res += ",";
65                 if (filter.id.match(/^[a-z:]+[=~]/)) {
66                     m_team.log("filter '" + filter.id + "' already begins with SETTING OP");
67                 } else {
68                     filter.id = 'pz:id=' + filter.id;
69                 }
70                 res += filter.id;
71             }
72         }
73
74         return res;
75     }
76
77     that.pp2limit = function(initial) {
78         var res = initial || "";
79
80         for (var i in m_list) {
81             var filter = m_list[i];
82             if (!filter.id) {
83                 if (res) res += ",";
84                 res += filter.field + "=" + filter.value.replace(/[\\|,]/g, '\\$&');
85             }
86         }
87
88         return res;
89     }
90
91
92     return that;
93 }
94
95
96 // Factory function for filters. These can be of several types.
97 function filter(id, name, field, value) {
98     var res;
99
100     if (id) {
101         res = { id: id, name: name };
102     } else {
103         res = { field: field, value: value };
104     }
105
106     return res;
107 }