Skip to content

CSV Diff — TypeScript source

Diff two CSVs by a key column: rows added, removed and changed, with the differing columns named. Quoted cells with commas, quotes and newlines are handled. Runs locally with a shareable link.

This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Pure surface of the CSV Diff tool (slug: csv-diff). Key-based row diff over
// two RFC-4180 CSVs: quoted cells (embedded commas, quotes, newlines), a
// required identical header row, one row per key. The rules here are the
// contract a Go CLI twin must reproduce — notably strict ragged-row errors,
// duplicate-key errors, and diff columns sorted by name. Parsing reuses the
// shared RFC-4180 parser from ./csv (blank single-cell rows are dropped here
// because a diff treats them as trailing noise, not data).
import { csvToRows } from './csv';

export interface CsvDiffOptions {
  /** Header name of the key column. Default: the first header column. */
  keyColumn?: string;
}

export interface CsvRowDiff {
  key: string;
  type: 'added' | 'removed' | 'changed';
  /** Differing column names, sorted. Present on 'changed' only. */
  columns?: string[];
  before?: Record<string, string>;
  after?: Record<string, string>;
}

export type CsvDiffResult =
  | { rows: CsvRowDiff[]; same: boolean; error: null }
  | { rows: []; same: false; error: string };

/** Parse via the shared RFC-4180 parser, dropping blank single-cell rows. */
function parseCsv(text: string): string[][] {
  return csvToRows(text).filter((r) => !(r.length === 1 && r[0] === ''));
}

function toRecords(rows: string[][], label: string): { header: string[]; records: Record<string, string>[] } {
  if (rows.length === 0) throw new Error(`${label}: empty CSV`);
  const header = rows[0];
  const seen = new Set<string>();
  for (const name of header) {
    if (seen.has(name)) throw new Error(`${label}: duplicate column "${name}"`);
    seen.add(name);
  }
  const records: Record<string, string>[] = [];
  for (let r = 1; r < rows.length; r++) {
    if (rows[r].length !== header.length) {
      throw new Error(`${label}: row ${r + 1} has ${rows[r].length} cells, expected ${header.length}`);
    }
    const record: Record<string, string> = {};
    header.forEach((name, c) => {
      record[name] = rows[r][c];
    });
    records.push(record);
  }
  return { header, records };
}

/** Diff two CSVs by key column. Headers must match exactly (same names). */
export function csvDiff(leftRaw: string, rightRaw: string, options: CsvDiffOptions = {}): CsvDiffResult {
  if (!leftRaw.trim() || !rightRaw.trim()) {
    return { rows: [], same: false, error: 'Both inputs are required' };
  }
  try {
    const left = toRecords(parseCsv(leftRaw), 'Left');
    const right = toRecords(parseCsv(rightRaw), 'Right');

    const key = options.keyColumn ?? left.header[0];
    if (!left.header.includes(key)) return { rows: [], same: false, error: `Left: no key column "${key}"` };
    if (!right.header.includes(key)) return { rows: [], same: false, error: `Right: no key column "${key}"` };
    if (left.header.length !== right.header.length || left.header.some((h, i) => h !== right.header[i])) {
      return {
        rows: [],
        same: false,
        error: `Headers differ: left [${left.header.join(', ')}] vs right [${right.header.join(', ')}]`,
      };
    }

    const leftBy = new Map<string, Record<string, string>>();
    for (const rec of left.records) {
      const k = rec[key];
      if (leftBy.has(k)) return { rows: [], same: false, error: `Left: duplicate key "${k}"` };
      leftBy.set(k, rec);
    }
    const rightBy = new Map<string, Record<string, string>>();
    for (const rec of right.records) {
      const k = rec[key];
      if (rightBy.has(k)) return { rows: [], same: false, error: `Right: duplicate key "${k}"` };
      rightBy.set(k, rec);
    }

    const rows: CsvRowDiff[] = [];
    for (const k of [...new Set([...leftBy.keys(), ...rightBy.keys()])].sort()) {
      const l = leftBy.get(k);
      const r = rightBy.get(k);
      if (!l) rows.push({ key: k, type: 'added', after: r });
      else if (!r) rows.push({ key: k, type: 'removed', before: l });
      else {
        const columns = left.header.filter((name) => name !== key && l[name] !== r[name]).sort();
        if (columns.length > 0) rows.push({ key: k, type: 'changed', columns, before: l, after: r });
      }
    }
    return { rows, same: rows.length === 0, error: null };
  } catch (e) {
    // Every throw site above constructs its own Error, so the cast is safe.
    return { rows: [], same: false, error: (e as Error).message };
  }
}

Also available in 12 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →