Last active
August 29, 2015 14:22
-
-
Save afonsomatos/651cf26e709a4491a112 to your computer and use it in GitHub Desktop.
Lightweight table creator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* Easy to use table creator | |
* afonsomatos <[email protected]> | |
* | |
* @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