-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhxl.js
2298 lines (2089 loc) · 66.5 KB
/
hxl.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
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
/**
* Simple HXL library.
*
* This isn't a full-featured HXL library; it focusses on datasets
* that have already had tags expanded, and includes mainly filtering
* operations that are useful to support mapping and visualisation.
*
* @author David Megginson
* @date 2021-05-25
* @version 0.6
*/
////////////////////////////////////////////////////////////////////////
// Root object
////////////////////////////////////////////////////////////////////////
/**
* Root hxl object, from which everything else starts.
*
* See {@link hxl.classes.Source} for a list of methods to use on a
* HXL object.
*
* @global
* @namespace
*/
var hxl = {
/**
* @namespace
*/
classes: {},
/**
* List of attached loggers
*/
loggers: [],
version: "0.4"
};
/**
* Log a warning or error message.
*
* Add logger functions to hxl.loggers.
*
* @param {string} message The message to log.
*/
hxl.log = function (message) {
hxl.loggers.forEach(logger => {
logger(message);
});
};
/**
* Wrap a JavaScript array as a HXL dataset.
*
* @param {array} rawData an array of arrays of raw strings to wrap
* @return a new {@link hxl.classes.Dataset}
*/
hxl.wrap = function (rawData) {
/**
* Convert object-style JSON to row-style JSON
*/
function convertToRows (data) {
let result = [[]];
let columnCount = 0;
let columns = {};
data.forEach(item => {
let row = [];
if (typeof(item) !== "object" || item === null) {
// expecting objects
console.error("Expected array of objects", item);
throw new Error("Expected array of objects in hxl.wrap()");
}
Object.keys(item).forEach(key => {
if (!(key in columns)) {
// we haven't seen this key yet; note it
columns[key] = columnCount++;
// add to header row
result[0][columns[key]] = key;
}
// add the value to the appropriate position in the row
row[columns[key]] = item[key];
});
// remove null and undefined values
for (var i = 0; i < columnCount; i++) {
if (row[i] === undefined || row[i] === null) {
row[i] = "";
}
}
// add the row to the dataset
result.push(row);
});
return result;
}
if (!Array.isArray(rawData)) {
console.error("Expected an array", rawData);
throw new Error("Expected an array in hxl.wrap()");
}
if (rawData.length == 0) {
console.error("Empty array", rawData);
throw new Error("Empty array in hxl.wrap()");
}
if (!Array.isArray(rawData[0])) {
rawData = convertToRows(rawData);
}
return new hxl.classes.Dataset(rawData);
};
/**
* Load a remote HXL dataset asynchronously.
*
* The callback takes a single argument, which is
* the HXL data source (when successfully loaded).
*
* @param {string} url The URL of the HXL dataset to load.
* @param {function} callback The function to call when loaded.
* @param {boolean} useProxy Pass the dataset through the HXL Proxy.
*/
hxl.load = function (url, callback) {
if ("Papa" in window && "parse" in window["Papa"]) {
window["Papa"].parse(url, {
download: true,
skipEmptyLines: true,
complete: result => {
callback(hxl.wrap(result.data));
},
error: result => {
console.error(result);
throw new Error(result);
}
});
} else {
throw Error("No CSV parser available (tried Papa.parse)");
}
};
/**
* Load a remote dataset asynchronously via the HXL Proxy
* @param {function} success_callback Callback for a successful load (arg is hxl.Dataset object)
* @param {function} error_callback Callback for an error (arg is XmlHttpRequest)
*/
hxl.proxy = function (dataUrl, successCallback, errorCallback) {
var url = "https://proxy.hxlstandard.org/data.json?url=" + encodeURIComponent(dataUrl);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = () => {
if (xhr.status === 200) {
successCallback(hxl.wrap(JSON.parse(xhr.responseText)));
} else {
if (errorCallback) {
errorCallback(xhr);
}
}
};
xhr.send(null);
};
/**
* Load a HXL dataset from a string
*/
hxl.parseString = function(string) {
if ("Papa" in window && "parse" in window["Papa"]) {
return hxl.wrap(window["Papa"].parse(string).data);
} else {
throw Error("No CSV parser available (tried Papa.parse)");
}
}
/**
* Normalise just whitespace within a string.
*/
hxl.normaliseSpace = function (value) {
if (value) {
return value.toString().trim().replace(/\s+/, ' ');
} else {
return null;
}
};
/**
* Normalise case and whitespace in a string.
*
* @param {string} value The string value to normalise.
* @return {string} the string with case and whitespace normalised.
*/
hxl.normaliseString = function (value) {
if (value) {
return hxl.normaliseSpace(value).toLowerCase();
} else {
return null;
}
};
/**
* Normalise a date.
* @param {string} dateString - the date string to normalise
* @return {string} - a normalised date string (ISO or extended Q format)
*/
hxl.normaliseDate = function (dateString, dayfirst=true) {
dateString = dateString.trim().toUpperCase();
// ISO date?
if (dateString.match(/^\d{4}(-\d{2}(-\d{2})?|Q[1-4])?$/)) {
return dateString;
}
// may need to swap month and day
// Date.parse expects mm/dd/yy
var result = dateString.match(/^(\d\d?)[ .-/]+(\d\d?)[ .-/]+(\d\d\d?\d?)$/);
if (result) {
if (0 + result[1] > 12 || (0 + result[2] <= 12 && dayfirst)) {
dateString = result[2] + '/' + result[1] + '/' + result[3];
}
}
// Fall back to the old, broken date parse
var timestamp = Date.parse(dateString);
if (isNaN(timestamp)) {
return false;
}
var date = new Date(timestamp);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
return ('0000' + year).slice(-4) + '-' +
('00' + month).slice(-2) + '-' +
('00' + day).slice(-2);
};
////////////////////////////////////////////////////////////////////////
// Data-type wrangling
////////////////////////////////////////////////////////////////////////
hxl.types = {};
/**
* Check if a value is logically empty.
* @param s: the value to check
* @returns: true if the value is null, an empty string, or all whitespace
*/
hxl.types.isEmpty = function (s) {
// check for an isSpace function
return (s === null || s === "" || s.match(/^\s+$/));
};
/**
* Check if a value is parseable as a number.
*/
hxl.types.isNumber = function (s) {
return !isNaN(hxl.types.toNumber(s));
};
/**
* Normalise a value as a number.
*/
hxl.types.toNumber = function (s) {
if (isNaN(s)) {
s = s.replace(/[\s|,]+/, '');
}
var intValue = parseInt(s);
var floatValue = parseFloat(s);
if (intValue === floatValue) {
return intValue;
} else {
return floatValue;
}
};
/**
* Check if a value is parseable as a date.
*/
hxl.types.isDate = function (s) {
return !isNaN(Date.parse(s));
};
////////////////////////////////////////////////////////////////////////
// hxl.classes.Source
////////////////////////////////////////////////////////////////////////
/**
* Abstract base class for any HXL data source.
* Derived classes must define getColumns() and iterator()
*
* @constructor
* @property {array} columns an array of column specs (see {@link #getColumns})
* @property {array} rows an array of data rows (see {@link #getRows})
* @property {array} headers an array of string headers (see {@link #getHeaders})
* @property {array} tags an array of string tags, without attributes (see {@link #getTags})
* @property {array} displayTags an array of display tags, with attributes (see {@link #getDisplayTags})
*/
hxl.classes.Source = function() {
var prototype = Object.getPrototypeOf(this);
this.indexCache = {};
Object.defineProperty(this, 'columns', {
enumerable: true,
get: prototype.getColumns
});
Object.defineProperty(this, 'rows', {
enumerable: true,
get: prototype.getRows
});
Object.defineProperty(this, 'rawData', {
enumerable: true,
get: prototype.getRawData
});
Object.defineProperty(this, 'headers', {
enumerable: true,
get: prototype.getHeaders
});
Object.defineProperty(this, 'tags', {
enumerable: true,
get: prototype.getTags
});
Object.defineProperty(this, 'displayTags', {
enumerable: true,
get: prototype.getDisplayTags
});
}
/**
* Get a list of columns for a HXL dataset.
*
* <pre>
* var columns = data.getColumns();
* </pre>
*
* It is usually easier to use the {@link #columns} property, which is
* an alias to this method:
*
* <pre>
* var columns = data.columns;
* </pre>
*
* @function
* @return {array} an array of {@link hxl.classes.Column} objects.
* @see #columns
* @see #getRows
*/
hxl.classes.Source.prototype.getColumns = undefined;
/**
* Get an iterator to read through the rows of a HXL dataset.
*
* The iterator will have a next() method to read each row in sequence, and
* will return null once the rows are exhausted.
*
* <pre>
* var row;
* var iterator = data.iterator();
* while (row = iterator.next()) {
* // do something with the row
* }
* </pre>
*
* The {@link #each} or {@link #forEach} method provides a
* more-elegant way of iterating through rows, but this method makes
* it easier to break out of the loop early.
*
* Note: doesn't implement the full Javascript iteration protocol
* (which would mean returning an object with "value" and "done"
* properties).
*
* @function
* @return {object} An iterator object with a .next() method.
* @see #getRows
* @see #each
* @see #forEach
*/
hxl.classes.Source.prototype.iterator = undefined;
/**
* Get an array of row objects.
*
* This method might be highly inefficient, depending on the
* implementation in the derived class. Normally, it's best
* to go through the rows using an iterator.
*
* <pre>
* var rows = data.getRows();
* </pre>
*
* It is usually easier to use the {@link #rows} property, which is an
* alias to this method:
*
* <pre>
* var rows = data.rows;
* </pre>
*
* @return {array} An array of {@link hxl.classes.Row} objects.
* @see #rows
* @see #iterator
* @see #getColumns
*/
hxl.classes.Source.prototype.getRows = function () {
var rows = [];
var iterator = this.iterator();
var row = iterator.next();
while (row) {
rows.push(row);
row = iterator.next();
}
return rows;
}
/**
* Get raw data for the dataset (excluding header rows and hashtag row)
*/
hxl.classes.Source.prototype.getRawData = function () {
var rawData = [];
var iterator = this.iterator();
var row = iterator.next()
while (row) {
rawData.push(row.values);
row = iterator.next()
}
return rawData;
};
/**
* Get an array of human-readable column headers.
*
* These are the headers that come before the HXL hashtag row. This is
* especially useful for creating an HTML table, CSV, JSON, etc.
*
* <pre>
* var headerRow = data.getHeaders();
* </pre>
*
* It is usually easier to use the {@link #headers} property, which is
* an alias to this method:
*
* <pre>
* var headerRow = data.headers();
* </pre>
*
* @return {array} An array of strings.
`* @see #headers
* @see #getTags
* @see #getDisplayTags
* @see #getColumns
*/
hxl.classes.Source.prototype.getHeaders = function () {
return this.columns.map(col => col.header);
}
/**
* Get an array of tags.
*
* These are plain tags, without attributes.
*
* <pre>
* var tagList = data.getTags();
* </pre>
*
* It is usually easier to use the {@link #tags} property, which is an
* alias to this method:
*
* <pre>
* var tagList = data.tags;
* </pre>
*
* @return {array} An array of strings.
* @see #tags
* @see #getDisplayTags
* @see #getHeaders
* @see #getColumns
*/
hxl.classes.Source.prototype.getTags = function () {
return this.columns.map(col => col.tag);
}
/**
* Get an array of tagspecs.
*
* These are full tagspecs, with attributes. This is especially useful
* for creating an HTML table, CSV, JSON, etc.
*
* <pre>
* var tagRow = data.getDisplayTags();
* </pre>
*
* It is usually more convenient to use the {@link #displayTags} property,
* which is an alias to this method:
*
* <pre>
* var tagRow = data.displayTags;
* </pre>
*
* @return {array} An array of strings.
* @see #displayTags
* @see #getTags
* @see #getHeaders
* @see #getColumns
*/
hxl.classes.Source.prototype.getDisplayTags = function () {
return this.columns.map(col => col.displayTag);
}
/**
* Export the whole dataset, include hashtags.
*
* @param skipHeaders: if truthy, exclude the text headers
* @return {array} an array of arrays forming a parseable HXL dataset
*/
hxl.classes.Source.prototype.exportArray = function(skipHeaders) {
var exported = [];
if (!skipHeaders) {
exported.push(this.headers);
}
exported.push(this.displayTags);
return exported.concat(this.rawData);
};
/**
* Get the sum of numeric values in a column
*
* <pre>
* var totalAffected = data.getSum('#affected');
* </pre>
*
* @param {string} pattern The tag pattern for the column(s) to
* use. See {@link hxl.classes.TagPattern} for details.
* @return {float} The sum of numeric values in the column.
* @see #getMax
*/
hxl.classes.Source.prototype.getSum = function(pattern) {
let result = 0;
const index = this.getColumnIndex(pattern);
if (index !== null) {
this.forEach(row => {
if (index < row.values.length && hxl.types.isNumber(row.values[index])) {
result += hxl.types.toNumber(row.values[index]);
}
});
}
return result;
}
/**
* Get the minimum value for a column
*
* Uses a less-than comparison, ignoring empty cells. This method is
* especially useful for setting ranges in a chart or other
* visualisation.
*
* <pre>
* var minAffected = data.getMin('#affected');
* </pre>
*
* @param {string} pattern The tag pattern for the column(s) to
* use. See {@link hxl.classes.TagPattern} for details.
* @return {string} The lowest value in the column.
* @see #getMax
*/
hxl.classes.Source.prototype.getMin = function(pattern) {
let min = null;
const index = this.getColumnIndex(pattern);
if (index !== null) {
this.forEach(row => {
if (index < row.values.length && hxl.types.isNumber(row.values[index])) {
let num = hxl.types.toNumber(row.values[index]);
if (min === null || num < min) {
min = num;
}
}
});
}
return min;
}
/**
* Get the maximum value for a column
*
* Uses a greater-than comparison, ignoring empty cells. This method is especially
* useful for setting ranges in a chart or other visualisation.
*
* <pre>
* var maxAffected = data.getMax('#affected');
* </pre>
*
* @param {string} pattern The tag pattern for the column(s) to
* use. See {@link hxl.classes.TagPattern} for details.
* @return {string} the highest value in the column.
* @see #getMin
*/
hxl.classes.Source.prototype.getMax = function(pattern) {
let max = null;
const index = this.getColumnIndex(pattern);
if (index !== null) {
this.forEach(row => {
if (index < row.values.length && hxl.types.isNumber(row.values[index])) {
let num = hxl.types.toNumber(row.values[index]);
if (max === null || num > max) {
max = num;
}
}
});
}
return max;
}
/**
* Get a list of unique values for a tag
*
* Uses a map to store unique values.
*
* <pre>
* var sectorList = data.getValues('#sector');
* </pre>
*
* @param {hxl.classes.TagPattern} pattern A tag pattern to match for the column(s).
* @return {array} A list of unique values.
*/
hxl.classes.Source.prototype.getValues = function(pattern) {
var valueMap = {};
var index = this.getColumnIndex(pattern);
if (index !== null) {
this.forEach(row => {
if (index < row.values.length) {
valueMap[row.values[index]] = true;
}
});
}
return Object.keys(valueMap);
}
/**
* Get a list of all values for a tag (included repeated values and nulls)
*
* <pre>
* var sectorList = data.getRawValues('#sector');
* </pre>
*
* @param {hxl.classes.TagPattern} pattern A tag pattern to match for the column(s).
* @return {array} A list of unique values.
*/
hxl.classes.Source.prototype.getRawValues = function(pattern) {
let result = [];
// precompute the index for speed
let index = this.getColumnIndex(pattern);
// iterate through the dataset
this.forEach(row => {
if (index === null || row.values.length <= index) {
result.push(null);
} else {
result.push(row.values[index]);
}
});
return result;
}
/**
* Check if a dataset contains at least one column matching a pattern.
*
* <pre>
* if (data.hasColumn('#meta+count')) {
* draw_my_graph(data);
* }
* </pre>
*
* @param {hxl.classes.TagPattern} pattern A tag pattern to match for the column(s).
* @return {boolean} true if there's a match, false otherwise.
* @see #getColumns
*/
hxl.classes.Source.prototype.hasColumn = function (pattern) {
return (this.getColumnIndex(pattern) !== null);
}
/**
* Get the index of the first matching column (0-based)
*/
hxl.classes.Source.prototype.getColumnIndex = function(pattern) {
var indices = this.getColumnIndices(pattern);
if (indices.length > 0) {
return indices[0];
} else {
return null;
}
};
/**
* Get a list of indices for columns matching a tag pattern (0-based)
*/
hxl.classes.Source.prototype.getColumnIndices = function(pattern) {
// Handle a null pattern gracefully
if (!pattern) {
return null;
}
// Try for a cache hit
if (pattern.toString() in this.indexCache) {
return this.indexCache[pattern.toString()];
}
let result = [];
pattern = hxl.classes.TagPattern.parse(pattern); // more efficient to precompile
columns = this.getColumns();
for (var i = 0; i < columns.length; i++) {
if (pattern.match(columns[i])) {
result.push(i);
}
}
this.indexCache[pattern.toString()] = result;
return result;
}
/**
* Fire a callback on each row of data.
*
* The callback has the form
*
* <pre>
* function (row, source, rowNumber) {}
* </pre>
*
* (Often, the callback will need to bother with only the first parameter,
* so function (row) {} will be more typical).
*
* <pre>
* var sectors = {};
* data.each(function(row) {
* sectors[row.getValue('sector')] = true;
* });
* </pre>
*
* @param {function} callback Callback function for each row of data.
* @return {int} The number of rows processed.
* @see #iterator
*/
hxl.classes.Source.prototype.each = function(callback) {
var rowNumber = 0, iterator = this.iterator();
var row = iterator.next();
while (row) {
callback(row, this, rowNumber++);
row = iterator.next();
}
return rowNumber;
}
/**
* Alias each() to forEach()
*
* <pre>
* var sectors = {};
* data.forEach(function(row) {
* sectors[row.getValue('sector')] = true;
* });
* </pre>
*
* @function
*/
hxl.classes.Source.prototype.forEach = hxl.classes.Source.prototype.each;
/**
* Test if a tag pattern points mainly to numbers.
*
* This method is useful for trying to guess which columns contain numeric
* values that can be graphed:
*
* <pre>
* if (data.isNumbery('#affected')) {
* min = data.getMin('#affected');
* }
* </pre>
*
* @param {hxl.classes.TagPattern} pattern A tag pattern to match for the column(s).
* @return {boolean} true if at least 90% of the non-null values are numeric.
*/
hxl.classes.Source.prototype.isNumbery = function(pattern) {
var totalSeen = 0;
var numericSeen = 0;
var index = this.getColumnIndex(pattern);
if (index === null) {
return false;
}
this.rows.forEach(row => {
if (index < row.values.length) {
let value = row.values[index];
if (value) {
totalSeen++;
if (hxl.types.isNumber(value)) {
numericSeen++;
}
}
}
});
return (totalSeen > 0 && (numericSeen/totalSeen >= 0.9));
}
/**
* Filter rows to include only those that match at least one predicate.
*
* Use this, for example, to include only rows where the #sector is "WASH":
*
* <pre>
* var filtered = data.withRows('sector=WASH');
* </pre>
*
* @param {array or string} predicates a single string predicate or a list of predicates.
* See {@link hxl.classes.RowFilter} for details.
* @return {hxl.classes.Source} A new data source, including only selected data rows.
* @see hxl.classes.RowFilter
*/
hxl.classes.Source.prototype.withRows = function(predicates) {
return new hxl.classes.RowFilter(this, predicates, false);
}
/**
* Filter rows to include only those that match none of the predicates.
*
* Use this, for example, to exclude any rows where the #status is "completed":
*
* <pre>
* var filtered = data.withoutRows('status=completed');
* </pre>
*
* @param predicates a single string predicate or a list of predicates.
* See {@link hxl.classes.RowFilter} for details.
* @return {hxl.classes.Source} A new data source, excluding matching data rows.
* @see hxl.classes.RowFilter
*/
hxl.classes.Source.prototype.withoutRows = function(predicates) {
return new hxl.classes.RowFilter(this, predicates, true);
}
/**
* Filter columns to include only those that match the pattern(s) provided.
*
* Use this, for example, to strip down a dataset to only the desired columns:
*
* <pre>
* var filtered = data.withColumns('org,sector,adm1');
* </pre>
*
* @param {array or string} patterns A single string tag pattern or a
* list of tag patterns for included columns (whitelist). See {@link
* hxl.classes.TagPattern} for details.
* @return {hxl.classes.Source} A new data source, including only matching columns.
* @see #withoutColumns
* @see hxl.classes.ColumnFilter
*/
hxl.classes.Source.prototype.withColumns = function(patterns) {
return new hxl.classes.ColumnFilter(this, patterns);
}
/**
* Filter columns to include only those that don't match the pattern(s) provided.
*
* Use this, for example, to remove any columns containing
* personally-identifiable information (PII):
*
* <pre>
* var filtered = data.withoutColumns('contact');
* </pre>
*
* @param {array or string} patterns A single string tag pattern or a
* list of tag patterns for excluded columns (blacklist). See {@link
* hxl.classes.TagPattern} for details.
* @return {hxl.classes.Source} A new data source, excluding matching columns.
* @see #withColumns
* @see hxl.classes.ColumnFilter
*/
hxl.classes.Source.prototype.withoutColumns = function(patterns) {
return new hxl.classes.ColumnFilter(this, patterns, true);
}
/**
* Count the unique occurrences of a combination of values in a dataset.
*
* Use this to count, e.g. the number of sectors, or the number of
* #org / #sector combinations:
*
* <pre>
* var filtered = data.count('org');
* </pre>
*
* @param {array or string} patterns A single string tag pattern or a
* list of tag patterns for counting unique combinations. See {@link
* hxl.classes.TagPattern#parse} for details.
* @param aggregate {string} (optional) A single numeric tag pattern for which
* to produce aggregate values
* @return {hxl.classes.Source} A new data source, including the aggregated data.
* @see hxl.classes.CountFilter
*/
hxl.classes.Source.prototype.count = function(patterns, aggregate) {
return new hxl.classes.CountFilter(this, patterns, aggregate);
}
/**
* Change the tag (and optionally, header) for one or more columns.
*
* Use this to change around tags and attributes. For example, you
* could change the first instance of #org to #org+funder to make the
* data easier to filter later:
*
* <pre>
* var filtered = data.rename('#org', '#org+funder', 'Donor', 0);
* </pre>
*
* @param {string} pattern The tag pattern to match for replacement.
* See {@link hxl.classes.TagPattern#parse} for details.
* @param newTag the new HXL tag spec (e.g. "#adm1+code"). See {@link
* hxl.classes.Column#parse} for details.
* @param {string} newHeader (optional) The new header. If undefined, don't change.
* @param {int} index The zero-based index to replace among matching tags. If undefined,
* replace *all* matches.
* @return {hxl.classes.Source} A new data source, with matching column(s) replaced.
* @see hxl.classes.RenameFilter
*/
hxl.classes.Source.prototype.rename = function(pattern, newTag, newHeader, index) {
return new hxl.classes.RenameFilter(this, pattern, newTag, newHeader, index);
}
/**
* Sort the dataset.
*
* <pre>
* var filtered = data.sort('#affected');
* </pre>
*
* @param {string} patterns The tag patterns to use as sort keys.
* @param {boolean} reverse If true, reverse the sort order.
* @return {hxl.classes.Source} A new data source, sorted.
* @see hxl.classes.SortFilter
*/
hxl.classes.Source.prototype.sort = function(patterns, reverse) {
return new hxl.classes.SortFilter(this, patterns, reverse);
}
/**
* Show a preview of the first few rows of a dataset.
*
* Use this to change around tags and attributes. For example, you
* could change the first instance of #org to #org+funder to make the
* data easier to filter later:
*
* <pre>
* var filtered = data.rename('#org', '#org+funder', 'Donor', 0);
* </pre>
*
* @param {string} pattern The tag pattern to match for replacement.
* See {@link hxl.classes.TagPattern#parse} for details.
* @param newTag the new HXL tag spec (e.g. "#adm1+code"). See {@link
* hxl.classes.Column#parse} for details.
* @param {int} index maximum number of rows to return (defaults to 10).
* @return {hxl.classes.Source} A new data source, with matching column(s) replaced.
* @see hxl.classes.PreviewFilter
*/
hxl.classes.Source.prototype.preview = function(maxRows) {
return new hxl.classes.PreviewFilter(this, maxRows);
}
/**
* Cache the transformed HXL for future use.
*
* Create a copy of the HXL dataset, as transformed up to this point
* in the filter chain, to save future work. Some filters, like
* {@link hxl.classes.CountFilter}, already build their own cache, and
* don't need this filter.
*
* <pre>
* var filtered = data.withRows('sector=WASH').withoutColumns('contact').cache();
* </pre>
*
* @return {hxl.classes.Source} a new data source, with all transformations cached.
* @see hxl.classes.CacheFilter
*/
hxl.classes.Source.prototype.cache = function() {
return new hxl.classes.CacheFilter(this);
}