The task is to display ascii table for a given array.
Input
The input is an 2D matrix. The matrix's row length is same with the length of an array. Alternatively, you can take input of an 2D matrix with the first row is a header. The outer dimension is the row.
Example Input:
[["License","2008-05-08","2009-03-11","2011-11-22","2013-08-12","2015-11-19"],["GPLv2","58.69%","52.2%","42.5%","33%","23%"],["GPLv3","1.64%","4.15%","6.5%","12%","9%"],["LGPL 2.1","11.39%","9.84%","?","6%","5%"],["LGPL 3.0","? (<0.64%)","0.37%","?","3%","2%"],["GPL family together","71.72% (+ <0.64%)","66.56%","?","54%","39%"]]
Output
The output of a table looks like below.
+---------------------+-------------------+------------+------------+------------+------------+
| License | 2008-05-08 | 2009-03-11 | 2011-11-22 | 2013-08-12 | 2015-11-19 |
+---------------------+-------------------+------------+------------+------------+------------+
| GPLv2 | 58.69% | 52.2% | 42.5% | 33% | 23% |
| GPLv3 | 1.64% | 4.15% | 6.5% | 12% | 9% |
| LGPL 2.1 | 11.39% | 9.84% | ? | 6% | 5% |
| LGPL 3.0 | ? (<0.64%) | 0.37% | ? | 3% | 2% |
| GPL family together | 71.72% (+ <0.64%) | 66.56% | ? | 54% | 39% |
+---------------------+-------------------+------------+------------+------------+------------+
Each cell has exactly one space on the left and at least one space on the right, padded until the bars aligned. However, at least one cell has only one space on its right.
Test cases
Input:
[["Hello", "World", "!!!"],["aa", "bbbbbbbbb", "CcC"], ["Pyth", "CJam", "GolfScript"]]
Output:
+-------+-----------+------------+
| Hello | World | !!! |
+-------+-----------+------------+
| aa | bbbbbbbbb | CcC |
| Pyth | CJam | GolfScript |
+-------+-----------+------------+
Example submission
function ascii_table(array, header) {
var lengths = array[0].map(function(_, i) {
var col = array.map(function(row) {
if (row[i] != undefined) {
return row[i].length;
} else {
return 0;
}
});
return Math.max.apply(Math, col);
});
array = array.map(function(row) {
return '| ' + row.map(function(item, i) {
var size = item.length;
if (size < lengths[i]) {
item += new Array(lengths[i]-size+1).join(' ');
}
return item;
}).join(' | ') + ' |';
});
var sep = '+' + lengths.map(function(length) {
return new Array(length+3).join('-');
}).join('+') + '+';
if (header) {
return sep + '\n' + array[0] + '\n' + sep + '\n' +
array.slice(1).join('\n') + '\n' + sep;
} else {
return sep + '\n' + array.join('\n') + '\n' + sep;
}
}
This is code-golf, so the submission with the least amount of bytes wins!