DEV Community

Cover image for CSV Is Not Just split(','): Parsing, Type Inference, and Time Alignment in the Browser
YananLee
YananLee

Posted on AI-assisted

CSV Is Not Just split(','): Parsing, Type Inference, and Time Alignment in the Browser

The first version of every chart tool I've written had this line in it:

const rows = text.split('\n').map(line => line.split(','));
Enter fullscreen mode Exit fullscreen mode

It works on the file you tested. It breaks on the first file a real person uploads: a product name with a comma in it, a Windows CRLF, a UTF-8 BOM, a cell with a newline. Then you discover the harder half of the problem — once you have rows, you still don't have series. Someone gives you three snapshots with different sets of categories and expects a smooth animation between them.

Here's the pipeline I ended up with, in plain JavaScript, no dependencies.

1. Parse CSV as a state machine, not a split

RFC 4180 gives you quoted fields, escaped quotes (""), and newlines inside fields. A two-state loop handles all of it:

function parseCSV(text) {
  if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1); // BOM
  const rows = [];
  let row = [], field = '', quoted = false;

  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (quoted) {
      if (c === '"') {
        if (text[i + 1] === '"') { field += '"'; i++; }
        else quoted = false;
      } else {
        field += c; // includes \n and \r inside quotes
      }
    } else if (c === '"' && field === '') {
      quoted = true;
    } else if (c === ',') {
      row.push(field); field = '';
    } else if (c === '\n' || c === '\r') {
      if (c === '\r' && text[i + 1] === '\n') i++;
      row.push(field); field = '';
      if (row.some(v => v !== '')) rows.push(row);
      row = [];
    } else {
      field += c;
    }
  }
  row.push(field);
  if (row.some(v => v !== '')) rows.push(row);
  return rows;
}
Enter fullscreen mode Exit fullscreen mode

Two details worth keeping: the BOM check (Excel loves BOMs), and the fact that a \n inside quoted lands in field rather than ending the row. Also note that this is a character loop — fine for a few MB, slow past that. For big files, move to a streaming parser or a worker.

2. Infer column types by voting, not by the first row

Headers lie, and so does row 1. Sample the column and take a majority:

function toNumber(v) {
  const s = v.trim().replace(/[¥$€£,\s%]/g, '');
  if (!/^[+-]?\d*\.?\d+(?:e[+-]?\d+)?$/i.test(s)) return null;
  const n = Number(s);
  return Number.isFinite(n) ? n : null;
}

const DATE_LIKE = /^\d{4}[-/]\d{1,2}[-/]\d{1,2}$|^\d{1,2}[-/]\d{1,2}[-/]\d{4}$/;

function inferColumn(values) {
  const sample = values.filter(v => v.trim() !== '').slice(0, 200);
  if (!sample.length) return 'empty';
  let num = 0, date = 0;
  for (const v of sample) {
    const s = v.trim();
    if (toNumber(s) !== null) num++;
    else if (DATE_LIKE.test(s) && !Number.isNaN(Date.parse(s))) date++;
  }
  if (num / sample.length > 0.9) return 'number';
  if (date / sample.length > 0.9) return 'date';
  return 'category';
}
Enter fullscreen mode Exit fullscreen mode

toNumber strips currency symbols, thousands separators, and %. That's a deliberate trade-off: 1,234 means 1234 in an English-locale export and 1.234 in a European one. If your users span locales, detect the decimal separator from the whole column first, or let them pick it. Guessing silently is how you ship a chart that's off by 1000x.

I use a 0.9 threshold because one stray "N/A" shouldn't turn a numeric column into a categorical one. Keep the raw strings around — you'll want them for tooltips and axis labels.

3. Align frames before you animate anything

An animated chart is usually a list of snapshots: { t, values: Map<category, number> }. The categories are rarely identical across snapshots — a new product launches, an old one drops out. Interpolating two maps with different keys gives you NaN, or worse, bars that silently jump to zero.

Build the union of keys and the sorted set of timestamps first:

function alignFrames(snapshots, { missing = null } = {}) {
  const keys = [...new Set(snapshots.flatMap(s => [...s.values.keys()]))];
  const times = [...new Set(snapshots.map(s => s.t))].sort();
  const byTime = new Map(snapshots.map(s => [s.t, s.values]));

  return times.map(t => ({
    t,
    values: Object.fromEntries(
      keys.map(k => [k, byTime.get(t)?.get(k) ?? missing])
    )
  }));
}
Enter fullscreen mode Exit fullscreen mode

missing = null matters. Absent is not zero. When you render, carry the last known value forward and fade the bar out, or hold it at its last rank — drawing it as a zero-height bar invents data the user never gave you.

4. Interpolate values and ranks

Values are the easy part:

const easeInOutCubic = u =>
  u < 0.5 ? 4 * u * u * u : 1 - Math.pow(-2 * u + 2, 3) / 2;

function blend(a, b, u, ease = easeInOutCubic) {
  const p = ease(u);
  return Object.fromEntries(
    Object.keys(a).map(k => [k, a[k] + (b[k] - a[k]) * p])
  );
}
Enter fullscreen mode Exit fullscreen mode

For a bar chart race, blending values alone still looks wrong: when two bars swap order, their positions snap in a single frame. Interpolate the target slot instead, using the previous layout as the start:

function barLayout(values, prevSlots, u, ease = easeInOutCubic) {
  const sorted = Object.entries(values).sort((a, b) => b[1] - a[1]);
  const target = new Map(sorted.map(([key], i) => [key, i]));
  const p = ease(u);

  return sorted.map(([key, value]) => {
    const from = prevSlots[key] ?? target.get(key);
    return {
      key,
      value,
      slot: from + (target.get(key) - from) * p
    };
  });
}
Enter fullscreen mode Exit fullscreen mode

Now a bar glides from rank 3 to rank 1 while its width changes. Feed slot into y = slot * (barHeight + gap) and you have the whole "race" effect in about ten lines. Keep prevSlots from the last frame of the previous segment, otherwise each transition restarts from the target position and you lose the motion.

5. For export, drive time from the frame index

requestAnimationFrame timestamps are fine on screen and useless in a render queue — dropped frames change the animation's duration. For deterministic MP4/WebM/GIF output, compute state from the frame number:

function frameAt(frames, index, totalFrames, fps = 30) {
  const u = totalFrames <= 1 ? 0 : index / (totalFrames - 1);
  const pos = u * (frames.length - 1);
  const i = Math.min(Math.floor(pos), frames.length - 2);
  const local = easeInOutCubic(pos - i);
  return blend(frames[i].values, frames[i + 1].values, local);
}

// renderFrame(i) must not read Date.now() or performance.now()
Enter fullscreen mode Exit fullscreen mode

Same input, same bytes out, every run. That's also what makes it possible to re-render at 4K without re-authoring anything.

Here's what a finished set of chart templates looks like once the data is mapped and the animation is driven this way:

Animated chart templates generated from spreadsheet data

The image links to a working tool if you want to see the result without wiring up the parser yourself.

When you shouldn't build this

If the goal is a QBR deck due this afternoon, the ~120 lines above are the wrong investment. LivelyChart does the spreadsheet import, the scene-based template generation, and the MP4/WebM/GIF/PNG export in the browser — you upload Excel or CSV, describe the scene, and export. The data is parsed locally unless you ask AI to edit it.

Still, the alignment step is the one I'd keep even if you use a charting library. Most "my animated chart looks janky" bugs aren't easing bugs. They're category sets that don't match between frames.


Disclosure: I work on LivelyChart. The parsing, alignment, and interpolation code above is generic, has no dependency on the tool, and runs in any browser.

Top comments (0)