Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.

Commit c12a579

Browse files
committed
Update CSV parsing example.
1 parent 614de5c commit c12a579

File tree

4 files changed

+13
-20
lines changed

4 files changed

+13
-20
lines changed

csv-parsing/csv-parsing.js

+13-17
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,20 @@
1-
process.stdin.resume();
2-
process.stdin.setEncoding('utf8');
1+
// Elegant solution using built-in JavaScript functions
2+
var parseCSV = function (csv) {
3+
return JSON.parse('[' + csv + ']');
4+
};
35

4-
var data = '';
5-
6-
process.stdin.on('data', function (chunk) {
7-
data += chunk;
8-
});
9-
10-
process.stdin.on('end', function () {
11-
var csv = data.trim(),
12-
isNumber = false,
6+
// Crazy parser which was the original solution
7+
var parseCSV = function (csv) {
8+
var isNumber = false,
139
isInput = false,
1410
curr = '',
1511
stack = [],
12+
i = 0,
1613
char,
1714
pushStack;
1815

16+
csv = csv.trim();
17+
1918
pushStack = function (input) {
2019
isNumber && (input = +input);
2120
// Resets
@@ -25,7 +24,7 @@ process.stdin.on('end', function () {
2524
stack.push(input);
2625
};
2726

28-
while (char = csv.charAt(0)) {
27+
while (char = csv.charAt(i++)) {
2928
if (char === '"') {
3029
isInput = !curr;
3130
} else if (char === ',') {
@@ -42,13 +41,10 @@ process.stdin.on('end', function () {
4241
if (isNumber || !isInput) { throw new Error('Unexpected character'); }
4342
curr += char;
4443
}
45-
csv = csv.substr(1);
4644
}
4745

4846
// Push the trailing entry
4947
pushStack(curr);
5048

51-
stack.forEach(function (output) {
52-
console.log(JSON.stringify(output));
53-
});
54-
});
49+
return stack;
50+
};

csv-parsing/input-1.csv

-1
This file was deleted.

csv-parsing/input-2.csv

-1
This file was deleted.

csv-parsing/input-3.csv

-1
This file was deleted.

0 commit comments

Comments
 (0)