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