Skip to content

Commit

Permalink
Measure length of column on stripped string
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Feb 21, 2017
1 parent abd95cb commit ecd5aa4
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
14 changes: 8 additions & 6 deletions columns.js
Expand Up @@ -3,22 +3,24 @@
var from = require('es5-ext/array/from')
, iterable = require('es5-ext/iterable/validate-object')
, stringifiable = require('es5-ext/object/validate-stringifiable')
, pad = require('es5-ext/string/#/pad');
, repeat = require('es5-ext/string/#/repeat')
, strip = require('./strip');

module.exports = function (rows/*, options*/) {
var options = Object(arguments[1]), cols = [];
return from(iterable(rows), function (row, index) {
return from(iterable(row), function (str, index) {
var col = cols[index];
var col = cols[index], strLength;
if (!col) col = cols[index] = { width: 0 };
str = stringifiable(str);
if (str.length > col.width) col.width = str.length;
return str;
strLength = strip(str).length;
if (strLength > col.width) col.width = strLength;
return { str: str, length: strLength };
});
}).map(function (row) {
return row.map(function (item, index) {
if (index === (row.length - 1)) return item;
return pad.call(item, ' ', -cols[index].width);
var pad = repeat.call(' ', cols[index].width - item.length);
return item.str + pad;
}).join((options.sep == null) ? ' | ' : options.sep);
}).join('\n') + '\n';
};
10 changes: 5 additions & 5 deletions test/columns.js
Expand Up @@ -12,21 +12,21 @@ module.exports = function (t, a) {
'A | BC | DEF\n1 | 23 | 456\n',
"Small items");
a(t([ [ "A", "BC", "DEF" ], [ 12, 234, 4567 ] ]),
'A | BC | DEF\n12 | 234 | 4567\n',
'A | BC | DEF \n12 | 234 | 4567\n',
"Large items");
a(t([ [ "A", "BC", "DEF" ], [ 1234, 23456, 456789 ] ]),
'A | BC | DEF\n1234 | 23456 | 456789\n',
'A | BC | DEF \n1234 | 23456 | 456789\n',
"Very large items");

a(t([ [ "A" ], [ 1 ], [ 23 ], [ 456 ] ]),
'A\n1\n23\n456\n',
'A \n1 \n23 \n456\n',
"Single column");

a(t([ [ "ID" ], [ 1 ], [ 1, 23 ], [ 1, 23, 456 ] ]),
'ID\n1\n1 | 23\n1 | 23 | 456\n',
'ID\n1 \n1 | 23\n1 | 23 | 456\n',
"Force columns");

a(t([ [ "ID" ], [ "", "" ], [ 123, 123 ] ]),
'ID\n | \n123 | 123\n',
'ID \n | \n123 | 123\n',
"Empty cells");
};

0 comments on commit ecd5aa4

Please sign in to comment.