• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1const utils = require('./utils');
2const tableLayout = require('./layout-manager');
3
4class Table extends Array {
5  constructor(options) {
6    super();
7
8    this.options = utils.mergeOptions(options);
9  }
10
11  toString() {
12    let array = this;
13    let headersPresent = this.options.head && this.options.head.length;
14    if (headersPresent) {
15      array = [this.options.head];
16      if (this.length) {
17        array.push.apply(array, this);
18      }
19    } else {
20      this.options.style.head = [];
21    }
22
23    let cells = tableLayout.makeTableLayout(array);
24
25    cells.forEach(function(row) {
26      row.forEach(function(cell) {
27        cell.mergeTableOptions(this.options, cells);
28      }, this);
29    }, this);
30
31    tableLayout.computeWidths(this.options.colWidths, cells);
32    tableLayout.computeHeights(this.options.rowHeights, cells);
33
34    cells.forEach(function(row) {
35      row.forEach(function(cell) {
36        cell.init(this.options);
37      }, this);
38    }, this);
39
40    let result = [];
41
42    for (let rowIndex = 0; rowIndex < cells.length; rowIndex++) {
43      let row = cells[rowIndex];
44      let heightOfRow = this.options.rowHeights[rowIndex];
45
46      if (rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)) {
47        doDraw(row, 'top', result);
48      }
49
50      for (let lineNum = 0; lineNum < heightOfRow; lineNum++) {
51        doDraw(row, lineNum, result);
52      }
53
54      if (rowIndex + 1 == cells.length) {
55        doDraw(row, 'bottom', result);
56      }
57    }
58
59    return result.join('\n');
60  }
61
62  get width() {
63    let str = this.toString().split('\n');
64    return str[0].length;
65  }
66}
67
68function doDraw(row, lineNum, result) {
69  let line = [];
70  row.forEach(function(cell) {
71    line.push(cell.draw(lineNum));
72  });
73  let str = line.join('');
74  if (str.length) result.push(str);
75}
76
77module.exports = Table;
78