Skip to content

Instantly share code, notes, and snippets.

@tylerneylon
Created June 24, 2023 22:59
Show Gist options
  • Save tylerneylon/1cc661e22ca8a57af55f1ac3b8324b33 to your computer and use it in GitHub Desktop.
Save tylerneylon/1cc661e22ca8a57af55f1ac3b8324b33 to your computer and use it in GitHub Desktop.
a JavaScript function to print out a table with right-justified columns
// Print out a simple table with right-justified columns of strings.
// This can handle some columns having fewer entries than others.
// (For mid-table missing entries, provide empty strings.)
// The `cols` value is an array of arrays of strings, the columns of the table.
// The optional `topSep` is a string the indicates the separator to use in the
// top row only. If you don't provide topSep, a single space is used.
function showTableWithColumns(cols, topSep) {
if (topSep === undefined) topSep = ' ';
let numRows = Math.max(...cols.map(x => x.length));
cols.forEach(col => {
while (col.length < numRows) col.push('');
});
// Find the maximum width in each column.
let widths = cols.map(col => Math.max(...col.map(x => x.length)));
let nonTopSep = ''.padStart(topSep.length);
for (let i = 0; i < numRows; i++) {
let sep = (i === 0) ? topSep : nonTopSep;
let msg = cols.map((col, j) => col[i].padStart(widths[j])).join(sep);
console.log(msg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment