forked from balderdashy/waterline-criteria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·352 lines (295 loc) · 9.57 KB
/
index.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
var _ = require('lodash');
// Find models in data which satisfy the options criteria,
// then return their indices in order
module.exports = function getMatchIndices(data, options) {
// Remember original indices
var origIndexKey = '__origindex';
var matches = _.clone(data);
// Determine origIndex key
_.each(matches, function(model, index) {
model[origIndexKey] = index;
});
// Query and return result set using criteria
matches = applyFilter(matches, options.where);
matches = applySort(matches, options.sort);
matches = applySkip(matches, options.skip);
matches = applyLimit(matches, options.limit);
var matchIndices = _.pluck(matches, origIndexKey);
// Remove original index key which is keeping track of the index in the unsorted data
_.each(data, function(datum) {
delete datum[origIndexKey];
});
return matchIndices;
};
// Run criteria query against data set
function applyFilter(data, criteria) {
if(!data) return data;
else {
return _.filter(data, function(model) {
return matchSet(model, criteria);
});
}
}
function applySort(data, sort) {
if(!sort || !data) return data;
var records = sortData(_.clone(data), sort);
return records;
}
// Sort Function
// Taken From: http://stackoverflow.com/a/4760279/909625
function sortData(data, sortCriteria) {
function dynamicSort(property) {
var sortOrder = 1;
if(property[0] === '-') {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
};
}
function dynamicSortMultiple() {
var props = arguments;
return function (obj1, obj2) {
var i = 0, result = 0, numberOfProperties = props.length;
while(result === 0 && i < numberOfProperties) {
result = dynamicSort(props[i])(obj1, obj2);
i++;
}
return result;
};
}
// build sort criteria in the format ['firstName', '-lastName']
var sortArray = [];
_.each(_.keys(sortCriteria), function(key) {
if(sortCriteria[key] === -1) sortArray.push('-' + key);
else sortArray.push(key);
});
data.sort(dynamicSortMultiple.apply(null, sortArray));
return data;
}
// Grab a key/pair from an object based on array index
function getKeyPair(obj, i) {
var key = Object.keys(obj)[i];
return { key: key, val: obj[key] };
}
// Ignore the first *skip* models
function applySkip(data, skip) {
if(!skip || !data) return data;
else {
return _.rest(data, skip);
}
}
function applyLimit(data, limit) {
if(!limit || !data) return data;
else {
return _.first(data, limit);
}
}
// Match a model against each criterion in a criteria query
function matchSet(model, criteria, parentKey) {
// Null or {} WHERE query always matches everything
if(!criteria || _.isEqual(criteria, {})) return true;
// By default, treat entries as AND
return _.all(criteria, function(criterion, key) {
return matchItem(model, key, criterion, parentKey);
});
}
function matchOr(model, disjuncts) {
var outcome = false;
_.each(disjuncts, function(criteria) {
if(matchSet(model, criteria)) outcome = true;
});
return outcome;
}
function matchAnd(model, conjuncts) {
var outcome = true;
_.each(conjuncts, function(criteria) {
if(!matchSet(model, criteria)) outcome = false;
});
return outcome;
}
function matchLike(model, criteria) {
for(var key in criteria) {
// Return false if no match is found
if (!checkLike(model[key], criteria[key])) return false;
}
return true;
}
function matchNot(model, criteria) {
return !matchSet(model, criteria);
}
function matchItem(model, key, criterion, parentKey) {
// Handle special attr query
if (parentKey) {
if (key === 'equals' || key === '=' || key === 'equal') {
return matchLiteral(model,parentKey,criterion, compare['=']);
}
else if (key === 'not' || key === '!') {
return matchLiteral(model,parentKey,criterion, compare['!']);
}
else if (key === 'greaterThan' || key === '>') {
return matchLiteral(model,parentKey,criterion, compare['>']);
}
else if (key === 'greaterThanOrEqual' || key === '>=') {
return matchLiteral(model,parentKey,criterion, compare['>=']);
}
else if (key === 'lessThan' || key === '<') {
return matchLiteral(model,parentKey,criterion, compare['<']);
}
else if (key === 'lessThanOrEqual' || key === '<=') {
return matchLiteral(model,parentKey,criterion, compare['<=']);
}
else if (key === 'startsWith') return matchLiteral(model,parentKey,criterion, checkStartsWith);
else if (key === 'endsWith') return matchLiteral(model,parentKey,criterion, checkEndsWith);
else if (key === 'contains') return matchLiteral(model,parentKey,criterion, checkContains);
else if (key === 'like') return matchLiteral(model,parentKey,criterion, checkLike);
else throw new Error ('Invalid query syntax!');
}
else if(key.toLowerCase() === 'or') {
return matchOr(model, criterion);
} else if(key.toLowerCase() === 'not') {
return matchNot(model, criterion);
} else if(key.toLowerCase() === 'and') {
return matchAnd(model, criterion);
} else if(key.toLowerCase() === 'like') {
return matchLike(model, criterion);
}
// IN query
else if(_.isArray(criterion)) {
return _.any(criterion, function(val) {
return compare['='](model[key], val);
});
}
// Special attr query
else if (_.isObject(criterion) && validSubAttrCriteria(criterion)) {
// Attribute is being checked in a specific way
return matchSet(model, criterion, key);
}
// Otherwise, try a literal match
else return matchLiteral(model,key,criterion, compare['=']);
}
// Comparison fns
var compare = {
// Equalish
'=' : function (a,b) {
var x = normalizeComparison(a,b);
return x[0] == x[1];
},
// Not equalish
'!' : function (a,b) {
var x = normalizeComparison(a,b);
return x[0] != x[1];
},
'>' : function (a,b) {
var x = normalizeComparison(a,b);
return x[0] > x[1];
},
'>=': function (a,b) {
var x = normalizeComparison(a,b);
return x[0] >= x[1];
},
'<' : function (a,b) {
var x = normalizeComparison(a,b);
return x[0] < x[1];
},
'<=': function (a,b) {
var x = normalizeComparison(a,b);
return x[0] <= x[1];
}
};
// Prepare two values for comparison
function normalizeComparison(a,b) {
if (_.isString(a) && _.isString(b)) {
a = a.toLowerCase();
b = b.toLowerCase();
}
// Stringify for comparisons
a = a.toString();
b = b.toString();
return [a,b];
}
// Return whether this criteria is valid as an object inside of an attribute
function validSubAttrCriteria(c) {
return _.isObject(c) && (
c.not || c.greaterThan || c.lessThan ||
c.greaterThanOrEqual || c.lessThanOrEqual ||
c['<'] || c['<='] || c['!'] || c['>'] || c['>='] ||
c.startsWith || c.endsWith || c.contains || c.like
);
}
// Returns whether this value can be successfully parsed as a finite number
function isNumbery (value) {
return Math.pow(+value, 2) > 0;
}
// matchFn => the function that will be run to check for a match between the two literals
function matchLiteral(model, key, criterion, matchFn) {
// If the criterion are both parsable finite numbers, cast them
if(isNumbery(criterion) && isNumbery(model[key])) {
criterion = +criterion;
model[key] = +model[key];
}
// ensure the key attr exists in model
if(_.isUndefined(model[key])) {
return false;
}
// ensure the key attr matches model attr in model
else if((! matchFn(model[key],criterion))) {
return false;
}
// Otherwise this is a match
return true;
}
function checkStartsWith (value, matchString) {
// console.log("CheCKING startsWith ", value, "against matchString:", matchString, "result:",sqlLikeMatch(value, matchString));
return sqlLikeMatch(value, matchString + '%');
}
function checkEndsWith (value, matchString) {
return sqlLikeMatch(value, '%' + matchString);
}
function checkContains (value, matchString) {
return sqlLikeMatch(value, '%' + matchString + '%');
}
function checkLike (value, matchString) {
// console.log("CheCKING ", value, "against matchString:", matchString, "result:",sqlLikeMatch(value, matchString));
return sqlLikeMatch(value, matchString);
}
function sqlLikeMatch (value,matchString) {
if(_.isRegExp(matchString)) {
// awesome
} else if(_.isString(matchString)) {
// Handle escaped percent (%) signs
matchString = matchString.replace(/%%%/g, '%');
// Escape regex
matchString = escapeRegExp(matchString);
// Replace SQL % match notation with something the ECMA regex parser can handle
matchString = matchString.replace(/([^%]*)%([^%]*)/g, '$1.*$2');
// Case insensitive by default
// TODO: make this overridable
var modifiers = 'i';
matchString = new RegExp('^' + matchString + '$', modifiers);
}
// Unexpected match string!
else {
console.error('matchString:');
console.error(matchString);
throw new Error("Unexpected match string: " + matchString + " Please use a regexp or string.");
}
// Deal with non-strings
if(_.isNumber(value)) value = "" + value;
else if(_.isBoolean(value)) value = value ? "true" : "false";
else if(!_.isString(value)) {
// Ignore objects, arrays, null, and undefined data for now
// (and maybe forever)
return false;
}
// Check that criterion attribute and is at least similar to the model's value for that attr
if(!value.match(matchString)) {
return false;
}
return true;
}
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}