export default class CSVReader { constructor(private readonly text: string) { } async *read() { let fields = null as string[]; const reader = this.splitCSV(); const { value, done } = reader.next(); if (!done) { fields = value; } for(;;) { const nr = reader.next(); if (nr.done) { break; } const values = nr.value; const json = {}; for (let index = 0; index < fields.length; index++) { const element = fields[index]; const v = values[index]; json[element] = v; } yield json; } } *splitCSV(): Generator { let m; let row = []; const regex = /((\"((\"\")|[^\"])+\")|[^,\n]+|\n)/gm; while ((m = regex.exec(this.text)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } if (m.length) { let field = m[0] as string; if (field.startsWith('"')) { field = field.substring(1, field.length -1); field = field.replaceAll(`""`, `"`); } if (field === "\n") { yield row; row = []; } else { row.push(field); } } } if (row.length) { yield row; } } }