UNPKG

2.08 kBJavaScriptView Raw
1
2/*
3 * https://tools.ietf.org/html/rfc4180
4 *
5 * 6. Fields containing line breaks (CRLF), double quotes, and commas
6 should be enclosed in double-quotes. For example:
7
8 "aaa","b CRLF
9 bb","ccc" CRLF
10 zzz,yyy,xxx
11
12 7. If double-quotes are used to enclose fields, then a double-quote
13 appearing inside a field must be escaped by preceding it with
14 another double quote. For example:
15
16 "aaa","b""bb","ccc"
17 */
18
19
20!function(exports) {
21 exports.encode = encode
22 exports.decode = decode
23
24 require("./json")
25 var re = /"((?:""|[^"])*)"|[^",\n\r]+|,|\r?\n/g
26
27 function encode(obj, _opts) {
28 var opts = _opts || {}
29 , re = opts.re || /[",\r\n]/
30 , escRe = opts.esc || /"/g
31 , escVal = opts.escVal || "\"\""
32 , arr = Array.isArray(obj) ? obj : [ obj ]
33 , keys = opts.select ? opts.select.replace(/\[[^\]]+?\]/g, "").split(",") : Object.keys(arr[0])
34
35 arr = arr.map(function(obj) {
36 return keys.map(function(key) {
37 var value = JSON.get(obj, key)
38 if (Array.isArray(value)) value = value.join(";")
39 return (
40 value == null ? opts.NULL : // jshint ignore:line
41 re.test(value += "") ? "\"" + value.replace(escRe, escVal) + "\"" :
42 value
43 )
44 }).join(opts.delimiter)
45 })
46 if (opts.header === "present") {
47 arr.unshift((opts.fields ? opts.fields.split(",") : keys).join(opts.delimiter))
48 }
49 return (opts.prefix || "") + arr.join(opts.br) + (opts.postfix || "")
50 }
51
52 function decode(str, _opts) {
53 var m
54 , opts = _opts || {}
55 , row = []
56 , head = row
57 , arr = []
58 , i = 0
59
60 if (opts.header !== "present") {
61 head = opts.fields ? opts.fields.split(",") : null
62 row = arr[0] = head === null ? [] : {}
63 }
64
65 for (; m = re.exec(str); ) {
66 if (m[0] === "\n" || m[0] === "\r\n") {
67 arr.push(row = head === null ? [] : {})
68 i = 0
69 } else if (m[0] === ",") {
70 i++
71 } else {
72 row[
73 head !== null && head !== row ? head[i] : i
74 ] = typeof m[1] === "string" ? m[1].replace(/""/g, "\"") : m[0]
75 }
76 }
77 if (i === 0) arr.length -= 1
78
79 return arr
80 }
81}(this) // jshint ignore:line
82
83