printAlignedCliTableRows
JavaScript
// Renders record rows as an aligned plain-text table for terminal output.
const widthOf = (value) => [...String(value)].length;
export function renderAlignedCliTable(rows, { columns, align = {} } = {}) {
if (!Array.isArray(rows) || rows.length === 0) return '';
const keys = columns ?? Object.keys(rows[0]);
const cells = rows.map((row) => keys.map((key) => String(row[key] ?? '')));
const widths = keys.map((key, index) => Math.max(
widthOf(key),
...cells.map((row) => widthOf(row[index])),
));
const formatRow = (values) => values
.map((value, index) => {
const pad = ' '.repeat(Math.max(0, widths[index] - widthOf(value)));
return align[keys[index]] === 'right' ? pad + value : value + pad;
})
.join(' ')
.trimEnd();
const rule = widths.map((width) => '-'.repeat(width)).join(' ');
return [formatRow(keys), rule, ...cells.map(formatRow)].join('\n');
}
export function printAlignedCliTable(rows, options, stream = process.stdout) {
const table = renderAlignedCliTable(rows, options);
if (table) stream.write(`${table}\n`);
}