// Client-side analysis of a parsed table (CSV/TSV files, Markdown and notebook // tables): type detection, sorting, filtering, grouping, aggregates, export and // the shareable URL state. Pure functions, no DOM: everything runs on the // anonymized text already on the page. export const AGGREGATES = [ ["mean", "Average"], ["sum", "Sum"], ["median", "Median"], ["min", "Min"], ["max", "Max"], ["count", "Count"], ["std", "Std dev"], ]; export const AGGREGATE_LABEL = Object.fromEntries(AGGREGATES); const AGGREGATE_SHORT = { mean: "Avg", sum: "Sum", median: "Median", min: "Min", max: "Max", count: "Count", std: "Std dev" }; export const aggregateShort = (fn) => AGGREGATE_SHORT[fn] || fn; // Cells that mean "no value" in exported numbers and dates (pandas, R, // spreadsheets). In a text column they are real categories ("none" as an // augmentation, a model called "None"), so there only a blank cell is empty. const PLACEHOLDER = /^(?:na|n\/a|nan|null|none|-|—|–)$/i; export const isBlank = (raw) => raw == null || String(raw).trim() === ""; export const isMissing = (raw) => isBlank(raw) || PLACEHOLDER.test(String(raw).trim()); // 1,234 · -0.5 · +3 · 12% · 1e-3 · −2 (Unicode minus) · .5 — one match gives // the value, the decimals as written and the percent sign. const NUMBER_RE = /^([-+]?)(\d{1,3}(?:,\d{3})+|\d*)(?:\.(\d+))?(?:e([-+]?\d+))?(%?)$/i; export function scanNumber(raw) { if (raw == null) return null; if (typeof raw === "number") return Number.isFinite(raw) ? { value: raw, decimals: 0, percent: false } : null; let text = String(raw).trim(); if (text.charCodeAt(0) === 0x2212) text = "-" + text.slice(1); const m = NUMBER_RE.exec(text); if (!m || (!m[2] && !m[3])) return null; const value = Number(m[1] + (m[2] ? m[2].replace(/,/g, "") : "0") + (m[3] ? "." + m[3] : "") + (m[4] ? "e" + m[4] : "")); if (!Number.isFinite(value)) return null; return { value, decimals: Math.max(0, Math.min(10, (m[3] || "").length - (m[4] ? Number(m[4]) : 0))), percent: m[5] === "%", exponent: !!m[4], mantissa: (m[3] || "").length }; } export const parseNumber = (raw) => scanNumber(raw)?.value ?? null; // Digits after the decimal point, as written ("78.90" -> 2, "1e-3" -> 3). export const decimalsOf = (raw) => scanNumber(raw)?.decimals ?? 0; // Unambiguous dates only: ISO (2026-03-01, 2026-03-01T10:00Z, 2026/03/01) and // written months with a year (Mar 1, 2026 · 1 March 2026). 03/01/2026 is left as text. const ISO_DATE = /^(\d{4})[-/](\d{1,2})[-/](\d{1,2})(?:[T ](\d{1,2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?\s*(Z|[+-]\d{2}:?\d{2})?)?$/i; const MONTHS = "jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec"; const WORD_DATE = new RegExp(`^(?:\\d{1,2}\\s+(?:${MONTHS})[a-z]*\\.?,?\\s+\\d{4}|(?:${MONTHS})[a-z]*\\.?\\s+\\d{1,2},?\\s+\\d{4})$`, "i"); export function parseDate(raw) { if (raw == null) return null; const text = String(raw).trim(); if (!text) return null; const iso = ISO_DATE.exec(text); if (iso) { const [, y, mo, d, h = "0", mi = "0", s = "0", zone] = iso; if (+mo < 1 || +mo > 12 || +d < 1 || +d > 31) return null; if (zone) { const t = Date.parse(`${y}-${mo.padStart(2, "0")}-${d.padStart(2, "0")}T${h.padStart(2, "0")}:${mi}:${s.padStart(2, "0")}${zone.length === 5 ? zone.slice(0, 3) + ":" + zone.slice(3) : zone}`); return Number.isFinite(t) ? t : null; } return Date.UTC(+y, +mo - 1, +d, +h, +mi, +s); } if (WORD_DATE.test(text)) { const t = Date.parse(text.replace(/\./g, "") + " UTC"); return Number.isFinite(t) ? t : null; } return null; } // "number" when every non-empty cell parses as a number, "date" when every one // parses as a date, "text" otherwise (and for a column with no values). export const detectType = (values) => makeColumn("", 0, values).type; const collator = typeof Intl !== "undefined" ? new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }) : null; const compareText = collator ? collator.compare : (a, b) => (a < b ? -1 : a > b ? 1 : 0); /** * A table model from rows of strings (the first row is the header). * Each column gets its detected type, precision (max decimals seen), unit ("%" * when every value has one) and a key per row: a number for numbers and dates * (null when empty), the cell text otherwise. */ export function analyzeTable(rows) { const header = (rows && rows[0]) || []; const body = rows ? rows.slice(1) : []; const width = Math.max(header.length, ...body.slice(0, 2000).map((r) => r.length), 0); const columns = []; for (let ci = 0; ci < width; ci++) { const values = body.map((r) => r[ci] ?? ""); columns.push(makeColumn(String(header[ci] ?? "").trim() || "Column " + (ci + 1), ci, values)); } for (const c of columns) c.identifier = isIdentifier(c); return { header: columns.map((c) => c.name), body, columns, size: body.length }; } // Columns that name a run rather than measure it: seed, id, run, fold, index, // year (by name), or small consecutive whole numbers that repeat across rows // (1..5 for five seeds). They are left out of summaries and group aggregates; // the column menu can still treat one as a number. const ID_NAME = /(?:^|[\s_.\-/(])(?:seed|id|ids|run|runs|run_id|fold|folds|index|idx|year|trial|trials|rep|reps|repeat|split|#|no)s?(?:$|[\s_.\-/)])|^(?:seed|id|run|fold|index|idx|year|trial|rep|repeat)s?$|[a-z]Id$/i; export function isIdentifier(column) { if (!column || column.type !== "number") return false; if (ID_NAME.test(column.name.trim())) return column.decimals === 0; if (column.decimals !== 0 || column.unit) return false; let min = Infinity, max = -Infinity, filled = 0; const seen = new Set(); for (const k of column.keys) { if (k == null) continue; if (k < 0 || !Number.isInteger(k)) return false; filled++; seen.add(k); if (k < min) min = k; if (k > max) max = k; if (seen.size > 12) return false; } // Consecutive keys (1..5, 0..9) each used at least twice. return seen.size >= 2 && filled >= 2 * seen.size && max - min + 1 === seen.size && min <= 1; } export function makeColumn(name, index, values, forced) { const n = values.length; const keys = new Array(n); let type = forced?.type, decimals = 0, empty = 0, percent = 0, filled = 0, exponent = 0, mantissa = 0; for (let i = 0; i < n; i++) if (isMissing(values[i])) { keys[i] = null; empty++; } else filled++; // One pass per candidate type, stopping at the first cell that doesn't fit. if (!type || type === "number") { let ok = filled > 0 || type === "number"; for (let i = 0; ok && i < n; i++) { if (keys[i] === null) continue; const scan = scanNumber(values[i]); if (!scan) { ok = type === "number"; keys[i] = null; continue; } keys[i] = scan.value; if (scan.decimals > decimals) decimals = scan.decimals; if (scan.percent) percent++; if (scan.exponent) { exponent++; if (scan.mantissa > mantissa) mantissa = scan.mantissa; } } if (ok) type = "number"; } if (!type || type === "date") { let ok = filled > 0 || type === "date"; for (let i = 0; ok && i < n; i++) { if (isMissing(values[i])) continue; const t = parseDate(values[i]); if (t == null) ok = type === "date"; keys[i] = t; } if (ok) type = "date"; } if (!type || type === "text") { type = "text"; empty = 0; for (let i = 0; i < n; i++) { keys[i] = isBlank(values[i]) ? null : String(values[i]).trim(); if (keys[i] === null) empty++; } } return { name, index, type, keys, empty, decimals: forced?.decimals ?? decimals, unit: forced?.unit ?? (type === "number" && filled && percent === filled ? "%" : ""), // Written as 1.38e-3: aggregates keep scientific notation and its significant digits. scientific: forced?.scientific ?? (type === "number" && exponent * 2 >= filled && exponent > 0 ? mantissa : null), }; } let distinctCache = new WeakMap(); export function distinctValues(column, indices) { const all = !indices; if (all && distinctCache.has(column)) return distinctCache.get(column); const counts = new Map(); const list = indices || column.keys.map((_, i) => i); for (const i of list) { const k = column.keys[i]; if (k == null) continue; counts.set(k, (counts.get(k) || 0) + 1); } if (all) distinctCache.set(column, counts); return counts; } // Row order for the given column: ascending or descending, stable (ties keep // their current order) and with empty cells last in both directions. export function sortIndices(table, indices, columnIndex, direction) { const column = table.columns[columnIndex]; if (!column || !direction) return indices.slice(); const sign = direction === "desc" ? -1 : 1; const keys = column.keys; const numeric = column.type !== "text"; const order = indices.map((row, position) => ({ row, position })); order.sort((a, b) => { const ka = keys[a.row], kb = keys[b.row]; if (ka == null || kb == null) return ka == null && kb == null ? a.position - b.position : ka == null ? 1 : -1; const c = numeric ? ka - kb : compareText(ka, kb); return c ? c * sign : a.position - b.position; }); return order.map((o) => o.row); } // Rows matching the search text (any cell, case-insensitive), every numeric // range { [column]: [min, max] } (either bound may be null) and every value set // { [column]: [values] } (as text; a date is its timestamp). export function filterIndices(table, { query = "", ranges = {}, values = {} } = {}) { const needle = String(query || "").trim().toLowerCase(); const rangeList = Object.entries(ranges || {}).map(([ci, r]) => [table.columns[ci], r]).filter(([c, r]) => c && r && (r[0] != null || r[1] != null)); const valueList = Object.entries(values || {}).map(([ci, v]) => [table.columns[ci], new Set(v)]).filter(([c, v]) => c && v.size); const out = []; const haystack = needle ? searchText(table) : null; for (let i = 0; i < table.size; i++) { if (needle && haystack[i].indexOf(needle) === -1) continue; let keep = true; for (const [c, [min, max]] of rangeList) { const k = c.keys[i]; if (k == null || (min != null && k < min) || (max != null && k > max)) { keep = false; break; } } if (!keep) continue; for (const [c, set] of valueList) if (!set.has(c.keys[i] == null ? "" : String(c.keys[i]))) { keep = false; break; } if (keep) out.push(i); } return out; } const searchCache = new WeakMap(); function searchText(table) { if (!searchCache.has(table)) searchCache.set(table, table.body.map((r) => r.join("\u0001").toLowerCase())); return searchCache.get(table); } // One aggregate over the non-empty keys of the given rows. null when undefined // (no values; a standard deviation needs two). export function aggregate(keys, indices, fn) { const values = []; for (const i of indices) { const k = keys[i]; if (k != null && Number.isFinite(k)) values.push(k); } const n = values.length; if (fn === "count") return n; if (!n) return null; if (fn === "sum") return values.reduce((s, v) => s + v, 0); if (fn === "mean") return values.reduce((s, v) => s + v, 0) / n; if (fn === "min") return values.reduce((m, v) => (v < m ? v : m), Infinity); if (fn === "max") return values.reduce((m, v) => (v > m ? v : m), -Infinity); if (fn === "median") { values.sort((a, b) => a - b); return n % 2 ? values[(n - 1) / 2] : (values[n / 2 - 1] + values[n / 2]) / 2; } if (fn === "std") { if (n < 2) return null; const mean = values.reduce((s, v) => s + v, 0) / n; return Math.sqrt(values.reduce((s, v) => s + (v - mean) ** 2, 0) / (n - 1)); } return null; } // Decimals shown for an aggregate: the column's own precision; an average, // median or standard deviation of whole numbers keeps one decimal. export const aggregateDecimals = (column, fn) => fn === "count" ? 0 : ["mean", "median", "std"].includes(fn) ? Math.max(column.decimals, 1) : column.decimals; const formats = new Map(); const numberFormat = (d) => { if (!formats.has(d)) formats.set(d, new Intl.NumberFormat("en-US", { minimumFractionDigits: d, maximumFractionDigits: d })); return formats.get(d); }; export function formatNumber(value, decimals = 0, unit = "") { if (value == null || !Number.isFinite(value)) return "—"; const d = Math.max(0, Math.min(10, decimals)); const abs = Math.abs(value); if (abs !== 0 && (abs >= 1e15 || (abs < 1e-6 && d <= 6))) return value.toExponential(Math.min(d, 3)) + unit; return numberFormat(d).format(value) + unit; } const pad = (n) => String(n).padStart(2, "0"); export function formatDate(ms, withTime) { if (ms == null || !Number.isFinite(ms)) return "—"; const d = new Date(ms); const day = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`; return withTime ? `${day} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}` : day; } const hasTime = (column) => column.keys.some((k) => k != null && k % 86400000 !== 0); export function formatKey(column, key, fn) { if (column.type === "number" && column.scientific != null && fn !== "count" && key != null && Number.isFinite(key) && key !== 0) return key.toExponential(column.scientific + (["mean", "median", "std"].includes(fn) ? 1 : 0)) + column.unit; if (column.type === "date") return fn === "count" ? formatNumber(key, 0) : formatDate(key, hasTime(column)); if (column.type === "number" || fn) return formatNumber(key, fn ? aggregateDecimals(column, fn) : column.decimals, fn === "count" ? "" : column.unit); return key == null ? "" : String(key); } // The summary cell of a column over the given rows: the selected aggregate for // measures, the count of distinct values for text and dates, nothing for // identifiers (seed, run...: an average of them means nothing). export function summarize(column, indices, fn = "mean", isMeasure = (c) => !c.identifier) { if (column.type !== "number") { const distinct = distinctValues(column, indices).size; return { kind: "distinct", value: distinct, text: distinct === 1 ? "1 distinct" : formatNumber(distinct) + " distinct" }; } if (!isMeasure(column)) return { kind: "none", text: "" }; const value = aggregate(column.keys, indices, fn); return { kind: "number", fn, value, text: formatKey(column, value, fn) }; } /** * Rows grouped by one column: the group's value, its row count, then every * numeric column aggregated with fn. The result is a table model like * analyzeTable's, so it can be sorted, summarized, charted and exported. */ export function groupTable(table, indices, groupIndex, fn = "mean", isMeasure = (c) => !c.identifier) { const by = table.columns[groupIndex]; if (!by) return null; const groups = new Map(); for (const i of indices) { const key = by.keys[i] == null ? "" : by.keys[i]; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(i); } const numeric = table.columns.filter((c) => c.type === "number" && c.index !== groupIndex && isMeasure(c)); const entries = [...groups.entries()]; // Text groups keep the cell as written (first occurrence); numbers and dates are formatted. const labels = entries.map(([key, rows]) => (key === "" ? "(empty)" : by.type === "text" ? table.body[rows[0]][groupIndex].trim() : formatKey(by, key))); const groupColumn = makeColumn(by.name, 0, labels, { type: by.type, decimals: by.decimals, unit: by.unit }); groupColumn.keys = entries.map(([key]) => (key === "" ? null : key)); groupColumn.source = groupIndex; groupColumn.identifier = by.type === "number"; const countColumn = makeColumn("Rows", 1, entries.map(([, rows]) => rows.length), { type: "number", decimals: 0, unit: "" }); const valueColumns = numeric.map((c, n) => { const values = entries.map(([, rows]) => aggregate(c.keys, rows, fn)); const column = makeColumn(c.name, n + 2, values, { type: "number", decimals: aggregateDecimals(c, fn), unit: fn === "count" ? "" : c.unit, scientific: fn === "count" || c.scientific == null ? null : c.scientific + (["mean", "median", "std"].includes(fn) ? 1 : 0) }); column.source = c.index; column.agg = fn; return column; }); const columns = [groupColumn, countColumn, ...valueColumns]; const body = entries.map((_, r) => columns.map((c) => (c === groupColumn ? labels[r] : formatKey(c, c.keys[r])))); return { header: columns.map((c) => c.name), body, columns, size: body.length, grouped: { by: by.name, fn } }; } // Quick facts for a column's menu: type, counts, range, mean and a histogram. export function columnStats(column, indices, bins = 12) { const stats = { type: column.type, count: 0, empty: 0, distinct: distinctValues(column, indices).size }; for (const i of indices) { if (column.keys[i] == null) stats.empty++; else stats.count++; } if (column.type === "text") { stats.top = [...distinctValues(column, indices).entries()].sort((a, b) => b[1] - a[1] || compareText(a[0], b[0])).slice(0, 5); return stats; } stats.min = aggregate(column.keys, indices, "min"); stats.max = aggregate(column.keys, indices, "max"); if (column.type === "number") { stats.mean = aggregate(column.keys, indices, "mean"); stats.std = aggregate(column.keys, indices, "std"); } if (stats.count && stats.min != null) { const n = stats.min === stats.max ? 1 : bins; const width = (stats.max - stats.min) / n || 1; const counts = new Array(n).fill(0); for (const i of indices) { const k = column.keys[i]; if (k == null) continue; counts[Math.min(n - 1, Math.floor((k - stats.min) / width))]++; } stats.histogram = counts.map((count, b) => ({ count, from: stats.min + b * width, to: stats.min + (b + 1) * width })); } return stats; } // ---- Export ----------------------------------------------------------------- const csvCell = (value, sep) => { const text = String(value ?? ""); return text.includes(sep) || /["\r\n]/.test(text) || /^\s|\s$/.test(text) ? '"' + text.replace(/"/g, '""') + '"' : text; }; export const toDelimited = (header, rows, sep = ",") => [header, ...rows].map((r) => r.map((v) => csvCell(v, sep)).join(sep)).join("\n") + "\n"; const mdCell = (value) => String(value ?? "").replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r?\n/g, " "); export function toMarkdown(header, rows, numeric = []) { const lines = [ "| " + header.map(mdCell).join(" | ") + " |", "| " + header.map((_, i) => (numeric[i] ? "---:" : "---")).join(" | ") + " |", ...rows.map((r) => "| " + header.map((_, i) => mdCell(r[i])).join(" | ") + " |"), ]; return lines.join("\n") + "\n"; } // ---- Shareable state -------------------------------------------------------- // The analysis of a table lives in the URL fragment so a link can carry // "grouped by model, average accuracy": #table:group=model&agg=mean (a single // file) or #table-2:... (the second file of a gist). Columns are named, not // numbered. Without the fragment the table opens as it always did. export const DEFAULT_STATE = Object.freeze({ view: "table", query: "", sort: null, group: null, agg: "mean", sum: "mean", ranges: {}, values: {}, sums: {}, numeric: [], chart: null, x: null, y: [] }); export function encodeState(state) { const p = new URLSearchParams(); if (state.view && state.view !== "table") p.set("view", state.view); if (state.query) p.set("q", state.query); if (state.sort?.column) p.set("sort", state.sort.column + (state.sort.dir === "desc" ? ":desc" : "")); if (state.group) p.set("group", state.group); if (state.group && state.agg && state.agg !== "mean") p.set("agg", state.agg); for (const [name, [min, max]] of Object.entries(state.ranges || {})) if (min != null || max != null) p.set("range." + name, (min ?? "") + "~" + (max ?? "")); for (const [name, list] of Object.entries(state.values || {})) for (const v of list || []) p.append("in." + name, v); if (state.sum && state.sum !== "mean") p.set("sum", state.sum); for (const [name, fn] of Object.entries(state.sums || {})) if (fn && fn !== (state.sum || "mean")) p.set("sum." + name, fn); if (state.numeric?.length) p.set("num", state.numeric.join("|")); if (state.chart) p.set("chart", state.chart); if (state.x) p.set("x", state.x); if (state.y?.length) p.set("y", state.y.join("|")); return p.toString(); } export function decodeState(text) { const p = new URLSearchParams(text || ""); const out = { ...DEFAULT_STATE, ranges: {}, values: {}, sums: {}, numeric: [], y: [] }; const view = p.get("view"); if (["table", "chart", "raw"].includes(view)) out.view = view; out.query = p.get("q") || ""; const sort = p.get("sort"); if (sort) { const m = /^(.*?)(?::(asc|desc))?$/.exec(sort); out.sort = { column: m[1], dir: m[2] || "asc" }; } out.group = p.get("group") || null; const agg = p.get("agg"); if (agg && AGGREGATE_LABEL[agg]) out.agg = agg; for (const [key, value] of p.entries()) { if (key.startsWith("range.")) { const [min, max] = value.split("~").map((v) => (v === "" || v == null ? null : Number(v))); out.ranges[key.slice(6)] = [Number.isFinite(min) ? min : null, Number.isFinite(max) ? max : null]; } else if (key.startsWith("in.")) (out.values[key.slice(3)] ||= []).push(value); else if (key.startsWith("sum.") && AGGREGATE_LABEL[value]) out.sums[key.slice(4)] = value; } const sum = p.get("sum"); if (sum && AGGREGATE_LABEL[sum]) out.sum = sum; out.numeric = (p.get("num") || "").split("|").filter(Boolean); const chart = p.get("chart"); if (["bar", "line", "scatter"].includes(chart)) out.chart = chart; out.x = p.get("x") || null; out.y = (p.get("y") || "").split("|").filter(Boolean); return out; } const hashPrefix = (key) => "#" + key + ":"; export function readHashState(hash, key) { if (!key || typeof hash !== "string" || !hash.startsWith(hashPrefix(key))) return null; try { return decodeState(hash.slice(hashPrefix(key).length)); } catch { return null; } } // The fragment for a state, "" when the state is the default (the link is then left clean). export function writeHashState(key, state) { const encoded = encodeState(state); return encoded ? hashPrefix(key) + encoded.replace(/%3A/gi, ":").replace(/%7C/gi, "|").replace(/%7E/gi, "~").replace(/%2C/gi, ",") : ""; } export const isTableHash = (hash) => /^#table(?:-\d+)?:/.test(hash || "");