@forzalabs/remora
Version:
A powerful CLI tool for seamless data translation.
61 lines (60 loc) • 2.29 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Affirm_1 = __importDefault(require("../../core/Affirm"));
class CSVParserClass {
constructor() {
this.parseRow = (row, delimiter) => {
(0, Affirm_1.default)(row, 'Invalid row');
(0, Affirm_1.default)(delimiter, 'Invalid delimiter');
const fields = [];
const len = row.length;
let fieldStart = 0;
let fieldEnd = 0;
let inQuotes = false;
let hasQuotes = false;
let i = 0;
while (i < len) {
const char = row.charCodeAt(i);
if (char === 34) { // '"'
if (!inQuotes) {
inQuotes = true;
hasQuotes = true;
fieldStart = i + 1;
}
else if (row.charCodeAt(i + 1) === 34) {
i++; // Skip escaped quote, will handle in extraction
}
else {
inQuotes = false;
fieldEnd = i;
}
}
else if (char === delimiter.charCodeAt(0) && !inQuotes) {
// Extract field
const field = hasQuotes
? row.slice(fieldStart, fieldEnd).replaceAll('""', '"')
: row.slice(fieldStart, i).trim();
fields.push(field);
fieldStart = i + 1;
fieldEnd = 0;
hasQuotes = false;
}
else if ((char === 13 || char === 10) && !inQuotes) { // \r or \n
break;
}
i++;
}
// Add the last field
const field = hasQuotes
? row.slice(fieldStart, fieldEnd).replaceAll('""', '"')
: row.slice(fieldStart, i).trim();
fields.push(field);
return fields;
};
}
}
const CSVParser = new CSVParserClass();
exports.default = CSVParser;