Skip to content

Instantly share code, notes, and snippets.

@MoritzKn
Last active December 18, 2020 18:15
Show Gist options
  • Save MoritzKn/ed2e6c13c511b827e75a52cad20570d5 to your computer and use it in GitHub Desktop.
Save MoritzKn/ed2e6c13c511b827e75a52cad20570d5 to your computer and use it in GitHub Desktop.
Print aligned tables
function alignedTable({
alignments = [],
separator = ' ',
prefix = '',
suffix = '',
newLine = '\n',
rows = [],
} = {}) {
function toString() {
const lengths = {};
const onlyNumbers = {};
let table = '';
rows.forEach((row, rowIndex) => {
row.forEach((cell, cellIndex) => {
cell = String(cell);
lengths[cellIndex] = Math.max(lengths[cellIndex] || 0, cell.length);
onlyNumbers[cellIndex] =
(onlyNumbers[cellIndex] === undefined || onlyNumbers[cellIndex]) &&
/^[0-9., ]*(\s*\w+)?$/.test(cell);
});
});
rows.forEach((row, rowIndex) => {
let line = prefix;
row.forEach((cell, cellIndex) => {
cell = String(cell);
if (cellIndex !== 0) {
line += separator;
}
const alignment =
alignments[cellIndex] || (onlyNumbers[cellIndex] ? 'r' : 'l');
if (alignment === 'r') {
line += cell.padStart(lengths[cellIndex]);
} else if (alignment === 'c') {
line += cell
.padStart(lengths[cellIndex] / 2 - cell.length / 2)
.padEnd(lengths[cellIndex]);
} else {
line += cell.padEnd(lengths[cellIndex]);
}
line += suffix;
});
table += line + newLine;
});
return table;
}
return {
row(...row) {
rows.push(row);
},
print() {
console.log(toString());
},
toString,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment