renderTable<T>() align terminal columns

TypeScript
export interface Column<T> {
  header: string;
  value: (row: T) => string;
  align?: 'left' | 'right';
}

/** Render rows as an aligned plain-text table without any dependency. */
export function renderTable<T>(rows: readonly T[], columns: readonly Column<T>[]): string {
  const cells = rows.map((row) => columns.map((column) => column.value(row).replace(/\s+/g, ' ').trim()));
  const widths = columns.map((column, index) =>
    Math.max(column.header.length, ...cells.map((line) => line[index]?.length ?? 0)),
  );
  const cell = (text: string, index: number): string => {
    const width = widths[index] ?? 0;
    return (columns[index]?.align ?? 'left') === 'right' ? text.padStart(width) : text.padEnd(width);
  };
  const line = (values: readonly string[]): string =>
    values.map((value, index) => cell(value, index)).join(' | ').trimEnd();
  const header = line(columns.map((column) => column.header));
  const divider = widths.map((width) => '-'.repeat(width)).join('-+-');
  return [header, divider, ...cells.map((row) => line(row))].join('\n');
}

// console.log(renderTable(users, [{ header: 'Name', value: (u) => u.name }]));