aboutsummaryrefslogtreecommitdiffstats
path: root/csv.mjs
blob: b096ab423a137600c7357366750d86962d8dd5ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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;
        }
    }
}