-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathFiddler.gs
1991 lines (1738 loc) · 57.2 KB
/
Fiddler.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
/**
* this is the V8 version
* if you need the legacy version use cUseful.Fiddler
* this is a utility for messing around with
* values obtained from setValues method
* of a spreadsheet
* @contructor Fiddler
* @param {Sheet} [sheet=null] populate the fiddler
*/
function Fiddler(sheet) {
var self = this;
var _values,
_headerOb = null,
_dataOb = [],
_empty = true,
_hasHeaders = true,
_functions,
_renameDups = true,
_renameBlanks = true,
_blankOffset = 0,
_sheet = null,
_headerFormat = {},
_columnFormats = null,
_tidyFormats = false,
_flatOptions = null,
_formulaOb = null,
_formulas,
_custom = null,
_defaultFlat = {
flatten: true,
objectSeparator: ".",
itemSeparator: ",",
expandArray: true,
columns: []
};
const _isUndef = (value) => {
return typeof value === typeof undefined
}
const _isNull = (value) => {
return value === null
}
const _isNundef = (value) => _isUndef(value) || _isNull(value)
const _isObject = (value) => Object(value) === value
const _isDate = (value) => (value instanceof Date)
const _forceArray = (item) => Array.isArray(item) ? item : [item]
/**
* TODO .. its a long story because of formatting
* work out details for next major version
*
* flattener works like this
* when writting to a sheet
* any objects get flattened
* {a:1,b:2,c:{d:3,e:{f:25}},g:[1,2,3]}
* becomes
* header of a,b c.d c.e.f g.o g.1 g.2
* values of 1 2 3 25 1 2 3
* objectseparator(".") is used in headers as in "c.d" and "g.1"
* and itemSeparator is used in arrays where expandArray is true as in 1 2 3 versus 1,2,3 in a single column
* when reading from a sheet
* headers are investigated for patterns like above and get shrunk back into objects/arrays
**/
/**
* these are the default iteration functions
* for the moment the do nothing
* just here for illustration
* properties take this format
* not all are relevant for each type of function
* .name the name of the column
* .data all the data in the fiddle
* .headers the header texts
* .rowOffset the row number starting at 0
* .columnOffset the column number starting at 0
* .fiddler this object
* .values an array of values for this row or column
* .row an object with all the properties/values for the current row
* .fiddler the fiddler obkect
*/
var _defaultFunctions = {
/**
* used to compare two values
* @param {*} a itema
* @param {*} b item b
* @return {boolean} whether the same
*/
compareFunc: function (a, b) {
return a === b;
},
/**
* used to filter rows
* @param {object} row the row object
* @param {object} properties properties of this row
* @return {boolean} whether to include
*/
filterRows: function (row, properties) {
return true;
},
/**
* used to filter columns
* @param {string} heading the heading text
* @param {object} properties properties of this column
* @return {boolean} whether to include
*/
filterColumns: function (heading, properties) {
return true;
},
/**
* used to change objects rowwise
* @param {object} row object
* @param {object} properties properties of this row
* @return {object} modified or left as is row
*/
mapRows: function (row, properties) {
return row;
},
/**
* used to change values columnwise
* @param {[*]} values the values for each row of the column
* @param {object} properties properties of this column
* @return {[*]|undefined} values - modified or left as is
*/
mapColumns: function (values, properties) {
return values;
},
/**
* used to change values columnwise in a single column
* @param {*} value the values for this column/row
* @param {object} properties properties of this column
* @return {[*]|undefined} values - modified or left as is
*/
mapColumn: function (value, properties) {
return value;
},
/**
* used to change header values
* @param {string} name the name of the column
* @param {object} [properties] properties of this column
* @return {*} values - modified or left as is
*/
mapHeaders: function (name, properties) {
return name;
},
/**
* returns the indices of matching values in a column
* @param {*} value the values for this column/row
* @param {object} properties properties of this columnrang
* @return {boolean} whether it matches
*/
selectRows: function (value, properties) {
return true;
}
};
// maybe a later version we'll allow changing of default functions
_functions = _defaultFunctions;
/**
* RangeValuePair - an object that contains the range and values
* @typedef {Object} RangeValuePair
* @property {string} name - any name for identification(usually a column name)
* @property {*[[]} values - The values - ready for use with setValues
* @property {Range} range - The range it applies to
*/
/**
* set a custom value in the fiddler - can be anything
* @param {*} value value to set
* @return {Fiddler} self
*/
self.setCustom = (value) => {
_custom = value;
return self;
}
/**
* get a custom value in the fiddler - can be anything
* @return {*} custom value
*/
self.getCustom = () => _custom
/**
* convert columns to values
* @param {string|string[]} [columnName] 0 or more column names to process -null is them all
* @return {RangeValuePair[]} all you need to dump the columns
*/
self.getDumper = (columnNames) => {
// first get the rangeList for these columns
columnNames = _patchColumnNames(columnNames)
return self.getRangeList(columnNames).getRanges()
.map((range, i) => {
const name = columnNames[i]
return {
values: _dataOb.map(row => [row[name]]),
range,
name
}
})
}
/**
* dump columns
* @param {string|string[]} [columnName] 0 or more column names to process
* @return {RangeValuePair[]} all you need to dump the columns
*/
self.dumpColumns = (columnNames, sheet) => self.getDumper(columnNames).map(rp => {
// first clear the existing data from that column
const targetSheet = sheet || rp.range.getSheet()
const rows = targetSheet.getDataRange().getNumRows()
const range = sheet
? targetSheet.getRange(rp.range.getRow(), rp.range.getColumn()).offset(0, 0, rp.range.getNumRows(), rp.range.getNumColumns())
: rp.range
if (rows) range.offset(0, 0, rows, range.getNumColumns()).clearContent()
// the data
range.setValues(rp.values)
// the header (if there is one)
if (self.hasHeaders()) range.offset(-1, 0, 1, 1).setValue(rp.name)
return {
...rp,
range
}
})
/**
* get the formulas from the sheet
* returns {object} self for chaining
*/
self.needFormulas = () => {
_formulas = self.getRange().getFormulas()
_formulaOb = _makeFormulaOb()
return self
}
// make a digest out of anything
self.fingerprinter = (...args) => {
// dont allow undefined
if (_isNundef(args)) throw new Error('fingerprinter doesnt allow undefined or null args')
// convert args to an array and digest them
return Utilities.base64EncodeWebSafe(
Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_1, args.map(d => {
return _isObject(d) ? (_isDate(d) ? d.getTime() : JSON.stringify(d)) : (_isNundef(d) ? '_nundef_' : d.toString());
}).join("-"), Utilities.Charset.UTF_8));
};
// all about digests for checking for fiddler dirtiness
const _dirtyList = new Map()
// this means digest all data
_dirtyList.set('all', {
columnNames: null,
fingerprint: null,
name: 'all'
})
const _checkDirtyWatch = (name) => {
if (!_dirtyList.has(name)) {
throw new Error(`${name} doesnt exist as a dirtywatch`)
}
return _dirtyList.get(name)
}
/**
* @param {string} name the name to give this dirty list
* @param {string[]} columnNames the names of the column it applies to
* @return {object} self
*/
self.setDirtyWatch = (name, columnNames) => {
// replacing is allowed
_dirtyList.set(name, {
columnNames: _patchColumnNames(columnNames),
fingerprint: null,
name
})
// set the current fingerprint
_dirtyList.get(name).fingerprint = self.getFingerprint(name)
return self
}
/**
* @param {string} name the name to give this dirty list
* @return {string[]} the columnnames as an array
*/
self.getDirtyWatch = (name = 'all') => _dirtyList.get(name)
/**
* gets a fingerprint for a collection of columns
* @param {string} [name] the dirtywatch name
* @return
*/
self.getFingerprint = (name = 'all') => {
const ob = _checkDirtyWatch(name)
if (self.isEmpty()) return null
// we need the headerOb as well since column positions may have swapped
return !ob.columnNames ?
self.fingerprinter(_dataOb, _headerOb) :
self.fingerprinter(ob.columnNames.map(f => ({
values: self.getColumnValues(f),
header: _headerOb[f]
})))
}
/**
* updates all the fingerprints - should be done when the fiddler data is reset or initialized
* so the rules are
* when a fiddler is created it's empty, and its fingerprint is null
* getFingerprint on an empty will always return null
* setData && setValues (or resetfingerprints directly) are the only way to reset it to a new value
* that new value becomes the new initial fingerprint
*
* @return {object} self
*/
const _resetFingerprints = () => {
for (let [key, value] of _dirtyList) {
value.fingerprint = self.getFingerprint(key)
}
}
/**
* gets a initial for a collection of columns from when the fiddler was first populated
* @param {string} [name] the dirtywatch name
* @return
*/
self.getInitialFingerprint = (name) => self.getDirtyWatch(name).fingerprint
/**
* checks if the fiddler is dirty
* @param {string} [name] see if the fiddler or certain columns are dirty
* @return {Boolean} whether its dirty
*/
self.isDirty = (name = 'all') => {
const ob = _checkDirtyWatch(name)
return ob.fingerprint !== self.getFingerprint(name) && !_isNull(ob.fingerprint)
}
/**
* @param {Sheet} sheet
*/
self.setSheet = function (sheet) {
_sheet = sheet;
return self;
};
/**
* @return {Sheet} sheet
*/
self.getSheet = function () {
return _sheet;
};
/// ITERATION FUNCTIONS
/**
* iterate through each row - given a specific column
* @param {string} name the column name
* @param {function} [func] optional function that shoud true or false if selected
* @return {number[]} matching row numbers
*/
self.selectRows = function (name, func) {
var values = self.getColumnValues(name);
var columnIndex = self.getHeaders().indexOf(name);
var result = [];
// add index if function returns true
values.forEach(function (d, i) {
if ((checkAFunc(func) || _functions.selectRows)(d, {
name: name,
data: _dataOb,
headers: _headerOb,
rowOffset: i,
columnOffset: columnIndex,
values: values,
row: _dataOb[i],
fiddler: self
})) result.push(i);
});
return result;
};
/**
* iterate through each row - nodifies the data in this fiddler instance
* @param {function} [func] optional function that shoud return a new row if changes made
* @return {Fiddler} self
*/
self.mapRows = function (func) {
_dataOb = _dataOb.map(function (row, rowIndex) {
var rowLength = Object.keys(row).length;
var result = (checkAFunc(func) || _functions.mapRows)(row, {
name: rowIndex,
data: _dataOb,
headers: _headerOb,
rowOffset: rowIndex,
columnOffset: 0,
values: self.getHeaders().map(function (k) {
return row[k];
}),
row: row,
rowFormulas: _formulaOb && _formulaOb[rowIndex],
fiddler: self
});
if (!result || typeof result !== "object") {
throw new Error("you need to return the row object - did you forget?");
}
if (Object.keys(result).length !== rowLength) {
throw new Error(
'you cant change the number of columns in a row during map items'
);
}
return result;
});
return self;
};
self.setRenameDups = function (rename) {
_renameDups = rename;
return self;
};
self.setRenameBlanks = function (rename) {
_renameBlanks = rename;
return self;
};
self.setBlankOffset = function (off) {
_blankOffset = off;
return self;
};
/**
* get the unique values in a column
* @param {string} columnName
* @param {function} [compareFunc]
* @return {[*]} array of unique values
*/
self.getUniqueValues = function (columnName, compareFunc) {
return self.getColumnValues(columnName)
.filter(function (d, i, a) {
return axof_(d, a, compareFunc) === i;
});
};
// like indexof except with custom compare
function axof_(value, arr, compareFunc) {
var cf = checkAFunc(compareFunc) || _functions.compareFunc;
for (var i = 0; i < arr.length; i++) {
if (cf(value, arr[i])) return i;
}
return -1;
}
/**
* iterate through each row - nodifies the data in this fiddler instance
* @param {[string]} [columnNames] optional which column names to use (default is all)
* @param {boolean} [keepLast=false] whether to keep the last row or the first found
* @param {function} [compareFunc] compare values function
* @return {Fiddler} self
*/
self.filterUnique = function (columnNames, keepLast, compareFunc) {
var headers = self.getHeaders();
cols = _forceArray(columnNames || headers);
// may need to reverse
var data = _dataOb.slice();
// check params are valid
if (cols.some(function (d) {
return headers.indexOf(d) === -1;
})) {
throw 'unknown columns in ' + JSON.stringify(cols) + ' compared to ' + JSON.stringify(headers);
}
// filter out dups
data = data.filter(function (d, i, a) {
// if we're keeping the first one, then keep only if there's none before
// if the last one, then keep only if there are none following
var soFar = keepLast ? a.slice(i + 1) : a.slice(0, i);
return !soFar.some(function (e) {
return cols.every(function (f) {
return (checkAFunc(compareFunc) || _functions.compareFunc)(d[f], e[f]);
});
});
});
// register
_dataOb = data;
return self;
};
/**
* set header format
* @param {object} headerFormat {backgrounds:'string',fontColors:'string',wraps:boolean,fontWeights:'string'}
* @return self
*/
self.setHeaderFormat = function (headerFormat) {
_headerFormat = headerFormat;
return self;
};
/**
* sort out a list of column names and throw if any invalid
* @param {string[]} [columnNames] can be an array, single or undefined for all
* @return {string[]} an array of column names
*/
function _patchColumnNames(columnNames) {
// undefined columnNames means them all
// names can be a single column or an array
var headers = self.getHeaders();
columnNames = _isNundef(columnNames) ? headers : _forceArray(columnNames)
var bad = columnNames.filter(function (d) {
return headers.indexOf(d) === -1;
});
if (bad.length) throw "these columnNames don't exist " + bad.join(",");
return columnNames;
}
/**
* clear given column formats
*/
self.clearColumnFormats = function (columnNames) {
_columnFormats = _columnFormats || {};
_patchColumnNames(columnNames)
.forEach(function (d) {
_columnFormats[d] = null;
});
return self;
};
/**
* get all known columnFormats
*/
self.getColumnFormats = function () {
return _columnFormats;
};
/**
* set tidy formats
* @param {boolean} tidyFormats whether to tidy formats in space outside the data being written
* @return self
*/
self.setTidyFormats = function (tidyFormats) {
_tidyFormats = tidyFormats;
return self;
};
/**
* this can be handy for chaining
*/
self.getSelf = () => self
/**
* get tidy formats
* @return {boolean} tidyFormats whether to tidy formats in space outside the data being written
*/
self.getTidyFormats = function () {
return tidyFormats;
};
/**
* set column format
* @param {object} columnFormat eg{backgrounds:'string',fontColors:'string',wraps:boolean,fontWeights:'string'}
* @param {string[]} [columnNames=all] default is it applies to all current columns
* @return self
*/
self.setColumnFormat = function (columnFormat, columnNames) {
// validate them
columnNames = _patchColumnNames(columnNames);
// a non-null column format means we actually have an interest in columnformats
_columnFormats = _columnFormats || {};
// apply them
columnNames.forEach(function (d) { _columnFormats[d] = columnFormat });
return self;
};
/**
* set flatting options
* @param
* @return self
*/
self.setFlattener = function (options) {
flattenOptions_ = options;
return self;
};
/**
* get flattening options
* @param
* @return self
*/
self.getFlattener = function (options) {
return flattenOptions_;
};
/**
* applies formats
* @param {object} format eg .. {backgrounds:'string',fontColors:'string',wraps:boolean,fontWeights:'string'}
* @param {Range}
* @return {range}
*/
self.setFormats = function (range, format) {
// if there's anything to do
var atr = range.getNumRows();
var atc = range.getNumColumns();
if (atc && atr) {
// for every format mentioned
Object.keys(format).forEach(function (f) {
// check method exists and apply it
var method = 'set' + f.slice(0, 1).toUpperCase() + f.slice(1).replace(/s$/, "").replace(/ies$/, "y");
if (typeof range[method] !== "function") throw 'unknown format ' + method;
range[method](format[f]);
});
}
return self;
};
/**
* applies formats to a rangelist
* @param {object} format eg .. {backgrounds:'string',fontColors:'string',wraps:boolean,fontWeights:'string'}
* @param {Range} rangeList a rangelist
* @return {range}
*/
self.setRangelistFormat = function (rangeList, format) {
// if there's anything to do
if (rangeList) {
Object.keys(format).forEach(function (f) {
var method = 'set' + f.slice(0, 1).toUpperCase() + f.slice(1);
// patch in case its plural
// https://github.com/brucemcpherson/bmFiddler/issues/2 - v29
method = method.replace(/ies$/, "y").replace(/s$/, "");
if (typeof rangeList[method] !== "function") throw 'unknown format ' + method;
rangeList[method](format[f]);
})
}
return self;
};
/**
* apply header formats
* @param {Range} range the start range for the headers
* @param {object} [format= _headerFormat] the format object
* @return self;
*/
self.applyHeaderFormat = function (range, format) {
if (!self.getNumColumns()) return self;
format = format || _headerFormat;
var rangeList = self.makeRangeList([range.offset(0, 0, 1, self.getNumColumns())], { numberOfRows: 1 }, range.getSheet());
return self.setRangelistFormat(rangeList, _headerFormat);
};
/**
* apply column formats
* @param {Range} range the start range
* @return self;
*/
self.applyColumnFormats = function (range) {
var foCollect = [];
if (_columnFormats) {
// we'll need this later
var dr = range.getSheet().getDataRange();
var atr = dr.getNumRows();
/// make space for the header
if (self.hasHeaders() && atr > 1) {
dr = dr.offset(1, 0, atr - 1);
}
if (Object.keys(_columnFormats).length === 0) {
// this means clear format for entire thing
dr.clearFormat();
}
else {
// first clear the bottom part of the sheet with no data
var atr = dr.getNumRows();
if (atr > self.getNumRows() && self.getNumRows()) {
dr.offset(self.getNumRows() - atr, 0, atr - self.getNumRows()).clearFormat();
}
if (self.getNumRows()) {
Object.keys(_columnFormats)
.forEach(function (d) {
var o = _columnFormats[d];
// validate still exists
var h = self.getHeaders().indexOf(d);
if (h !== -1) {
// set the range for the data
var r = dr.offset(0, h, self.getNumRows(), 1);
if (!o) {
// its a clear
r.clearFormat();
}
else {
//self.setFormats (r, o);
foCollect.push({
format: o,
range: r
});
}
}
else {
// delete it as column is now gone
delete _columnFormats[d];
}
});
}
}
}
else {
// there;'s no formatting to do
}
// optimize the formatting
var foNew = foCollect.reduce(function (p, c) {
// index by the format being set
var sht = c.range.getSheet();
var sid = sht.getSheetId();
Object.keys(c.format)
.forEach(function (f) {
var key = f + "_" + c.format[f] + "_" + sid;
p[key] = p[key] || {
value: c.format[f],
format: f,
ranges: [],
sheet: sht
};
p[key].ranges.push(c.range);
})
return p;
}, {});
// now make rangelists and apply formats
Object.keys(foNew)
.forEach(function (d) {
var o = foNew[d];
// make the range list - they are all ont he same sheet
var sht = o.sheet;
var rangeList = sht.getRangeList(o.ranges.map(function (e) { return e.getA1Notation(); }));
// workout the method (could be pluralized)
var method = "set" + o.format.slice(0, 1).toUpperCase() + o.format.slice(1).replace(/s$/, "").replace(/ies$/, "y");
var t = {};
t[o.format] = o.value;
if (!rangeList[method]) {
// fall back to individual ranges
rangeList.getRanges()
.forEach(function (e) {
self.setFormats(e, t);
});
}
else {
rangeList[method](o.value);
}
});
return self;
}
/**
* get header format
* @return self
*/
self.getHeaderFormat = function () {
return _headerFormat;
};
/**
* iterate through each row - nodifies the data in this fiddler instance
* @param {function} [func] optional function that shoud return true if the row is to be kept
* @return {Fiddler} self
*/
self.filterRows = function (func) {
_dataOb = _dataOb.filter(function (row, rowIndex) {
return (checkAFunc(func) || _functions.filterRows)(row, {
name: rowIndex,
data: _dataOb,
headers: _headerOb,
rowOffset: rowIndex,
columnOffset: 0,
fiddler: self,
values: self.getHeaders().map(function (k) {
return row[k];
}),
row: row
});
});
return self;
};
/**
* mapSort
* @param {string} name column name
* @param {boolean} [descending=false] sort order
* @param {Fiddler} [auxFiddler] another fiddler to drive the sort
* @return {[object]} fiddler data sorted
*/
self.sort = function (name, descending, auxFiddler) {
if (self.getHeaders().indexOf(name) === -1) {
throw new Error(name + ' is not a valid header name');
}
return self.handySort(self.getData(), {
values: auxFiddler ? auxFiddler.getData() : null,
descending: descending,
extractFunction: function (values, a) {
return values[a][name];
}
});
};
/**
* sort returns sorted values
* for chaining , can be handy to return the fiddler
*/
self.sortFiddler = function (name, descending, auxFiddler) {
var data = self.sort(name, descending, auxFiddler);
// the true means we try to preserve the order of the original fiddler columns
// if possible - as self data would normally recreate them according to insert time
self.setData(data, true, false);
return self;
}
self.handySort = function (displayValues, options) {
// default comparitor & extractor
options = options || {};
var descending = options.descending || false;
var defaultExtract = function (values, a) {
return values[a];
};
var extractFunc = options.extractFunction || defaultExtract;
var compareFunc = options.compareFunc || function (a, b) {
return a > b ? 1 : (a === b ? 0 : -1);
};
// allow regular sorting too
var values = options.values || displayValues;
if (displayValues.length !== values.length) {
throw 'value arrays need to be same length';
}
return displayValues.map(function (d, i) {
// make an array of indices
return i;
})
.sort(function (a, b) {
// sort the according to values the point to
return compareFunc(
extractFunc(values, descending ? b : a), extractFunc(values, descending ? a : b)
);
})
.map(function (d) {
// reorder the tartget array according to index on the values
return displayValues[d];
});
}
/**
* iterate through each column - modifies the data in this fiddler instance
* @param {string} name the name of the column
* @param {function} [func] optional function that shoud return new column data
* @return {Fiddler} self
*/
self.mapColumn = function (name, func) {
var values = self.getColumnValues(name);
var columnIndex = self.getHeaders().indexOf(name);
values.forEach(function (value, rowIndex) {
_dataOb[rowIndex][name] = (checkAFunc(func) || _functions.mapColumns)(value, {
name: name,
data: _dataOb,
headers: _headerOb,
rowOffset: rowIndex,
columnOffset: columnIndex,
fiddler: self,
values: values,
row: _dataOb[rowIndex],
fiddler: self
});
});
return self;
};
/**
* iterate through each column - modifies the data in this fiddler instance
* @param {function} [func] optional function that shoud return new column data
* @return {Fiddler} self
*/
self.mapColumns = function (func) {
var columnWise = _columnWise();
const columnWiseFormula = _columnWiseFormula
var oKeys = Object.keys(columnWise);
oKeys.forEach(function (key, columnIndex) {
// so we can check for a change
var hold = columnWise[key].slice();
var result = (checkAFunc(func) || _functions.mapColumns)(columnWise[key], {
name: key,
data: _dataOb,
headers: _headerOb,
rowOffset: 0,
columnOffset: columnIndex,
fiddler: self,
values: columnWise[key],
formulas: columnWiseFormula && columnWiseFormula[key],
fiddler: self
});
// changed no of rows?
if (!result || result.length !== hold.length) {
throw new Error(
'you cant change the number of rows in a column during map items'
);
}
// need to zip through the dataOb and change to new column values
if (hold.join() !== result.join()) {
result.forEach(function (r, i) {
_dataOb[i][key] = r;
});
}
});
return self;
};
/**
* iterate through each header
* @param {function} [func] optional function that shoud return new column data
* @return {Fiddler} self
*/
self.mapHeaders = function (func) {
if (!self.hasHeaders()) {
throw new Error('this fiddler has no headers so you cant change them');
}
var columnWise = _columnWise();
var oKeys = Object.keys(columnWise);
var nKeys = [];
oKeys.forEach(function (key, columnIndex) {
var result = (checkAFunc(func) || _functions.mapHeaders)(key, {
name: key,
data: _dataOb,
headers: _headerOb,
rowOffset: 0,
columnOffset: columnIndex,
fiddler: self,
values: columnWise[key],
fiddler: self
});
// deleted the header
if (!result) {
throw new Error(
'header cant be blank'
);
}
nKeys.push(result);
});
// check for change
if (nKeys.join() !== oKeys.join()) {
_headerOb = {};
_dataOb = _dataOb.map(function (d) {
return oKeys.reduce(function (p, c) {
var idx = Object.keys(p).length;
_headerOb[nKeys[idx]] = idx;
p[nKeys[idx]] = d[c];
return p;
}, {});
});