-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv.js
More file actions
94 lines (74 loc) · 1.87 KB
/
Copy pathcsv.js
File metadata and controls
94 lines (74 loc) · 1.87 KB
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
/**
* Parse a string containing lines of comma-separated values into an array of records.
*
* @param {string} csv
* A string containing lines of comma-separated values.
*
* @returns {any[]} An array of records.
*/
function parse(
csv
) {
const rows = csv
.trim() // remove surrounding whitespace
.split('\n') // split string to lines
.map(e => e.trim()) // remove white spaces for each line
.map(e => e.split(',').map(e => e.trim()));
const keys = rows.shift();
const array = [];
for (const row of rows) {
const object = {};
for (const key of keys) {
value = row[keys.indexOf(key)];
try {
value = JSON.parse(value);
} catch {}
object[key] = value;
}
array.push(object);
}
return array;
}
/**
* Convert a value, or an array of values, into a string containing rows of comma-separated values.
*
* @param {any} value
* A value to convert into a string containing rows of comma-separated values.
*
* @returns {string}
* A string containing rows of comma-separated values.
*/
function stringify(
value
) {
// If the value is a function, stringify it.
if (typeof value === "function") return `"${value.toString().replaceAll("\"", "\\\"")}"`;
// If the value is not an object, stringify it.
if (typeof value !== "object") return JSON.stringify(value);
if (!(value instanceof Array)) {
return stringify( [ value ] );
}
let csv = "";
const array = value;
const object = array[0];
const keys = Object.keys(object);
csv += keys.map(key => key.includes(" ") ? JSON.stringify(key) : key).join(",") + "\n";
for (
let i = 0;
i < array.length;
i++
) {
keys.map(
key => csv += array[i][key] + ","
);
csv = csv.substring(0, csv.length - 1) + "\n";
}
return csv;
}
const CSV = Object.freeze(
{
parse,
stringify
}
);
module.exports = CSV;