[76] | 1 | d3.csv.parse = function(text) { |
---|
| 2 | var header; |
---|
| 3 | return d3.csv.parseRows(text, function(row, i) { |
---|
| 4 | if (i) { |
---|
| 5 | var o = {}, j = -1, m = header.length; |
---|
| 6 | while (++j < m) o[header[j]] = row[j]; |
---|
| 7 | return o; |
---|
| 8 | } else { |
---|
| 9 | header = row; |
---|
| 10 | return null; |
---|
| 11 | } |
---|
| 12 | }); |
---|
| 13 | }; |
---|
| 14 | |
---|
| 15 | d3.csv.parseRows = function(text, f) { |
---|
| 16 | var EOL = {}, // sentinel value for end-of-line |
---|
| 17 | EOF = {}, // sentinel value for end-of-file |
---|
| 18 | rows = [], // output rows |
---|
| 19 | re = /\r\n|[,\r\n]/g, // field separator regex |
---|
| 20 | n = 0, // the current line number |
---|
| 21 | t, // the current token |
---|
| 22 | eol; // is the current token followed by EOL? |
---|
| 23 | |
---|
| 24 | re.lastIndex = 0; // work-around bug in FF 3.6 |
---|
| 25 | |
---|
| 26 | /** @private Returns the next token. */ |
---|
| 27 | function token() { |
---|
| 28 | if (re.lastIndex === text.length) return EOF; // special case: end of file |
---|
| 29 | if (eol) { eol = false; return EOL; } // special case: end of line |
---|
| 30 | |
---|
| 31 | // special case: quotes |
---|
| 32 | var j = re.lastIndex; |
---|
| 33 | if (text.charCodeAt(j) === 34) { |
---|
| 34 | var i = j; |
---|
| 35 | while (i++ < text.length) { |
---|
| 36 | if (text.charCodeAt(i) === 34) { |
---|
| 37 | if (text.charCodeAt(i + 1) !== 34) break; |
---|
| 38 | i++; |
---|
| 39 | } |
---|
| 40 | } |
---|
| 41 | re.lastIndex = i + 2; |
---|
| 42 | var c = text.charCodeAt(i + 1); |
---|
| 43 | if (c === 13) { |
---|
| 44 | eol = true; |
---|
| 45 | if (text.charCodeAt(i + 2) === 10) re.lastIndex++; |
---|
| 46 | } else if (c === 10) { |
---|
| 47 | eol = true; |
---|
| 48 | } |
---|
| 49 | return text.substring(j + 1, i).replace(/""/g, "\""); |
---|
| 50 | } |
---|
| 51 | |
---|
| 52 | // common case |
---|
| 53 | var m = re.exec(text); |
---|
| 54 | if (m) { |
---|
| 55 | eol = m[0].charCodeAt(0) !== 44; |
---|
| 56 | return text.substring(j, m.index); |
---|
| 57 | } |
---|
| 58 | re.lastIndex = text.length; |
---|
| 59 | return text.substring(j); |
---|
| 60 | } |
---|
| 61 | |
---|
| 62 | while ((t = token()) !== EOF) { |
---|
| 63 | var a = []; |
---|
| 64 | while ((t !== EOL) && (t !== EOF)) { |
---|
| 65 | a.push(t); |
---|
| 66 | t = token(); |
---|
| 67 | } |
---|
| 68 | if (f && !(a = f(a, n++))) continue; |
---|
| 69 | rows.push(a); |
---|
| 70 | } |
---|
| 71 | |
---|
| 72 | return rows; |
---|
| 73 | }; |
---|