Skip to content

Instantly share code, notes, and snippets.

@afonsomatos
Last active August 29, 2015 14:22
Show Gist options
  • Save afonsomatos/651cf26e709a4491a112 to your computer and use it in GitHub Desktop.
Save afonsomatos/651cf26e709a4491a112 to your computer and use it in GitHub Desktop.
Lightweight table creator
/*!
* Easy to use table creator
* afonsomatos <contact@afonsomatos.com>
*
* @param {Array} - Array containing the rows of the table
* @param {Object} [{rows: Array.length,
* padding: 2,
* marginLeft: 2,
* lineHeight: 0,
* cols: <row in most length>.length }] - Configure object
*
*/
let createTable = function(arr, obj) {
obj = obj || {};
let rows = obj.rows,
cols = obj.cols,
padding = obj.padding,
lineBreaks = obj.lineBreaks,
marginLeft = obj.marginLeft,
lineHeight = obj.lineHeight;
if (rows === undefined) {
// Find number of rows by size
rows = arr.length;
}
if (padding === undefined) {
// Space between columns
padding = 2;
}
if (marginLeft === undefined) {
// Default margin left
marginLeft = 2;
}
if (lineHeight === undefined) {
// Lines between rows
lineHeight = 0;
}
if (cols === undefined) {
// Find row with most elements
cols = arr.reduce(function(len, val) {
return Math.max(len, val.length);
}, 0);
}
// Shrink desired rows
arr = arr.slice(0, rows);
return arr.map(function(row, r) {
return row.map(function(col, c) {
// Handle undefined values
col = col || "";
// Shrink desired cols
if (c > cols - 1) return "";
// Find the element with greatest length in column
let maxLen = arr.reduce(function(max, el) {
return Math.max(max, (el[c] || "").length);
}, 0)
return " ".repeat(marginLeft) + col + " ".repeat(maxLen - col.length + padding);
}).join('');
}).join('\n'.repeat(lineHeight + 1));
};
let myTable = createTable([
["-q", "--quit", "Quit program"],
["-h", "--help", "Help for more information"],
["-d", "--dance", "Make the command line dance"],
["-p", "--panda", "Log panda"]
], {rows: 3, cols: 2, padding: 2, marginLeft: 2, lineHeight: 0});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment