@ztimson/utils 0.23.16 → 0.23.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -686,16 +686,16 @@ function validateEmail(email) {
686
686
  function fromCsv(csv, hasHeaders = true) {
687
687
  function parseLine(line) {
688
688
  const columns = [];
689
- let current = "", inQuotes = false;
689
+ let current = "", inQuotes2 = false;
690
690
  for (let i = 0; i < line.length; i++) {
691
691
  const char = line[i];
692
692
  const nextChar = line[i + 1];
693
693
  if (char === '"') {
694
- if (inQuotes && nextChar === '"') {
694
+ if (inQuotes2 && nextChar === '"') {
695
695
  current += '"';
696
696
  i++;
697
- } else inQuotes = !inQuotes;
698
- } else if (char === "," && !inQuotes) {
697
+ } else inQuotes2 = !inQuotes2;
698
+ } else if (char === "," && !inQuotes2) {
699
699
  columns.push(current);
700
700
  current = "";
701
701
  } else current += char;
@@ -703,12 +703,21 @@ function fromCsv(csv, hasHeaders = true) {
703
703
  columns.push(current);
704
704
  return columns.map((col) => col.replace(/^"|"$/g, "").replace(/""/g, '"'));
705
705
  }
706
- const row = csv.split(/\r?\n/);
707
- let headers = hasHeaders ? row.splice(0, 1)[0] : null;
706
+ const rows2 = [];
707
+ let currentRow = "", inQuotes = false;
708
+ for (const char of csv) {
709
+ if (char === '"') inQuotes = !inQuotes;
710
+ if (char === "\n" && !inQuotes) {
711
+ rows2.push(currentRow);
712
+ currentRow = "";
713
+ } else currentRow += char;
714
+ }
715
+ if (currentRow) rows2.push(currentRow);
716
+ let headers = hasHeaders ? rows2.splice(0, 1)[0] : null;
708
717
  if (headers) headers = headers.match(/(?:[^,"']+|"(?:[^"]|"")*"|'(?:[^']|'')*')+/g);
709
- return row.map((r2) => {
718
+ return rows2.map((r2) => {
710
719
  const props = parseLine(r2);
711
- const h = headers || Array(props.length).fill(null).map((r22, i) => {
720
+ const h = headers || Array(props.length).fill(null).map((_, i) => {
712
721
  let letter = "";
713
722
  const first = i / 26;
714
723
  if (first > 1) letter += LETTER_LIST[Math.floor(first - 1)];
@@ -729,7 +738,7 @@ function toCsv(target, flatten = true) {
729
738
  ...t.map((row) => headers.map((h) => {
730
739
  const value2 = dotNotation(row, h);
731
740
  if (value2 == null) return "";
732
- if (typeof value2 == "object") return `"${JSONSanitize(value2).replaceAll("`", '""')}"`;
741
+ if (typeof value2 == "object") return `"${JSONSanitize(value2).replaceAll('"', '""')}"`;
733
742
  if (typeof value2 == "string" && /[\n"]/g.test(value2)) return `"${value2.replaceAll('"', '""')}"`;
734
743
  return value2;
735
744
  }).join(","))