Add pp2limit method
[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.removeMatching = function(matchFn) {
17         var newList = [];
18         for (var i in m_list) {
19             var filter = m_list[i];
20             if (matchFn(filter)) {
21                 m_team.log("removeMatching() removing filter " + $.toJSON(filter));
22             } else {
23                 m_team.log("removeMatching() keeping filter " + $.toJSON(filter));
24                 newList.push(filter);
25             }
26         }
27         m_list = newList;
28     };
29
30     that.targetFiltered = function(id) {
31         for (var i = 0; i < m_list.length; i++) {
32             if (m_list[i].id === id ||
33                 m_list[i].id === 'pz:id=' + id) {
34                 return true;
35             }
36         }
37         return false;
38     }
39
40     that.pp2filter = function() {
41         var res = "";
42
43         for (var i in m_list) {
44             var filter = m_list[i];
45             if (filter.id) {
46                 if (res) res += ",";
47                 if (filter.id.match(/^[a-z:]+[=~]/)) {
48                     m_team.log("filter '" + filter.id + "' already begins with SETTING OP");
49                 } else {
50                     filter.id = 'pz:id=' + filter.id;
51                 }
52                 res += filter.id;
53             }
54         }
55
56         return res;
57     }
58
59     that.pp2limit = function(initial) {
60         var res = initial || "";
61
62         for (var i in m_list) {
63             var filter = m_list[i];
64             if (!filter.id) {
65                 if (res) res += ",";
66                 res += filter.field + "=" + filter.value.replace(/[\\|,]/g, '\\$&');
67             }
68         }
69
70         return res;
71     }
72
73
74     return that;
75 }
76
77
78 // Factory function for filters. These can be of several types.
79 function filter(id, name, field, value) {
80     var res;
81
82     if (id) {
83         res = { id: id, name: name };
84     } else {
85         res = { field: field, value: value };
86     }
87
88     return res;
89 }