UNPKG

@stordata/grammars

Version:

A collection of ANTLR grammars used at Stordata. This project exists so that we can package the grammars (and various utilities) as a CommonJS module. The `antlr4` Javascript runtime is only available as an ES module at the time of writing.

49 lines (35 loc) 877 B
import CSVVisitor from '../../generated/src/grammars/CSVVisitor.js'; export default class CSVParserVisitor extends CSVVisitor { constructor() { super(); this.lines = []; this.headers = []; this.delimiter = ''; } visitAll(ctx) { super.visitAll(ctx); return { lines: this.lines, headers: this.headers, delimiter: this.delimiter }; } visitHeaders(ctx) { super.visitHeaders(ctx); this.headers = this.lines.shift(); this.delimiter = ctx.line().delimiter?.text; } visitLine(ctx) { this.line = []; super.visitLine(ctx); this.lines.push(this.line); } visitColumn(ctx) { let text = ctx.getText().trim(); const isQuoted = text.startsWith('"') && text.endsWith('"'); if (isQuoted) { text = text.slice(1, -1).replaceAll('""', '"'); } this.line.push(text); } }