forked from mohsen1/better-console
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log_table.js
71 lines (57 loc) · 1.56 KB
/
log_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
var Table = require('cli-table');
module.exports = exports = function logTable(data){
if(typeof data !== 'object' || data === null){
console.log('');
return;
}
if(typeof data[Object.keys(data)[0]] !== 'object' || data[Object.keys(data)[0]] === null){
console.log('');
return;
}
var firstKey = Object.keys(data)[0];
var firstObject = data[firstKey];
var thead = Object.keys(firstObject);
thead.unshift('(index)');
var colWidths = thead.map(calculateColWidth);
Object.keys(data).forEach(function(rowKey){
var row = data[rowKey];
if(typeof row == 'object'){
Object.keys(row).forEach(function(k,i){
var width = calculateColWidth (row[k]);
if(colWidths[i+1] < width)
colWidths[i+1] = width;
});
}
});
var table = new Table({
head: thead,
colWidths: colWidths
});
Object.keys(data).forEach(function(rowKey){
var row = data[rowKey];
var rowValues = [];
if(typeof row == 'object'){
rowValues = Object.keys(row).map(function(k){
return row[k];
});
}
table.push([rowKey].concat(rowValues));
});
console.log(table.toString());
function calculateColWidth (item) {
var MAX_COL_WIDTH = 28;
var MIN_COL_WIDTH = 3;
var width = null;
if(item.toString){
if(item.toString().length > MAX_COL_WIDTH)
width = MAX_COL_WIDTH;
if(item.toString().length < MIN_COL_WIDTH)
width = MIN_COL_WIDTH;
else if(!width)
width = item.toString().length;
}else{
width = MAX_COL_WIDTH;
}
return width + 2;
}
};