-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.csv.js
1027 lines (922 loc) · 32.9 KB
/
jquery.csv.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
/* eslint no-prototype-builtins: 0 */
/**
* jQuery-csv (jQuery Plugin)
*
* This document is licensed as free software under the terms of the
* MIT License: http://www.opensource.org/licenses/mit-license.php
*
* Acknowledgements:
* The original design and influence to implement this library as a jquery
* plugin is influenced by jquery-json (http://code.google.com/p/jquery-json/).
* If you're looking to use native JSON.Stringify but want additional backwards
* compatibility for browsers that don't support it, I highly recommend you
* check it out.
*
* A special thanks goes out to [email protected] for providing a lot of valuable
* feedback to the project including the core for the new FSM
* (Finite State Machine) parsers. If you're looking for a stable TSV parser
* be sure to take a look at jquery-tsv (http://code.google.com/p/jquery-tsv/).
* For legal purposes I'll include the "NO WARRANTY EXPRESSED OR IMPLIED.
* USE AT YOUR OWN RISK.". Which, in 'layman's terms' means, by using this
* library you are accepting responsibility if it breaks your code.
*
* Legal jargon aside, I will do my best to provide a useful and stable core
* that can effectively be built on.
*
* Copyrighted 2012 by Evan Plaice.
*/
RegExp.escape = function (s) {
return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
};
(function () {
'use strict'
let $
// to keep backwards compatibility
if (typeof jQuery !== 'undefined' && jQuery) {
$ = jQuery
} else {
$ = {}
}
/**
* jQuery.csv.defaults
* Encapsulates the method paramater defaults for the CSV plugin module.
*/
$.csv = {
defaults: {
separator: ',',
delimiter: '"',
headers: true
},
hooks: {
castToScalar: function (value, state) {
const hasDot = /\./
if (isNaN(value)) {
return value
} else {
if (hasDot.test(value)) {
return parseFloat(value)
} else {
const integer = parseInt(value)
if (isNaN(integer)) {
return null
} else {
return integer
}
}
}
}
},
parsers: {
parse: function (csv, options) {
// cache settings
const separator = options.separator
const delimiter = options.delimiter
// set initial state if it's missing
if (!options.state.rowNum) {
options.state.rowNum = 1
}
if (!options.state.colNum) {
options.state.colNum = 1
}
// clear initial state
const data = []
let entry = []
let state = 0
let value = ''
let exit = false
function endOfEntry () {
// reset the state
state = 0
value = ''
// if 'start' hasn't been met, don't output
if (options.start && options.state.rowNum < options.start) {
// update global state
entry = []
options.state.rowNum++
options.state.colNum = 1
return
}
if (options.onParseEntry === undefined) {
// onParseEntry hook not set
data.push(entry)
} else {
const hookVal = options.onParseEntry(entry, options.state) // onParseEntry Hook
// false skips the row, configurable through a hook
if (hookVal !== false) {
data.push(hookVal)
}
}
// console.log('entry:' + entry);
// cleanup
entry = []
// if 'end' is met, stop parsing
if (options.end && options.state.rowNum >= options.end) {
exit = true
}
// update global state
options.state.rowNum++
options.state.colNum = 1
}
function endOfValue () {
if (options.onParseValue === undefined) {
// onParseValue hook not set
entry.push(value)
} else if (options.headers && options.state.rowNum === 1) {
// don't onParseValue object headers
entry.push(value)
} else {
const hook = options.onParseValue(value, options.state) // onParseValue Hook
// false skips the row, configurable through a hook
if (hook !== false) {
entry.push(hook)
}
}
// console.log('value:' + value);
// reset the state
value = ''
state = 0
// update global state
options.state.colNum++
}
// escape regex-specific control chars
const escSeparator = RegExp.escape(separator)
const escDelimiter = RegExp.escape(delimiter)
// compile the regEx str using the custom delimiter/separator
let match = /(D|S|\r\n|\n|\r|[^DS\r\n]+)/
let matchSrc = match.source
matchSrc = matchSrc.replace(/S/g, escSeparator)
matchSrc = matchSrc.replace(/D/g, escDelimiter)
match = new RegExp(matchSrc, 'gm')
// put on your fancy pants...
// process control chars individually, use look-ahead on non-control chars
csv.replace(match, function (m0) {
if (exit) {
return
}
switch (state) {
// the start of a value
case 0:
// null last value
if (m0 === separator) {
value += ''
endOfValue()
break
}
// opening delimiter
if (m0 === delimiter) {
state = 1
break
}
// null last value
if (/^(\r\n|\n|\r)$/.test(m0)) {
endOfValue()
endOfEntry()
break
}
// un-delimited value
value += m0
state = 3
break
// delimited input
case 1:
// second delimiter? check further
if (m0 === delimiter) {
state = 2
break
}
// delimited data
value += m0
state = 1
break
// delimiter found in delimited input
case 2:
// escaped delimiter?
if (m0 === delimiter) {
value += m0
state = 1
break
}
// null value
if (m0 === separator) {
endOfValue()
break
}
// end of entry
if (/^(\r\n|\n|\r)$/.test(m0)) {
endOfValue()
endOfEntry()
break
}
// broken paser?
throw Error('CSVDataError: Illegal State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']')
// un-delimited input
case 3:
// null last value
if (m0 === separator) {
endOfValue()
break
}
// end of entry
if (/^(\r\n|\n|\r)$/.test(m0)) {
endOfValue()
endOfEntry()
break
}
if (m0 === delimiter) {
// non-compliant data
throw Error('CSVDataError: Illegal Quote [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']')
}
// broken parser?
throw Error('CSVDataError: Illegal Data [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']')
default:
// shenanigans
throw Error('CSVDataError: Unknown State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']')
}
// console.log('val:' + m0 + ' state:' + state);
})
// submit the last entry
// ignore null last line
if (entry.length !== 0) {
endOfValue()
endOfEntry()
}
return data
},
// a csv-specific line splitter
splitLines: function (csv, options) {
if (!csv) {
return undefined
}
options = options || {}
// cache settings
const separator = options.separator || $.csv.defaults.separator
const delimiter = options.delimiter || $.csv.defaults.delimiter
// set initial state if it's missing
options.state = options.state || {}
if (!options.state.rowNum) {
options.state.rowNum = 1
}
// clear initial state
const entries = []
let state = 0
let entry = ''
let exit = false
function endOfLine () {
// reset the state
state = 0
// if 'start' hasn't been met, don't output
if (options.start && options.state.rowNum < options.start) {
// update global state
entry = ''
options.state.rowNum++
return
}
if (options.onParseEntry === undefined) {
// onParseEntry hook not set
entries.push(entry)
} else {
const hookVal = options.onParseEntry(entry, options.state) // onParseEntry Hook
// false skips the row, configurable through a hook
if (hookVal !== false) {
entries.push(hookVal)
}
}
// cleanup
entry = ''
// if 'end' is met, stop parsing
if (options.end && options.state.rowNum >= options.end) {
exit = true
}
// update global state
options.state.rowNum++
}
// escape regex-specific control chars
const escSeparator = RegExp.escape(separator)
const escDelimiter = RegExp.escape(delimiter)
// compile the regEx str using the custom delimiter/separator
let match = /(D|S|\n|\r|[^DS\r\n]+)/
let matchSrc = match.source
matchSrc = matchSrc.replace(/S/g, escSeparator)
matchSrc = matchSrc.replace(/D/g, escDelimiter)
match = new RegExp(matchSrc, 'gm')
// put on your fancy pants...
// process control chars individually, use look-ahead on non-control chars
csv.replace(match, function (m0) {
if (exit) {
return
}
switch (state) {
// the start of a value/entry
case 0:
// null value
if (m0 === separator) {
entry += m0
state = 0
break
}
// opening delimiter
if (m0 === delimiter) {
entry += m0
state = 1
break
}
// end of line
if (m0 === '\n') {
endOfLine()
break
}
// phantom carriage return
if (/^\r$/.test(m0)) {
break
}
// un-delimit value
entry += m0
state = 3
break
// delimited input
case 1:
// second delimiter? check further
if (m0 === delimiter) {
entry += m0
state = 2
break
}
// delimited data
entry += m0
state = 1
break
// delimiter found in delimited input
case 2: {
// escaped delimiter?
const prevChar = entry.substr(entry.length - 1)
if (m0 === delimiter && prevChar === delimiter) {
entry += m0
state = 1
break
}
// end of value
if (m0 === separator) {
entry += m0
state = 0
break
}
// end of line
if (m0 === '\n') {
endOfLine()
break
}
// phantom carriage return
if (m0 === '\r') {
break
}
// broken paser?
throw Error('CSVDataError: Illegal state [Row:' + options.state.rowNum + ']')
}
// un-delimited input
case 3:
// null value
if (m0 === separator) {
entry += m0
state = 0
break
}
// end of line
if (m0 === '\n') {
endOfLine()
break
}
// phantom carriage return
if (m0 === '\r') {
break
}
// non-compliant data
if (m0 === delimiter) {
throw Error('CSVDataError: Illegal quote [Row:' + options.state.rowNum + ']')
}
// broken parser?
throw Error('CSVDataError: Illegal state [Row:' + options.state.rowNum + ']')
default:
// shenanigans
throw Error('CSVDataError: Unknown state [Row:' + options.state.rowNum + ']')
}
// console.log('val:' + m0 + ' state:' + state);
})
// submit the last entry
// ignore null last line
if (entry !== '') {
endOfLine()
}
return entries
},
// a csv entry parser
parseEntry: function (csv, options) {
// cache settings
const separator = options.separator
const delimiter = options.delimiter
// set initial state if it's missing
if (!options.state.rowNum) {
options.state.rowNum = 1
}
if (!options.state.colNum) {
options.state.colNum = 1
}
// clear initial state
const entry = []
let state = 0
let value = ''
function endOfValue () {
if (options.onParseValue === undefined) {
// onParseValue hook not set
entry.push(value)
} else {
const hook = options.onParseValue(value, options.state) // onParseValue Hook
// false skips the value, configurable through a hook
if (hook !== false) {
entry.push(hook)
}
}
// reset the state
value = ''
state = 0
// update global state
options.state.colNum++
}
// checked for a cached regEx first
if (!options.match) {
// escape regex-specific control chars
const escSeparator = RegExp.escape(separator)
const escDelimiter = RegExp.escape(delimiter)
// compile the regEx str using the custom delimiter/separator
const match = /(D|S|\n|\r|[^DS\r\n]+)/
let matchSrc = match.source
matchSrc = matchSrc.replace(/S/g, escSeparator)
matchSrc = matchSrc.replace(/D/g, escDelimiter)
options.match = new RegExp(matchSrc, 'gm')
}
// put on your fancy pants...
// process control chars individually, use look-ahead on non-control chars
csv.replace(options.match, function (m0) {
switch (state) {
// the start of a value
case 0:
// null last value
if (m0 === separator) {
value += ''
endOfValue()
break
}
// opening delimiter
if (m0 === delimiter) {
state = 1
break
}
// skip un-delimited new-lines
if (m0 === '\n' || m0 === '\r') {
break
}
// un-delimited value
value += m0
state = 3
break
// delimited input
case 1:
// second delimiter? check further
if (m0 === delimiter) {
state = 2
break
}
// delimited data
value += m0
state = 1
break
// delimiter found in delimited input
case 2:
// escaped delimiter?
if (m0 === delimiter) {
value += m0
state = 1
break
}
// null value
if (m0 === separator) {
endOfValue()
break
}
// skip un-delimited new-lines
if (m0 === '\n' || m0 === '\r') {
break
}
// broken paser?
throw Error('CSVDataError: Illegal State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']')
// un-delimited input
case 3:
// null last value
if (m0 === separator) {
endOfValue()
break
}
// skip un-delimited new-lines
if (m0 === '\n' || m0 === '\r') {
break
}
// non-compliant data
if (m0 === delimiter) {
throw Error('CSVDataError: Illegal Quote [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']')
}
// broken parser?
throw Error('CSVDataError: Illegal Data [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']')
default:
// shenanigans
throw Error('CSVDataError: Unknown State [Row:' + options.state.rowNum + '][Col:' + options.state.colNum + ']')
}
// console.log('val:' + m0 + ' state:' + state);
})
// submit the last value
endOfValue()
return entry
}
},
helpers: {
/**
* $.csv.helpers.collectPropertyNames(objectsArray)
* Collects all unique property names from all passed objects.
*
* @param {Array} objects Objects to collect properties from.
*
* Returns an array of property names (array will be empty,
* if objects have no own properties).
*/
collectPropertyNames: function (objects) {
let o = []
let propName = []
const props = []
for (o in objects) {
for (propName in objects[o]) {
if ((objects[o].hasOwnProperty(propName)) &&
(props.indexOf(propName) < 0) &&
(typeof objects[o][propName] !== 'function')) {
props.push(propName)
}
}
}
return props
}
},
/**
* $.csv.toArray(csv)
* Converts a CSV entry string to a javascript array.
*
* @param {Array} csv The string containing the CSV data.
* @param {Object} [options] An object containing user-defined options.
* @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
* @param {Character} [delimiter] An override for the delimiter character. Defaults to a double-quote(").
*
* This method deals with simple CSV strings only. It's useful if you only
* need to parse a single entry. If you need to parse more than one line,
* use $.csv2Array instead.
*/
toArray: function (csv, options, callback) {
// if callback was passed to options swap callback with options
if (options !== undefined && typeof (options) === 'function') {
if (callback !== undefined) {
return console.error('You cannot 3 arguments with the 2nd argument being a function')
}
callback = options
options = {}
}
options = (options !== undefined ? options : {})
const config = {}
config.callback = ((callback !== undefined && typeof (callback) === 'function') ? callback : false)
config.separator = 'separator' in options ? options.separator : $.csv.defaults.separator
config.delimiter = 'delimiter' in options ? options.delimiter : $.csv.defaults.delimiter
const state = (options.state !== undefined ? options.state : {})
// setup
options = {
delimiter: config.delimiter,
separator: config.separator,
onParseEntry: options.onParseEntry,
onParseValue: options.onParseValue,
state: state
}
const entry = $.csv.parsers.parseEntry(csv, options)
// push the value to a callback if one is defined
if (!config.callback) {
return entry
} else {
config.callback('', entry)
}
},
/**
* $.csv.toArrays(csv)
* Converts a CSV string to a javascript array.
*
* @param {String} csv The string containing the raw CSV data.
* @param {Object} [options] An object containing user-defined options.
* @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
* @param {Character} [delimiter] An override for the delimiter character. Defaults to a double-quote(").
*
* This method deals with multi-line CSV. The breakdown is simple. The first
* dimension of the array represents the line (or entry/row) while the second
* dimension contains the values (or values/columns).
*/
toArrays: function (csv, options, callback) {
// if callback was passed to options swap callback with options
if (options !== undefined && typeof (options) === 'function') {
if (callback !== undefined) {
return console.error('You cannot 3 arguments with the 2nd argument being a function')
}
callback = options
options = {}
}
options = (options !== undefined ? options : {})
const config = {}
config.callback = ((callback !== undefined && typeof (callback) === 'function') ? callback : false)
config.separator = 'separator' in options ? options.separator : $.csv.defaults.separator
config.delimiter = 'delimiter' in options ? options.delimiter : $.csv.defaults.delimiter
// setup
let data = []
options = {
delimiter: config.delimiter,
separator: config.separator,
onPreParse: options.onPreParse,
onParseEntry: options.onParseEntry,
onParseValue: options.onParseValue,
onPostParse: options.onPostParse,
start: options.start,
end: options.end,
state: {
rowNum: 1,
colNum: 1
}
}
// onPreParse hook
if (options.onPreParse !== undefined) {
csv = options.onPreParse(csv, options.state)
}
// parse the data
data = $.csv.parsers.parse(csv, options)
// onPostParse hook
if (options.onPostParse !== undefined) {
data = options.onPostParse(data, options.state)
}
// push the value to a callback if one is defined
if (!config.callback) {
return data
} else {
config.callback('', data)
}
},
/**
* $.csv.toObjects(csv)
* Converts a CSV string to a javascript object.
* @param {String} csv The string containing the raw CSV data.
* @param {Object} [options] An object containing user-defined options.
* @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
* @param {Character} [delimiter] An override for the delimiter character. Defaults to a double-quote(").
* @param {Boolean} [headers] Indicates whether the data contains a header line. Defaults to true.
*
* This method deals with multi-line CSV strings. Where the headers line is
* used as the key for each value per entry.
*/
toObjects: function (csv, options, callback) {
// if callback was passed to options swap callback with options
if (options !== undefined && typeof (options) === 'function') {
if (callback !== undefined) {
return console.error('You cannot 3 arguments with the 2nd argument being a function')
}
callback = options
options = {}
}
options = (options !== undefined ? options : {})
const config = {}
config.callback = ((callback !== undefined && typeof (callback) === 'function') ? callback : false)
config.separator = 'separator' in options ? options.separator : $.csv.defaults.separator
config.delimiter = 'delimiter' in options ? options.delimiter : $.csv.defaults.delimiter
config.headers = 'headers' in options ? options.headers : $.csv.defaults.headers
options.start = 'start' in options ? options.start : 1
// account for headers
if (config.headers) {
options.start++
}
if (options.end && config.headers) {
options.end++
}
// setup
let lines = []
let data = []
options = {
delimiter: config.delimiter,
separator: config.separator,
onPreParse: options.onPreParse,
onParseEntry: options.onParseEntry,
onParseValue: options.onParseValue,
onPostParse: options.onPostParse,
start: options.start,
end: options.end,
state: {
rowNum: 1,
colNum: 1
},
match: false,
transform: options.transform
}
// fetch the headers
const headerOptions = {
delimiter: config.delimiter,
separator: config.separator,
start: 1,
end: 1,
state: {
rowNum: 1,
colNum: 1
},
headers: true
}
// onPreParse hook
if (options.onPreParse !== undefined) {
csv = options.onPreParse(csv, options.state)
}
// parse the csv
const headerLine = $.csv.parsers.splitLines(csv, headerOptions)
const headers = $.csv.toArray(headerLine[0], headerOptions)
// fetch the data
lines = $.csv.parsers.splitLines(csv, options)
// reset the state for re-use
options.state.colNum = 1
if (headers) {
options.state.rowNum = 2
} else {
options.state.rowNum = 1
}
// convert data to objects
for (let i = 0, len = lines.length; i < len; i++) {
const entry = $.csv.toArray(lines[i], options)
const object = {}
for (let j = 0; j < headers.length; j++) {
object[headers[j]] = entry[j]
}
if (options.transform !== undefined) {
data.push(options.transform.call(undefined, object))
} else {
data.push(object)
}
// update row state
options.state.rowNum++
}
// onPostParse hook
if (options.onPostParse !== undefined) {
data = options.onPostParse(data, options.state)
}
// push the value to a callback if one is defined
if (!config.callback) {
return data
} else {
config.callback('', data)
}
},
/**
* $.csv.fromArrays(arrays)
* Converts a javascript array to a CSV String.
*
* @param {Array} arrays An array containing an array of CSV entries.
* @param {Object} [options] An object containing user-defined options.
* @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
* @param {Character} [delimiter] An override for the delimiter character. Defaults to a double-quote(").
*
* This method generates a CSV file from an array of arrays (representing entries).
*/
fromArrays: function (arrays, options, callback) {
// if callback was passed to options swap callback with options
if (options !== undefined && typeof (options) === 'function') {
if (callback !== undefined) {
return console.error('You cannot 3 arguments with the 2nd argument being a function')
}
callback = options
options = {}
}
options = (options !== undefined ? options : {})
const config = {}
config.callback = ((callback !== undefined && typeof (callback) === 'function') ? callback : false)
config.separator = 'separator' in options ? options.separator : $.csv.defaults.separator
config.delimiter = 'delimiter' in options ? options.delimiter : $.csv.defaults.delimiter
let output = ''
for (let i = 0; i < arrays.length; i++) {
const line = arrays[i]
const lineValues = []
for (let j = 0; j < line.length; j++) {
let strValue = (line[j] === undefined || line[j] === null) ? '' : line[j].toString()
if (strValue.indexOf(config.delimiter) > -1) {
strValue = strValue.replace(new RegExp(config.delimiter, 'g'), config.delimiter + config.delimiter)
}
let escMatcher = '\n|\r|S|D'
escMatcher = escMatcher.replace('S', config.separator)
escMatcher = escMatcher.replace('D', config.delimiter)
if (strValue.search(escMatcher) > -1) {
strValue = config.delimiter + strValue + config.delimiter
}
lineValues.push(strValue)
}
output += lineValues.join(config.separator) + '\n'
}
// push the value to a callback if one is defined
if (!config.callback) {
return output
} else {
config.callback('', output)
}
},
/**
* $.csv.fromObjects(objects)
* Converts a javascript dictionary to a CSV string.
*
* @param {Object} objects An array of objects containing the data.
* @param {Object} [options] An object containing user-defined options.
* @param {Character} [separator] An override for the separator character. Defaults to a comma(,).
* @param {Character} [delimiter] An override for the delimiter character. Defaults to a double-quote(").
* @param {Character} [sortOrder] Sort order of columns (named after
* object properties). Use 'alpha' for alphabetic. Default is 'declare',
* which means, that properties will _probably_ appear in order they were
* declared for the object. But without any guarantee.
* @param {Character or Array} [manualOrder] Manually order columns. May be
* a strin in a same csv format as an output or an array of header names
* (array items won't be parsed). All the properties, not present in
* `manualOrder` will be appended to the end in accordance with `sortOrder`
* option. So the `manualOrder` always takes preference, if present.
*
* This method generates a CSV file from an array of objects (name:value pairs).
* It starts by detecting the headers and adding them as the first line of
* the CSV file, followed by a structured dump of the data.
*/
fromObjects: function (objects, options, callback) {
// if callback was passed to options swap callback with options
if (options !== undefined && typeof (options) === 'function') {
if (callback !== undefined) {
return console.error('You cannot 3 arguments with the 2nd argument being a function')
}
callback = options
options = {}
}
options = (options !== undefined ? options : {})
const config = {}
config.callback = ((callback !== undefined && typeof (callback) === 'function') ? callback : false)
config.separator = 'separator' in options ? options.separator : $.csv.defaults.separator
config.delimiter = 'delimiter' in options ? options.delimiter : $.csv.defaults.delimiter
config.headers = 'headers' in options ? options.headers : $.csv.defaults.headers
config.sortOrder = 'sortOrder' in options ? options.sortOrder : 'declare'
config.manualOrder = 'manualOrder' in options ? options.manualOrder : []
config.transform = options.transform
if (typeof config.manualOrder === 'string') {
config.manualOrder = $.csv.toArray(config.manualOrder, config)
}
if (config.transform !== undefined) {
const origObjects = objects
objects = []
for (let i = 0; i < origObjects.length; i++) {
objects.push(config.transform.call(undefined, origObjects[i]))
}
}
let props = $.csv.helpers.collectPropertyNames(objects)
if (config.sortOrder === 'alpha') {
props.sort()
}
if (config.manualOrder.length > 0) {
const propsManual = [].concat(config.manualOrder)
for (let p = 0; p < props.length; p++) {
if (propsManual.indexOf(props[p]) < 0) {
propsManual.push(props[p])
}
}
props = propsManual
}
let line
const output = []
let propName
if (config.headers) {
output.push(props)
}
for (let o = 0; o < objects.length; o++) {
line = []