File: index.js

package info (click to toggle)
node-ansi-color-table 1.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 112 kB
  • sloc: javascript: 221; makefile: 2
file content (92 lines) | stat: -rw-r--r-- 2,252 bytes parent folder | download | duplicates (2)
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
var ansi = require("ansi");
var padSegments = require("./lib/padsegments");

var colors = [
  "white",
  "black",
  "blue",
  "cyan",
  "green",
  "magenta",
  "red",
  "yellow",
  "grey",
  "brightBlack",
  "brightRed",
  "brightGreen",
  "brightYellow",
  "brightBlue",
  "brightMagenta",
  "brightCyan",
  "brightWhite"
];
var styles = [
  "bold",
  "italic",
  "underline",
  "inverse"
];

colors.forEach(function (color) {
  String.prototype[color] = function () {
    this._color = color;
    return this;
  };
});
styles.forEach(function (style) {
  String.prototype[style] = function () {
    if ( !this._styles ) this._styles = [];
    this._styles.push(style);
    return this;
  };
});

function printTable(table, opts, stream) {
  opts = opts || { align : [] };
  if ( opts.align === undefined ) opts.align = [];
  // compute row length
  if ( table.length === 0 ) return;
  // output stream
  stream = stream || process.stdout;
  var cursor = ansi(stream);
  var numCols = table.reduce(function (maxCols, col) {
    return ( col.length > maxCols ) ? col.length : maxCols;
  }, 0);
  var maxColumnLengths = Array(numCols);
  for ( var i = 0; i < numCols; i++ ) maxColumnLengths[i] = 0;
  table.map(function (row) {
    var i = 0;
    for ( ; i < numCols; i++ ) {
      if ( row[i] !== undefined && row[i].length > maxColumnLengths[i] ) {
        maxColumnLengths[i] = row[i].length;
      }
    }
  });

  // print table
  var output = [];
  var segments;
  table.forEach(function (row, indexRow) {
    row.forEach(function (col, indexCol) {
      var align = ( opts.headerAlign && indexRow === 0 ) ? opts.headerAlign : opts.align[indexCol];
      segments = padSegments(col.toString(), maxColumnLengths[indexCol], align);
      stream.write(segments.left);
      if ( col._color ) {
        cursor[col._color]();
      }
      if ( col._styles ) {
        col._styles.forEach( function (style) {
          cursor[style]();
        });
      }
      stream.write(col.toString());
      cursor.reset();
      stream.write(segments.right);
      if ( indexCol < row.length-1 ) stream.write(opts.separator || "  ");
    });
    stream.write("\n");
  });
  if ( stream != process.stdout ) stream.end();
}

module.exports = exports = printTable;