@trenskow/print 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/lib/index.js +34 -0
  2. package/package.json +5 -1
package/lib/index.js CHANGED
@@ -6,6 +6,9 @@
6
6
  // See license in LICENSE.
7
7
  //
8
8
 
9
+ import NullStream from '@trenskow/null-stream';
10
+ import keyd from 'keyd';
11
+
9
12
  let ttyColumn = 0;
10
13
 
11
14
  const printer = (stream) => {
@@ -70,6 +73,37 @@ const printer = (stream) => {
70
73
 
71
74
  };
72
75
 
76
+ print.table = ({ columns, data, options: { header } = { header: true } }) => {
77
+
78
+ if (!Array.isArray(data)) data = [data];
79
+
80
+ data = data.map((row) => Object.keys(columns).map((column) => `${keyd(row).get(column) || ''}`));
81
+
82
+ if (!stream.isTTY) {
83
+ print(data.map((row) => row.join('\t')).join('\n'));
84
+ return;
85
+ }
86
+
87
+ data = [header ? Object.values(columns) : [], ...data];
88
+
89
+ const columnWidth = Object.keys(columns)
90
+ .map((_, idx) => {
91
+ return Math.max(...data.map((row) => row[idx].length));
92
+ });
93
+
94
+ data.forEach((row, idx) => {
95
+ print.nn(idx === 0 && header ? '\x1b[1m' : '\x1b[0m');
96
+ print(row.map((cell, idx) => cell.padEnd(columnWidth[idx])).join(' '));
97
+ });
98
+
99
+ };
100
+
101
+ Object.defineProperty(print, 'tty', {
102
+ get: () => {
103
+ return stream.isTTY ? print : printer(new NullStream());
104
+ }
105
+ });
106
+
73
107
  return print;
74
108
 
75
109
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trenskow/print",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "A simple package for printing to the console (or other streams).",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -28,5 +28,9 @@
28
28
  "@eslint/js": "^9.17.0",
29
29
  "eslint": "^9.17.0",
30
30
  "globals": "^15.14.0"
31
+ },
32
+ "dependencies": {
33
+ "@trenskow/null-stream": "^0.1.1",
34
+ "keyd": "^2.1.17"
31
35
  }
32
36
  }