table.js
1.8 KB
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
var utils = require('./utils');
var tableLayout = require('./layout-manager');
var _ = require('lodash');
function Table(options){
this.options = utils.mergeOptions(options);
}
Table.prototype.__proto__ = Array.prototype;
Table.prototype.toString = function(){
var array = this;
var 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=[];
}
var cells = tableLayout.makeTableLayout(array);
_.forEach(cells,function(row){
_.forEach(row,function(cell){
cell.mergeTableOptions(this.options,cells);
},this);
},this);
tableLayout.computeWidths(this.options.colWidths,cells);
tableLayout.computeHeights(this.options.rowHeights,cells);
_.forEach(cells,function(row,rowIndex){
_.forEach(row,function(cell,cellIndex){
cell.init(this.options);
},this);
},this);
var result = [];
for(var rowIndex = 0; rowIndex < cells.length; rowIndex++){
var row = cells[rowIndex];
var heightOfRow = this.options.rowHeights[rowIndex];
if(rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)){
doDraw(row,'top',result);
}
for(var lineNum = 0; lineNum < heightOfRow; lineNum++){
doDraw(row,lineNum,result);
}
if(rowIndex + 1 == cells.length){
doDraw(row,'bottom',result);
}
}
return result.join('\n');
};
function doDraw(row,lineNum,result){
var line = [];
_.forEach(row,function(cell){
line.push(cell.draw(lineNum));
});
var str = line.join('');
if(str.length) result.push(str);
}
Table.prototype.__defineGetter__('width', function (){
var str = this.toString().split("\n");
return str[0].length;
});
module.exports = Table;