| 1 |
"use strict"; |
| 2 |
|
| 3 |
var generate = require("es5-ext/array/generate") |
| 4 |
, from = require("es5-ext/array/from") |
| 5 |
, iterable = require("es5-ext/iterable/validate-object") |
| 6 |
, isValue = require("es5-ext/object/is-value") |
| 7 |
, stringifiable = require("es5-ext/object/validate-stringifiable") |
| 8 |
, repeat = require("es5-ext/string/#/repeat") |
| 9 |
, getStrippedLength = require("./get-stripped-length"); |
| 10 |
|
| 11 |
var push = Array.prototype.push; |
| 12 |
|
| 13 |
module.exports = function (inputRows /*, options*/) { |
| 14 |
var options = Object(arguments[1]) |
| 15 |
, colsMeta = [] |
| 16 |
, colsOptions = options.columns || [] |
| 17 |
, rows = []; |
| 18 |
|
| 19 |
from(iterable(inputRows), function (row) { |
| 20 |
var rowRows = [[]]; |
| 21 |
from(iterable(row), function (cellStr, columnIndex) { |
| 22 |
var cellRows = stringifiable(cellStr).split("\n"); |
| 23 |
while (cellRows.length > rowRows.length) rowRows.push(generate(columnIndex, "")); |
| 24 |
cellRows.forEach(function (cellRow, rowRowIndex) { |
| 25 |
rowRows[rowRowIndex][columnIndex] = cellRow; |
| 26 |
}); |
| 27 |
}); |
| 28 |
push.apply(rows, rowRows); |
| 29 |
}); |
| 30 |
|
| 31 |
return ( |
| 32 |
rows |
| 33 |
.map(function (row) { |
| 34 |
return from(iterable(row), function (str, index) { |
| 35 |
var col = colsMeta[index], strLength; |
| 36 |
if (!col) col = colsMeta[index] = { width: 0 }; |
| 37 |
str = stringifiable(str); |
| 38 |
strLength = getStrippedLength(str); |
| 39 |
if (strLength > col.width) col.width = strLength; |
| 40 |
return { str: str, length: strLength }; |
| 41 |
}); |
| 42 |
}) |
| 43 |
.map(function (row) { |
| 44 |
return row |
| 45 |
.map(function (item, index) { |
| 46 |
var pad, align = "left", colOptions = colsOptions && colsOptions[index]; |
| 47 |
align = colOptions && colOptions.align === "right" ? "right" : "left"; |
| 48 |
pad = repeat.call(" ", colsMeta[index].width - item.length); |
| 49 |
if (align === "left") return item.str + pad; |
| 50 |
return pad + item.str; |
| 51 |
}) |
| 52 |
.join(isValue(options.sep) ? options.sep : " | "); |
| 53 |
}) |
| 54 |
.join("\n") + "\n" |
| 55 |
); |
| 56 |
}; |