aboutsummaryrefslogtreecommitdiffstats
path: root/csv-parse.mjs
diff options
context:
space:
mode:
authorBrian Cully <bjc@spork.org>2025-07-16 19:18:50 -0400
committerBrian Cully <bjc@spork.org>2025-07-16 19:18:50 -0400
commit9e14963bad67ab2c640e98bb2148635b551727ae (patch)
tree70b24908063e21cf6f1ff133d713a338005109d3 /csv-parse.mjs
parente1a9e10902de4d927f4c2c87b6c27e6303fa1ead (diff)
downloadpnit-9e14963bad67ab2c640e98bb2148635b551727ae.tar.gz
pnit-9e14963bad67ab2c640e98bb2148635b551727ae.zip
add csv download
Diffstat (limited to 'csv-parse.mjs')
-rw-r--r--csv-parse.mjs79
1 files changed, 79 insertions, 0 deletions
diff --git a/csv-parse.mjs b/csv-parse.mjs
new file mode 100644
index 0000000..b096ab4
--- /dev/null
+++ b/csv-parse.mjs
@@ -0,0 +1,79 @@
+export default class {
+ constructor() {
+ this.state = this.awaitingTokenOrComma;
+ this.inProgress = '';
+ this._rowResults = [];
+ this._results = [];
+ }
+
+ push(c) {
+ this.state(c);
+ }
+
+ get results() {
+ return this._results.concat([this._rowResults.concat([this.inProgress])]);
+ }
+
+ awaitingTokenOrComma(c) {
+ switch (c) {
+ case ',':
+ // empty column
+ this._rowResults.push('');
+ break;
+ case '\n':
+ this._results.push(this._rowResults);
+ this._rowResults = [];
+ break;
+ default:
+ if (/\s/.test(c)) {
+ return;
+ }
+ this.inProgress += c;
+ this.state = this.awaitingComma;
+ }
+ }
+
+ awaitingComma(c) {
+ switch (c) {
+ case ',':
+ this._rowResults.push(this.inProgress);
+ this.inProgress = '';
+ this.state = this.awaitingTokenOrComma;
+ break;
+ case '\r':
+ break;
+ case '\n':
+ this._results.push(this._rowResults.concat(this.inProgress));
+ this._rowResults = [];
+ this.inProgress = '';
+ this.state = this.awaitingTokenOrComma;
+ break;
+ case '"':
+ this.state = this.checkForDoubleQuote;
+ break;
+ default:
+ this.inProgress += c;
+ }
+ }
+
+ checkForDoubleQuote(c) {
+ this.inProgress += c
+ switch (c) {
+ case '"':
+ this.state = this.awaitingComma;
+ break;
+ default:
+ this.state = this.awaitingQuote;
+ }
+ }
+
+ awaitingQuote(c) {
+ switch (c) {
+ case '"':
+ this.state = this.awaitingComma;
+ break;
+ default:
+ this.inProgress += c;
+ }
+ }
+}