From 9e14963bad67ab2c640e98bb2148635b551727ae Mon Sep 17 00:00:00 2001 From: Brian Cully Date: Wed, 16 Jul 2025 19:18:50 -0400 Subject: add csv download --- csv-parse.mjs | 79 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 csv-parse.mjs (limited to 'csv-parse.mjs') 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; + } + } +} -- cgit v1.3