-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgasql.gs
1403 lines (1198 loc) · 37.3 KB
/
gasql.gs
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
JSplyr = Object.create(null);
/**
* CConstructor for table objects
*
* The table has a table attribute with is an object with field names as keys.
* The values are arrays containing the rows of each column.
*
* @param {Object} table The object that will be the table propertt.
* @returns {Table} The table with methods to work with instances of itself.
*/
JSplyr.Table = function(table) {
this.table = table;
};
/**
* Table Wrapper for Objcts
*
* @param {Object} table The object that will be the table propertt.
* @returns {Table} The table with methods to work with instances of itself.
*/
JSplyr.createTable = function(table) {
var output = new JSplyr.Table(table)
return output;
};
/**
* Creates a table from a two dimensional array.
*
* The 2d array is an array of arrays.
* Each element of the outer array is a row.
* Each element of the inner arrays is a column in that row.
*
* @param {Object[][]} data The 2d array to be converted into a table.
* @return {Table} The input as a table instance.
*/
JSplyr.createTableFromMatrix = function(data) {
function verify2dArray() {
var errorMessage = "Data is not a 2 dimensional Array"
if (!Array.isArray(data)) {throw errorMessage;}
data.map(function (x) {if (!Array.isArray(x)) {throw errorMessage;}});
}
function makeTable() {
var output = {};
function populateColumn(field, col) {
function extractColumn(row) {return row[col];}
function indexGreater0(_, i) {return i > 0;};
output[field] = data.filter(indexGreater0).map(extractColumn);
}
data[0].forEach(populateColumn);
return output;
}
return JSplyr.createTable(makeTable());
};
/**
* Creates a table from an array of dictionaries
*
* @param {Object[]} data The Array of dictionaries
* @return {Table} The input as a table instance.
*/
JSplyr.createTableFromObjects = function(data) {
if (!Array.isArray(data) || data.length < 1) {
throw "Must have a least on dict in Array to construct a table"
}
var fields = Object.keys(data[0]);
var rawTable = {};
fields.forEach(function(field) {rawTable[field] = [];});
data.forEach(function(row) {
fields.forEach(function(field) {
rawTable[field].push(row[field]);
})
})
return JSplyr.createTable(rawTable);
};
/**
* verifies whether an Object is a certain JSplyr object.
*
* @param {Object} object The object to be checked
* @param {string} name The name of the object to be checked. Blank checks
* if it has a _JSplyrName property (lame)
* @return {logical} Whether the object passes the test.
*/
JSplyr.isObject = function(object, name) {
if (!name) {return object.hasOwnProperty("_JSplyrName");}
return object._JSplyrName === name;
};
/**
* An alias object that can be used instead of field names in selections.
*
* @param {Object} field The field of the table to be used.
* @param {string} alias The Name the field will have in the selection.
*
* @return {Object} Returns a field-alias object.
*/
JSplyr.as = function(field, alias) {
return {_JSplyrName: "alias", field: field, alias: alias};
};
/**
* Allows for scalar functions within records of a table.
* Note that while this is a scalar application of a function it is possible
* to use it as an aggregation when using group_by().
*
* @param {function} fun The function to be evaluated per row.
* @param {string} alias The alias of the function value.
* @param {...} ... Any arguments passed to the function.
*/
JSplyr.fun = function(fun, alias) {
if (typeof(fun) !== "function") {
throw "First argument must be a function!";
}
var args = JSplyr.objectToArray(arguments);
args.splice(0,2);
return {_JSplyrName: "function", fun: fun, alias: alias, args: args};
};
/**
* Gets the i-th values of each array suuplied
*
* @param {Int} index The position (0-based)
* @param {<*[]>] optional arrays
* @param {*[]} One array
*/
JSplyr.multiSubscript = function(index) {
var args = JSplyr.objectToArray(arguments).slice(1);
function getAtPosition(a) {return a[index];};
return args.map(getAtPosition);
};
/**
* Whether a and b are both true
* can be used in functional programs as a reducer.
*
* @param {Boolean} a
* @param {Boolean} b
* @return {Boolean}
*/
JSplyr.both = function(a, b) {
return a && b;
};
/**
* Whether at least one of a or b is true
* can be used in functional programs as a reducer.
*
* @param {Boolean} a
* @param {Boolean} b
* @return {Boolean}
*/
JSplyr.either = function(a, b) {
return a || b;
};
/**
* Whether all elements of a vector are true.
*
* @param {Boolean[]} v
* @return {Boolean}
*/
JSplyr.all = function(v) {
return v.reduce(JSplyr.both, {}, true); // No idea why this needs {}...
};
/**
* Whether any element of a vector is true.
*
* @param {Boolean[]} v
* @return {Boolean}
*/
JSplyr.any = function(v) {
return v.reduce(JSplyr.either, undefined, false); // But this needs undefined?
};
/**
* Logical and applied to a list of arrays.
*
* k Arrays of length n will return an array of length n where each row is the
* logical and of row i of n for each column j of k.
*
* @param {Array} ... 0 or more arrays.
* @return {Array} The resulting vector of true/false values.
*/
JSplyr.arrayAnd = function() {
var args = JSplyr.objectToArray(arguments);
function getWholeRow(_, i) {
return JSplyr.multiSubscript.apply({},[i].concat(args));
};
if (args.length === 0) {return undefined;}
return args[0].map(getWholeRow).map(JSplyr.all);
};
/**
* Logical or applied to a list of arrays.
*
* k Arrays of length n will return an array of length n where each row is the
* logical or of row i of n for each column j of k.
*
* @param {Array} ... 0 or more arrays.
* @return {Array} The resulting vector of true/false values.
*/
JSplyr.arrayOr = function() {
var args = JSplyr.objectToArray(arguments);
function getWholeRow(_, i) {
return JSplyr.multiSubscript.apply({},[i].concat(args));
};
if (args.length === 0) {return undefined;}
return args[0].map(getWholeRow).map(JSplyr.any);
};
/**
* The negation of an array of boolean values.
*
* @param {Array} x The array to be negated.
* @return {Array} an array of the negated values of x.
*/
JSplyr.arrayNot = function(x) {
return x.map(function(x) {return !x;});
};
/**
* Extracts element out of an Object into an array
*
* @param {Object} object The object to be parsed
* @return {Array} The Values of the object in an array.
*/
JSplyr.objectToArray = function(object) {
var output = [];
return Object.keys(object).map(function(key) {return object[key];});
};
/**
* Return a comparison object
*
* @param {Object} lop The left operand. Can be a field name or a literal.
* @param {Object} op The operand.
* @param {Object} rop The right operand. Can be a field name or a literal.
* @param {...} ... Opt arguments supplied to the function. Field or literal.
* @return {Object} An object containing the three arguments.
*/
JSplyr.comp = function(lop, op, rop) {
var args = JSplyr.objectToArray(arguments);
var optArgs = args.slice(3, args.length);
return {_JSplyrName: "comparison", lop: lop, op: op, rop: rop, args: optArgs};
};
/**
* Returns a logical combination of type and
*
* @param {comparison} ... A series of comparisons
* @return {logical combination} A logical and combinations
*/
JSplyr.and = function() {
var args = JSplyr.objectToArray(arguments);
return {_JSplyrName: "logical combination", type: "and", args: args};
};
/**
* Returns a logical combination of type or
*
* @param {comparison} ... A series of comparisons
* @return {logical combination} A logical or combinations
*/
JSplyr.or = function() {
var args = JSplyr.objectToArray(arguments);
return {_JSplyrName: "logical combination", type: "or", args: args};
};
/**
* Returns the logical complement of a comparison
*
* @param {comparison} comp The logical comparison to be negated/
* @return {logical combination} A logical negation
*/
JSplyr.not = function(comp) {
return {_JSplyrName: "logical combination", type: "not", args: [comp]};
};
/**
* Recursively evaluates logical combinations
*
* @param {logical combination} comb the logical combination to be evaluated.
* @param {table} target the table on which the logical combination happens.
*/
JSplyr.evaluateLogicalCombination = function(comb, target) {
if (!JSplyr.isObject(comb, "logical combination")) {"Not a combination!";}
var logicalArrays = comb.args.map(function(expr) {
if (JSplyr.isObject(expr, "logical combination")) {
return JSplyr.evaluateLogicalCombination(expr, target);
} else {
return target.is(expr);
}
});
if (comb.type === "and") {
return JSplyr.arrayAnd.apply(target, logicalArrays);
} if (comb.type === "or") {
return JSplyr.arrayOr.apply(target, logicalArrays);
} if (comb.type === "not") {
return JSplyr.arrayNot.apply(target, logicalArrays);
}
};
/**
* @param {Object} field a field name or fun instance.
* @return {Object} an order orbject (ascending type)
*/
JSplyr.asc = function(field) {
return {_JSplyrName: "order param", type: "asc", field: field};
};
/**
* @param {Object} field a field name or fun instance.
* @return {Object} an order orbject (descending type)
*/
JSplyr.desc = function(field) {
return {_JSplyrName: "order param", type: "desc", field: field};
};
/**
* Creates an object with field names as keys and empty arrays as values.
*
* @param {Array} fields An array of field names.
* @return {Object} The object with the field names as keys and empty arrays.
*/
JSplyr.createOutput = function(fields) {
if(!Array.isArray(fields)) {throw "Argument must be an array!";}
var output = {};
fields.map(function (field) {
if (typeof(field) == "string") {
output[field] = [];
} else {
output[field.alias] = [];
}});
return output;
};
/**
* A python style range generator
*/
JSplyr.range = function(a, b, c) {
var start, end, step;
if (c === undefined && b === undefined) {
start = 0;
end = a;
step = 1;
} else {
start = a;
end = b;
step = c || 1;
}
var current = start;
var output = [];
while (current < end) {
output.push(current);
current += step;
}
return output;
};
/**
* Whether or not x is in array y
*
* @param {Object} x The object to be looked for
* @param {Array} y The array to be searched
* @return {logical} Whether x could be found in y.
*/
JSplyr.isIn = function(x, y) {
return y.indexOf(x) !== -1;
};
/**
* Returns unique entries from an array.
*
* @param {Array} a The array to be deduped.
* @return {Array} An array with unique values.
*/
JSplyr.unique = function(a) {
if(!Array.isArray(a)) {throw "Argument must be an array!";}
var output = [];
a.map(function(e) {if (!JSplyr.isIn(e, output)) {output.push(e);}});
return output;
};
/**
* Repeats a value n times
*
* @param {Object} x The object to be repeated.
* @param {number} n The number of repetitions.
* @return {Array} An array of size n filled with copies of x.
*/
JSplyr.repeat = function(x, n) {
if (!(typeof(n) === "number" && n >= 0 && n % 1 === 0)) {
throw "n must be an integer greater or than equal to 0"
}
var output = [];
while (n > 0) {
output.push(x);
n--;
}
return output;
};
/**
* Repeats a string n times and returns it in a new string instead of an array
*
* @param {String} str The string to be repeated
* @param {Number} n Integer (0 or greater) how many times str is repeated.
* @return {String} The repeated string
*/
JSplyr.repeatString = function(str, n, joinkey) {
joinkey = joinkey || "";
return JSplyr.repeat(str, n).join(joinkey);
};
/**
* Recursively checks if two arrays are identical
*/
JSplyr.equalArrays = function(a1, a2) {
if (!(Array.isArray(a1) && Array.isArray(a2))) {return false;}
if (a1.length !== a2.length) {return false;}
for (var i in a1) {
if (Array.isArray(a1[i])) {
if (!equalArrays(a1[i], a2[i])) {return false;jj}
} else {
if (a1[i] !== a2[i]) {return false;}
}
}
return true;
};
JSplyr.stringifier = Object.create(null);
/**
* Creates a character Object for a number
*/
JSplyr.stringifier.numberCharacterizer = function(x) {
return {
content: String(x),
type: "number",
height: 1,
width: String(x).length
}
};
/**
* Creates a character Object for a string
*/
JSplyr.stringifier.stringCharacterizer = function(x) {
var findNewlines = /[\n\r]/gi;
var newLines = x.match(findNewlines);
var height = newLines ? newLines.length + 1 : 1;
var rows = x.split(findNewlines);
var maxWidth = rows.reduce(function(x, y) {return x.length > y.length ? x : y});
return {content: x, type: "string", width: maxWidth.length, height: height}
};
/**
* Creates a character Object for a function
*/
JSplyr.stringifier.functionCharacterizer = function(x) {
var fString = x.toString().replace(/\r/g, "");
return JSplyr.stringifier.stringCharacterizer(fString);
};
/**
* Creates a character Object for an array
*/
JSplyr.stringifier.arrayCharacterizer = function(x) {
var elements = x.map(JSplyr.stringifier.characterize);
var outputContent =
"["+
elements.map(function(x) {return x.content}).toString() +
"]";
var output = JSplyr.stringifier.stringCharacterizer(outputContent)
return output;
};
/**
* Creates a character Object for a table
*/
JSplyr.stringifier.tableCharacterizer = function(x) {
var m = x.toMatrix();
var o = m.map(function(row) {
return row.map(JSplyr.stringifier.characterize);});
var fields = x.getFields();
var colWidths = o[0].map(function(x) {return x.width});
// Find widest row of each column
JSplyr.range(1, x.rows() + 1).forEach(function(row) {
for (var col in colWidths) {
if (o[row][col].width > colWidths[col]) {
colWidths[col] = o[row][col].width;
}
}
});
var rowHeights = o.map(function(row) {
return row
.map(function(x) {return x.height;})
.reduce(function(x, y) {return x > y ? x : y;})
});
/**
* function to create matrix for row containing subrows that can be parsed
* into a string to handle linebreaks
*/
function rowMatrix(row) {
// Create Subrows
var columns = fields.map(function(_, col) {
return o[row][col].content.split(/[\n\r]/);
});
// Standardize subrows to # of subrows the row needs
for (var col in o[row]) {
while (columns[col].length < rowHeights[row]) {
columns[col].push("");
}
// Pad subrows to column width
for (var subRow in columns[col]) {
while (columns[col][subRow].length < colWidths[col]) {
columns[col][subRow] += " ";
}
}
}
return columns
};
var output = "";
var rowNumberFiller = JSplyr.repeatString(
" ", Math.floor(1 + Math.log10(o.length)));
for (var row in o) {
if (row == 1) {
output += JSplyr.repeatString(" ", rowNumberFiller.length) + "| " +
colWidths.map(function(w) {return JSplyr.repeatString("-", w)}
).join(" | ") + " |\n";
}
var currentRow = rowMatrix(row);
for (var subRow in JSplyr.range(rowHeights[row])) {
// Add the row numbers
output += (subRow == 0 && row > 0 ?
rowNumberFiller.substring(
0, rowNumberFiller.length - String(row).length) + row :
rowNumberFiller) + "| ";
// Add rest of row
output += currentRow.map(function(col) {return col[subRow]}).join(" | ");
output += " |\n";
}
};
return JSplyr.stringifier.stringCharacterizer(output);
};
/**
* Creates a character Object for a generic object
*/
JSplyr.stringifier.objectCharacterizer = function(x) {
var stringifiedX = JSplyr.stringifier.stringCharacterizer(x.toString());
return stringifiedX;
};
/**
* Carachterizes generic objects by dispatching
*/
JSplyr.stringifier.characterize = function(x) {
if (typeof(x) === "number") return JSplyr.stringifier.numberCharacterizer(x);
if (typeof(x) === "string") return JSplyr.stringifier.stringCharacterizer(x);
if (typeof(x) === "function") return JSplyr.stringifier.functionCharacterizer(x);
if (Array.isArray(x)) return JSplyr.stringifier.arrayCharacterizer(x);
if (JSplyr.isObject(x, "Table")) return JSplyr.stringifier.tableCharacterizer(x);
return JSplyr.stringifier.objectCharacterizer(x);
};
/**
* toString prototype returning an ASCII representation of the table
*/
JSplyr.Table.prototype.toString = function() {
return JSplyr.stringifier.tableCharacterizer(this).content;
};
JSplyr.Table.prototype._JSplyrName = "Table";
/**
* Field names of the Table
*
* @return {Array} An array of the field names of the table.
*/
JSplyr.Table.prototype.getFields = function() {
return Object.keys(this.table)
};
/**
* The number of columns in the table
*
* @return {number} The number of columns in the table
*/
JSplyr.Table.prototype.cols = function() {
return this.getFields().length;
};
/**
* The i-th row's of a table as an array
*
* @param {Number} i The row number to be retrieved (0-based).
* @return {Object[]} An array of the values in the i-th row.
*/
JSplyr.Table.prototype.getRow = function(i) {
if (!(i % 1 == 0 && i >= 0)) {
throw "row must be an integer greater than or equal to 0";
}
var fields = this.getFields();
return fields.map(function(field) {return this.table[field][i];}, this);
};
/**
* The i-th row of a table as a dictionary
*
* @param {Number} i The row number to be retrieved (0-based).
* @return {Object} An array of the values in the i-th row.
*/
JSplyr.Table.prototype.getRowObject = function(i) {
var fields = this.getFields();
var output = {};
fields.forEach(function(field) {
output[field] = this.getColumn(field)[i];
}, this)
return output;
};
/**
* Retrieves a column from a table
*
* @param {String} col The column to be retrieved.
* @return {Object[]} The rows of the column
*/
JSplyr.Table.prototype.getColumn = function(col) {
if (!JSplyr.isIn(col, this.getFields())) {
throw "Column does not exist"
}
return this.table[col];
};
/**
* The number of rows in the table
*
* @return {number} The number of rows in the table.
*/
JSplyr.Table.prototype.rows = function() {
return this.table[this.getFields()[0]].length;
};
/**
* Limits the output starting at a given offset or the first row.
*
* @param {Number} limit The number of rows.
* @param {Number} offset The number of rows from the first at which to start.
* @return {Table} the truncated table.
*/
JSplyr.Table.prototype.limit = function(limit, offset) {
offset = offset || 0;
var fields = this.getFields();
var output = JSplyr.createOutput(fields);
fields.map(function(field) {
output[field] = this.table[field].splice(offset, limit);
}, this);
return JSplyr.createTable(output);
};
/**
* Creates a two dimensional array from the table.
*
* The table part gets returned as an array of equal length arrays.
* Each array is a row and each element in the sub arrays a column within it.
* The keys of the table object for into the first row.
*
* @returns {Array} An array of arrays containing the table.
*/
JSplyr.Table.prototype.toMatrix = function() {
var output = [];
var fields = this.getFields();
output.push(fields);
JSplyr
.range(this.rows())
.forEach(function(row) {output.push(this.getRow(row));}, this);
return output;
};
/**
* Adds an array of values to the table as a new field
*
* @param {Array} values The array of values to be added
* @param {String} alias The name the new field should have
* ~return {Table} The Table with the new column
*/
JSplyr.Table.prototype.addColumn = function (values, alias) {
if (!Array.isArray(values)) {
throw "First Argument must be an array";
}
if (values.length !== this.rows()) {
throw "Incompatible number of elements!";
}
output = this.table;
output[alias] = values;
return JSplyr.createTable(output);
};
/**
* Selects a list of fields from the existing table.
*
* Takes either field names, As Aliases or Fun Functions.
*
* @param {...} ... A list of arguments.
* @return {Table} An instance of a table with the selected fields.
*/
JSplyr.Table.prototype.select = function() {
var fields = JSplyr.objectToArray(arguments);
//verify fields exist
var tableFields = this.getFields();
fields.map(function(field) {
if (JSplyr.isIn(field, ["object", "string"])) {
throw "Wrong argument type";
}
if (typeof(field) === "string") {
if (!JSplyr.isIn(field, tableFields) && field !== "*") {
throw field + "is not a field of this table";
}
}
});
var output = {};
fields.map(function (field) {
if (typeof(field) == "string") {
output[field] = this.table[field];
} else if (JSplyr.isObject(field, "function")) {
output[field.alias] = this.applyScalar(field);
} else {
output[field.alias] = this.table[field.field];
}
}, this);
return JSplyr.createTable(output);
};
/**
* Applies a Fun object to a table
*
* @param {Fun} fun A Fun object.
* @return {Array} Returns an array of the results, one element per row.
*/
JSplyr.Table.prototype.applyScalar = function(fun) {
if (!JSplyr.isObject(fun, "function")) {
throw "Must provide a Fun Object!";
}
var fields = this.getFields();
var r = this.rows();
var args = fun.args.map(function(arg) {
if (!JSplyr.isIn(arg, fields)) {
return JSplyr.repeat(arg, r);
} else {
return this.table[arg];
}
}, this);
var output = [];
var currentArgs;
for (var row = 0; row < r; row++) {
currentArgs = args.map(function(arg) {return arg[row];});
output.push(fun.fun.apply(this, currentArgs));
}
return output;
};
/**
* Whether rows fulfil a criterion or not
*
* The function accepts either a string of a comparison such as == or > or
* a function or a column reference;
* that column must contain a functio in every row!
* Due to the way JS evaluates truthiness any return value is ok.
* The comperands can be field names, fun instances or literals.
*
* @param {Object} lop The left operand.
* @param {Object} op The operand.
* @param {Object} rop The right operand.
* @return {Array} An array of booleans or values that will be used as such.
*/
JSplyr.Table.prototype.is = function(comp) {
var lop = comp.lop;
var op = comp.op;
var rop = comp.rop;
var args = comp.args;
var fields = this.getFields();
var output = [];
var operations = {
"==": function(l, r) {return l == r;},
"===": function(l, r) {return l === r;},
">": function(l, r) {return l > r;},
"<": function(l, r) {return l < r;},
">=": function(l, r) {return l >= r;},
"<=": function(l, r) {return l <= r;},
"!=": function(l, r) {return l != r;},
"!==": function(l, r) {return l !== r;}
};
if (typeof(op) === "function") {
operations[op] = op;
} else if (JSplyr.isIn(op, fields)) {
operations[op] = this.table[op];
} else if (operations[op] === undefined) {
throw "Operator must be a function, JS comparison or a field reference!";
}
function createComparator(side, thisArg) {
thisArg = thisArg || this;
if (JSplyr.isIn(side, fields)) {
return thisArg.table[side];
} if (JSplyr.isObject(side, "function")) {
return thisArg.applyScalar(side)
}
return JSplyr.repeat(side, thisArg.rows());
}
var lopf = createComparator(lop, this);
var ropf = createComparator(rop, this);
var optArgs = args.map(
function(arg) {return createComparator(arg, this);},
this);
for (var row in lopf) {
var optArgsForRow = optArgs.map(function(arg) {return arg[row];});
output.push((fields.indexOf(op) !== -1 ?
operations[op][row] :
operations[op]).apply(
this,
[lopf[row], ropf[row]].concat(optArgsForRow)));
}
return output;
};
/**
* Filters a table's rows.
*
* @param {Array} criterion An array of boolean values, one for each row.
* @return {createTable} The resulting filtered table.
*/
JSplyr.Table.prototype.filter = function(criterion) {
var fields = this.getFields();
var output = JSplyr.createOutput(fields);
function addRow(rowI) {
function pushCol(col) {output[field].push(this[field][rowI]);};
fields.map(addRow);
};
for (var row in criterion) {
if (criterion[row]) {
fields.map(function(field) {
output[field].push(this.table[field][row]);
}, this);
}
}
return JSplyr.createTable(output);
};
/**
* Filters a table based on a logical combination or comparison provided
*/
JSplyr.Table.prototype.where = function(expr) {
if (JSplyr.isObject(expr, "comparison")) {
return this.filter(this.is(expr));
} else if(JSplyr.isObject(expr, "logical combination")) {
return this.filter(JSplyr.evaluateLogicalCombination(expr, this))
} else {
throw "Expression must be a comparison or logical combination!";
}
};
/**
* Creates the union all of to tables.
*
* Behavior of behavior:
* - undefined or 0 uses only common columns
* - 1 uses only left columns
* - 2 uses right columns
* - 3 uses all columns
*
* @param {createTable} t The table to be unioned with.
* @param {number} behavior Which columns are to be selected.
* @param {Object} empty The value missing columns shall be filled with.
* @return {Table} The union of two tables.
*/
JSplyr.Table.prototype.union = function(t, behavior, empty) {
behavior = behavior || 0;
var lfields = this.getFields();
var rfields = t.getFields();
var fields;
if (behavior == 0) {
fields = lfields.filter(function(lField) {
return JSplyr.isIn(lField, rfields);
})
}
if (behavior == 1) {fields = lfields;}
if (behavior == 2) {fields = rfields;}
if (behavior == 3) {fields = JSplyr.unique(lfields.concat(rfields));}
var output = JSplyr.createOutput(fields);
// Check if any of the fields of the left table are in the final table
// To see if missing values need to be filled up
function fillUpNeeded(unionPartFields) {
return unionPartFields.map(function(field) {
return JSplyr.isIn(field, fields);}).reduce(function(a,b) {
return a || b;});
}
function appendRows(source, field, unionPartfields, needsFillUp) {
if (JSplyr.isIn(field, unionPartfields)) {
output[field] = output[field].concat(source.table[field]);
} else if (needsFillUp) {
output[field] = output[field].concat(JSplyr.repeat(empty, source.rows()));
}
}
var lfillupNeeded = fillUpNeeded(lfields);