ts-markdown-builder
Version:
Elegant markdown builder with minimal bundle size.
24 lines • 1.03 kB
JavaScript
export function table(header, rows, options) {
if (header.length === 0) {
return '';
}
header = header.map(escapeCellContent);
rows = rows.map(row => row.map(escapeCellContent));
const widths = !options?.compact ? getColumnsWidth(header, rows) : header.map(() => 1);
const separators = header.map((_, i) => '-'.repeat(widths[i] ?? 0));
return [renderRow(header, widths), renderRow(separators, widths), ...rows.map(row => renderRow(row, widths))].join('\n');
}
function getColumnsWidth(header, rows) {
return header.map((_, index) => getColumnWidth(header, rows, index));
}
function getColumnWidth(header, rows, index) {
return Math.max(header[index]?.length ?? 0, ...rows.map(row => row[index]?.length ?? 0));
}
function renderRow(row, widths) {
const paddedCells = row.map((cell, index) => cell.padEnd(widths[index] ?? 0));
return `| ${paddedCells.join(' | ')} |`;
}
function escapeCellContent(cell) {
return cell.replace(/\|/g, '\\|').replace(/\n/g, '<br/>');
}
//# sourceMappingURL=table.mjs.map