-
Notifications
You must be signed in to change notification settings - Fork 44
/
table.js
106 lines (88 loc) · 2.61 KB
/
table.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const debug = require('./debug');
const utils = require('./utils');
const tableLayout = require('./layout-manager');
class Table extends Array {
constructor(opts) {
super();
const options = utils.mergeOptions(opts);
Object.defineProperty(this, 'options', {
value: options,
enumerable: options.debug,
});
if (options.debug) {
switch (typeof options.debug) {
case 'boolean':
debug.setDebugLevel(debug.WARN);
break;
case 'number':
debug.setDebugLevel(options.debug);
break;
case 'string':
debug.setDebugLevel(parseInt(options.debug, 10));
break;
default:
debug.setDebugLevel(debug.WARN);
debug.warn(`Debug option is expected to be boolean, number, or string. Received a ${typeof options.debug}`);
}
Object.defineProperty(this, 'messages', {
get() {
return debug.debugMessages();
},
});
}
}
toString() {
let array = this;
let headersPresent = this.options.head && this.options.head.length;
if (headersPresent) {
array = [this.options.head];
if (this.length) {
array.push.apply(array, this);
}
} else {
this.options.style.head = [];
}
let cells = tableLayout.makeTableLayout(array);
cells.forEach(function (row) {
row.forEach(function (cell) {
cell.mergeTableOptions(this.options, cells);
}, this);
}, this);
tableLayout.computeWidths(this.options.colWidths, cells);
tableLayout.computeHeights(this.options.rowHeights, cells);
cells.forEach(function (row) {
row.forEach(function (cell) {
cell.init(this.options);
}, this);
}, this);
let result = [];
for (let rowIndex = 0; rowIndex < cells.length; rowIndex++) {
let row = cells[rowIndex];
let heightOfRow = this.options.rowHeights[rowIndex];
if (rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)) {
doDraw(row, 'top', result);
}
for (let lineNum = 0; lineNum < heightOfRow; lineNum++) {
doDraw(row, lineNum, result);
}
if (rowIndex + 1 == cells.length) {
doDraw(row, 'bottom', result);
}
}
return result.join('\n');
}
get width() {
let str = this.toString().split('\n');
return str[0].length;
}
}
Table.reset = () => debug.reset();
function doDraw(row, lineNum, result) {
let line = [];
row.forEach(function (cell) {
line.push(cell.draw(lineNum));
});
let str = line.join('');
if (str.length) result.push(str);
}
module.exports = Table;