forked from kriszyp/rql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
js-array.js
427 lines (425 loc) · 11.5 KB
/
js-array.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/*
* An implementation of RQL for JavaScript arrays. For example:
* require("./js-array").query("a=3", {}, [{a:1},{a:3}]) -> [{a:3}]
*
*/
({define:typeof define!="undefined"?define:function(deps, factory){module.exports = factory(exports, require("./parser"), require("./query"), require("./util/each"), require("./util/contains"));}}).
define(["exports", "./parser", "./query", "./util/each", "./util/contains"], function(exports, parser, QUERY, each, contains){
//({define:typeof define!="undefined"?define:function(deps, factory){module.exports = factory(exports, require("./parser"));}}).
//define(["exports", "./parser"], function(exports, parser){
var parseQuery = parser.parseQuery;
var stringify = typeof JSON !== "undefined" && JSON.stringify || function(str){
return '"' + str.replace(/"/g, "\\\"") + '"';
};
var nextId = 1;
exports.jsOperatorMap = {
"eq" : "===",
"ne" : "!==",
"le" : "<=",
"ge" : ">=",
"lt" : "<",
"gt" : ">"
};
exports.operators = {
sort: function(){
var terms = [];
for(var i = 0; i < arguments.length; i++){
var sortAttribute = arguments[i];
var firstChar = sortAttribute.charAt(0);
var term = {attribute: sortAttribute, ascending: true};
if (firstChar == "-" || firstChar == "+") {
if(firstChar == "-"){
term.ascending = false;
}
term.attribute = term.attribute.substring(1);
}
terms.push(term);
}
this.sort(function(a, b){
for (var term, i = 0; term = terms[i]; i++) {
if (a[term.attribute] != b[term.attribute]) {
return term.ascending == a[term.attribute] > b[term.attribute] ? 1 : -1;
}
}
return 0;
});
return this;
},
match: filter(function(value, regex){
return new RegExp(regex).test(value);
}),
"in": filter(function(value, values){
return contains(values, value);
}),
out: filter(function(value, values){
return !contains(values, value);
}),
contains: filter(function(array, value){
if(typeof value == "function"){
return array instanceof Array && each(array, function(v){
return value.call([v]).length;
});
}
else{
return array instanceof Array && contains(array, value);
}
}),
excludes: filter(function(array, value){
if(typeof value == "function"){
return !each(array, function(v){
return value.call([v]).length;
});
}
else{
return !contains(array, value);
}
}),
or: function(){
var items = [];
var idProperty = "__rqlId" + nextId++;
try{
for(var i = 0; i < arguments.length; i++){
var group = arguments[i].call(this);
for(var j = 0, l = group.length;j < l;j++){
var item = group[j];
// use marker to do a union in linear time.
if(!item[idProperty]){
item[idProperty] = true;
items.push(item);
}
}
}
}finally{
// cleanup markers
for(var i = 0, l = items.length; i < l; i++){
delete items[idProperty];
}
}
return items;
},
and: function(){
var items = this;
// TODO: use condition property
for(var i = 0; i < arguments.length; i++){
items = arguments[i].call(items);
}
return items;
},
select: function(){
var args = arguments;
var argc = arguments.length;
return each(this, function(object, emit){
var selected = {};
for(var i = 0; i < argc; i++){
var propertyName = args[i];
var value = evaluateProperty(object, propertyName);
if(typeof value != "undefined"){
selected[propertyName] = value;
}
}
emit(selected);
});
},
unselect: function(){
var args = arguments;
var argc = arguments.length;
return each(this, function(object, emit){
var selected = {};
for (var i in object) if (object.hasOwnProperty(i)) {
selected[i] = object[i];
}
for(var i = 0; i < argc; i++) {
delete selected[args[i]];
}
emit(selected);
});
},
values: function(first){
if(arguments.length == 1){
return each(this, function(object, emit){
emit(object[first]);
});
}
var args = arguments;
var argc = arguments.length;
return each(this, function(object, emit){
var selected = [];
if (argc === 0) {
for(var i in object) if (object.hasOwnProperty(i)) {
selected.push(object[i]);
}
} else {
for(var i = 0; i < argc; i++){
var propertyName = args[i];
selected.push(object[propertyName]);
}
}
emit(selected);
});
},
limit: function(limit, start, maxCount){
var totalCount = this.length;
start = start || 0;
var sliced = this.slice(start, start + limit);
if(maxCount){
sliced.start = start;
sliced.end = start + sliced.length - 1;
sliced.totalCount = Math.min(totalCount, typeof maxCount === "number" ? maxCount : Infinity);
}
return sliced;
},
distinct: function(){
var primitives = {};
var needCleaning = [];
var newResults = this.filter(function(value){
if(value && typeof value == "object"){
if(!value.__found__){
value.__found__ = function(){};// get ignored by JSON serialization
needCleaning.push(value);
return true;
}
}else{
if(!primitives[value]){
primitives[value] = true;
return true;
}
}
});
each(needCleaning, function(object){
delete object.__found__;
});
return newResults;
},
recurse: function(property){
// TODO: this needs to use lazy-array
var newResults = [];
function recurse(value){
if(value instanceof Array){
each(value, recurse);
}else{
newResults.push(value);
if(property){
value = value[property];
if(value && typeof value == "object"){
recurse(value);
}
}else{
for(var i in value){
if(value[i] && typeof value[i] == "object"){
recurse(value[i]);
}
}
}
}
}
recurse(this);
return newResults;
},
aggregate: function(){
var distinctives = [];
var aggregates = [];
for(var i = 0; i < arguments.length; i++){
var arg = arguments[i];
if(typeof arg === "function"){
aggregates.push(arg);
}else{
distinctives.push(arg);
}
}
var distinctObjects = {};
var dl = distinctives.length;
each(this, function(object){
var key = "";
for(var i = 0; i < dl;i++){
key += '/' + object[distinctives[i]];
}
var arrayForKey = distinctObjects[key];
if(!arrayForKey){
arrayForKey = distinctObjects[key] = [];
}
arrayForKey.push(object);
});
var al = aggregates.length;
var newResults = [];
for(var key in distinctObjects){
var arrayForKey = distinctObjects[key];
var newObject = {};
for(var i = 0; i < dl;i++){
var property = distinctives[i];
newObject[property] = arrayForKey[0][property];
}
for(var i = 0; i < al;i++){
var aggregate = aggregates[i];
newObject[i] = aggregate.call(arrayForKey);
}
newResults.push(newObject);
}
return newResults;
},
between: filter(function(value, range){
return value >= range[0] && value < range[1];
}),
sum: reducer(function(a, b){
return a + b;
}),
mean: function(property){
return exports.operators.sum.call(this, property)/this.length;
},
max: reducer(function(a, b){
return Math.max(a, b);
}),
min: reducer(function(a, b){
return Math.min(a, b);
}),
count: function(){
return this.length;
},
first: function(){
return this[0];
},
one: function(){
if(this.length > 1){
throw new TypeError("More than one object found");
}
return this[0];
}
};
exports.filter = filter;
function filter(condition, not){
// convert to boolean right now
var filter = function(property, second){
if(typeof second == "undefined"){
second = property;
property = undefined;
}
var args = arguments;
var filtered = [];
for(var i = 0, length = this.length; i < length; i++){
var item = this[i];
if(condition(evaluateProperty(item, property), second)){
filtered.push(item);
}
}
return filtered;
};
filter.condition = condition;
return filter;
};
function reducer(func){
return function(property){
var result = this[0];
if(property){
result = result && result[property];
for(var i = 1, l = this.length; i < l; i++) {
result = func(result, this[i][property]);
}
}else{
for(var i = 1, l = this.length; i < l; i++) {
result = func(result, this[i]);
}
}
return resul;t
}
}
exports.evaluateProperty = evaluateProperty;
function evaluateProperty(object, property){
if(property instanceof Array){
each(property, function(part){
object = object[decodeURIComponent(part)];
});
return object;
}else if(typeof property == "undefined"){
return object;
}else{
return object[decodeURIComponent(property)];
}
};
var conditionEvaluator = exports.conditionEvaluator = function(condition){
var jsOperator = exports.jsOperatorMap[term.name];
if(jsOperator){
js += "(function(item){return item." + term[0] + jsOperator + "parameters[" + (index -1) + "][1];});";
}
else{
js += "operators['" + term.name + "']";
}
return eval(js);
};
exports.executeQuery = function(query, options, target){
return exports.query(query, options, target);
}
exports.query = query;
exports.missingOperator = function(operator){
throw new Error("Operator " + operator + " is not defined");
}
function query(query, options, target){
options = options || {};
query = parseQuery(query, options.parameters);
function t(){}
t.prototype = exports.operators;
var operators = new t;
// inherit from exports.operators
for(var i in options.operators){
operators[i] = options.operators[i];
}
function op(name){
return operators[name]||exports.missingOperator(name);
}
var parameters = options.parameters || [];
var js = "";
function queryToJS(value){
if(value && typeof value === "object" && !(value instanceof RegExp)){
if(value instanceof Array){
return '[' + each(value, function(value, emit){
emit(queryToJS(value));
}) + ']';
}else{
var jsOperator = exports.jsOperatorMap[value.name];
if(jsOperator){
// item['foo.bar'] ==> (item && item.foo && item.foo.bar && ...)
var path = value.args[0];
var target = value.args[1];
if (typeof target == "undefined"){
var item = "item";
target = path;
}else if(path instanceof Array){
var item = "item";
var escaped = [];
for(var i = 0;i < path.length; i++){
escaped.push(stringify(path[i]));
item +="&&item[" + escaped.join("][") + ']';
}
}else{
var item = "item&&item[" + stringify(path) + "]";
}
// use native Array.prototype.filter if available
var condition = item + jsOperator + queryToJS(target);
if (typeof Array.prototype.filter === 'function') {
return "(function(){return this.filter(function(item){return " + condition + "})})";
//???return "this.filter(function(item){return " + condition + "})";
} else {
return "(function(){var filtered = []; for(var i = 0, length = this.length; i < length; i++){var item = this[i];if(" + condition + "){filtered.push(item);}} return filtered;})";
}
}else{
if (value instanceof Date){
return value.valueOf();
}
return "(function(){return op('" + value.name + "').call(this" +
(value && value.args && value.args.length > 0 ? (", " + each(value.args, function(value, emit){
emit(queryToJS(value));
}).join(",")) : "") +
")})";
}
}
}else{
return typeof value === "string" ? stringify(value) : value;
}
}
var evaluator = eval("(1&&function(target){return " + queryToJS(query) + ".call(target);})");
return target ? evaluator(target) : evaluator;
}
function throwMaxIterations(){
throw new Error("Query has taken too much computation, and the user is not allowed to execute resource-intense queries. Increase maxIterations in your config file to allow longer running non-indexed queries to be processed.");
}
exports.maxIterations = 10000;
return exports;
});