-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathCSV.ts
324 lines (309 loc) · 7.99 KB
/
CSV.ts
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
import { Parser } from './Parser';
import { Streamer } from './Streamer';
import {
Comma,
ForEachCallback,
LineBreak,
PristineInput,
Quote,
ReadAllCallback,
ReadCallback,
Value,
ParseOptions,
} from './types';
const EOL: LineBreak = '\r\n';
const SEPARATOR: Comma = ',';
const quoteCharReqex = new RegExp('"', 'g');
const specialCharReqex = new RegExp('["\r\n]', 'g');
const _shouldBeQuoted = (value: string, sep: string): boolean =>
value.search(specialCharReqex) >= 0 || value.includes(sep);
const _quoteIfRquired = (value: string, sep: string): string =>
_shouldBeQuoted(value, sep)
? '"' + value.replace(quoteCharReqex, '""') + '"'
: value;
const _stringifySingleValue = (item: PristineInput): string => {
if (item === 0) {
item = '0';
} else if (item === undefined || item === null) {
item = '';
}
if (typeof item != 'string') {
const s = item.toString();
if (s == '[object Object]') {
item = JSON.stringify(item);
if (item == '{}') {
item = '';
}
} else {
item = s;
}
}
return item;
};
const reducer = (
item: PristineInput,
memo: PristineInput | undefined,
sep: Comma,
prependSep?: boolean
): Value => {
item = _stringifySingleValue(item);
return (
(memo !== undefined || prependSep ? `${memo}${sep}` : '') +
_quoteIfRquired(item, sep)
);
};
const detect = (input: string): Comma => {
const separators = [',', ';', '|', '\t'];
const idx = separators
.map((separator) => input.indexOf(separator))
.reduce((prev, cur) =>
prev === -1 || (cur !== -1 && cur < prev) ? cur : prev
);
return (input[idx] || ',') as Comma;
};
const stringify = (input?: PristineInput, sep: Comma = SEPARATOR): string => {
let ret: string | undefined;
sep = sep || SEPARATOR;
if (Array.isArray(input)) {
if (input.length === 0) {
ret = EOL;
} else if (!Array.isArray(input[0])) {
for (let loop = 0; loop < input.length; loop++) {
ret = reducer(input[loop], ret, sep, loop > 0);
}
ret += EOL;
} else if (Array.isArray(input[0])) {
ret = input.map((item) => stringify(item, sep)).join('');
}
} else if (typeof input == 'object') {
for (const key in input) {
if (input.hasOwnProperty(key)) {
ret = reducer(input[key], ret, sep);
}
}
ret += EOL;
} else {
ret = reducer(input, ret, sep) + EOL;
}
return ret as string;
};
function parse(input: string, sep?: Comma, quo?: Quote): Value[][];
function parse(input: string, opts?: Partial<ParseOptions & { output: 'tuples' }>): Value[][];
function parse(
input: string,
opts: Partial<ParseOptions> & { output: 'objects' }
): { [k: string]: Value }[];
function parse(
input: string,
sepOrOpts?: Comma | Partial<ParseOptions>,
quo?: Quote
): Value[][] | { [k: string]: Value }[] {
// Create an options hash, using positional parameters or the passed in options hash for values
const opts: Partial<ParseOptions> = typeof sepOrOpts === "object" ? sepOrOpts : {};
if (typeof sepOrOpts === "string") {
opts.comma = sepOrOpts as Comma;
}
if (quo) {
opts.quote = quo as Quote;
}
// try to detect the separator if not provided
if (opts.comma === undefined) {
opts.comma = detect(input);
}
// Clean characters, if necessary
// TODO: We should probably throw an error here to signal bad input to the user
if (opts.comma) {
opts.comma = opts.comma[0] as Comma;
}
if (opts.quote) {
opts.quote = opts.quote[0] as Quote;
}
const csv = new Parser(input, opts.comma, opts.quote);
return csv.File(opts.output);
};
function read(input: string, callback: ReadCallback): number;
function read(input: string, sep: Comma, callback: ReadCallback): number;
function read(
input: string,
sep: Comma,
quo: Quote,
callback: ReadCallback
): number;
function read(
input: string,
sep: Comma | ReadCallback,
quo?: Quote | ReadCallback,
callback?: ReadCallback
): number {
if (callback === undefined) {
if (quo === undefined) {
// arguments.length < 3) {
if (typeof sep !== 'function') {
throw Error('Last/second argument is not a callback');
}
callback = sep;
sep = ',';
} else {
// arguments.length < 4) {
if (typeof quo !== 'function') {
throw Error('Last/third argument is not a callback');
}
callback = quo;
quo = '"';
}
}
const csv = new Parser(input, sep as Comma, quo as Quote);
const fields = csv.Row();
callback(fields);
return csv.pointer;
}
function forEach(input: string, callback: ForEachCallback): void;
function forEach(input: string, sep: Comma, callback: ForEachCallback): void;
function forEach(
input: string,
sep: Comma,
quo: Quote,
callback: ForEachCallback
): void;
function forEach(
input: string,
sep: Comma | ForEachCallback,
quo?: Quote | ForEachCallback,
callback?: ForEachCallback
): void {
if (callback === undefined) {
if (quo === undefined) {
// arguments.length < 3) {
if (typeof sep !== 'function') {
throw Error('Last/second argument is not a callback');
}
callback = sep;
sep = ',';
} else {
// arguments.length < 4) {
if (typeof quo !== 'function') {
throw Error('Last/third argument is not a callback');
}
callback = quo;
quo = '"';
}
}
let i = 0;
let s = 0;
let r: number;
while (
(r = read(input.slice(s), sep as Comma, quo as Quote, (fields) =>
(callback as ForEachCallback)(fields, i++)
))
) {
s += r;
}
}
function readAll(input: string, callback: ReadAllCallback): number;
function readAll(input: string, sep: Comma, callback: ReadAllCallback): number;
function readAll(
input: string,
sep: Comma,
quo: Quote,
callback: ReadAllCallback
): number;
function readAll(
input: string,
sep: Comma | ReadAllCallback,
quo?: Quote | ReadAllCallback,
callback?: ReadAllCallback
): number {
if (callback === undefined) {
if (quo === undefined) {
// arguments.length < 3) {
if (typeof sep !== 'function') {
throw Error('Last/second argument is not a callback');
}
callback = sep;
sep = ',';
} else {
// arguments.length < 4) {
if (typeof quo !== 'function') {
throw Error('Last/third argument is not a callback');
}
callback = quo;
quo = '"';
}
}
const csv = new Parser(input, sep as Comma, quo as Quote);
const rows = csv.File();
callback(rows);
return csv.pointer;
}
function readChunk(input: string, callback: ReadAllCallback): number;
function readChunk(
input: string,
sep: Comma,
callback: ReadAllCallback
): number;
function readChunk(
input: string,
sep: Comma,
quo: Quote,
callback: ReadAllCallback
): number;
function readChunk(
input: string,
sep: Comma | ReadAllCallback,
quo?: Quote | ReadAllCallback,
callback?: ReadAllCallback
): number {
if (callback === undefined) {
if (quo === undefined) {
// arguments.length < 3) {
if (typeof sep !== 'function') {
throw Error('Last/second argument is not a callback');
}
callback = sep;
sep = ',';
} else {
// arguments.length < 4) {
if (typeof quo !== 'function') {
throw Error('Last/third argument is not a callback');
}
callback = quo;
quo = '"';
}
}
const csv = new Parser(input, sep as Comma, quo as Quote);
const rows = csv.File();
let ret = 0;
if (csv.pointer < input.length) {
ret = csv.pointer;
} else {
rows.pop();
ret = csv.linePointer;
}
callback(rows);
return ret;
}
const fetch = (input: string, sep?: Comma, quo?: Quote): Value[] => {
// TODO
let output: Value[] | undefined;
read(input, sep as Comma, quo as Quote, (fields) => {
output = fields;
});
return output as Value[];
};
const createStream = (options?: {
separator?: Comma;
quote?: Quote;
}): Streamer => new Streamer(options);
export {
EOL as eol,
SEPARATOR as separator,
detect,
stringify,
parse,
read,
forEach,
readAll,
readChunk,
fetch,
createStream,
};