-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMDTable.js
More file actions
120 lines (98 loc) · 2.95 KB
/
MDTable.js
File metadata and controls
120 lines (98 loc) · 2.95 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
const defaultOptions = {};
class MDTable {
#columns = [];
#columnWidth = new Map();
#options = {};
constructor(data, options) {
this.#options = {
...options,
...defaultOptions
};
this.data = data;
this.#init();
}
toString() {
return [
this.#renderHeader(),
this.#renderHeaderSplit(),
...this.data.map((item) => this.#renderRow(item)),
].join("\n");
}
#init() {
this.#makeColumns();
this.#calcColumnWidth();
}
#makeColumns() {
if (this.#options.columns !== undefined) {
this.#columns = this.#options.columns;
return;
}
const columns = new Set();
this.data.forEach(i => {
Object.entries(i).forEach(([key, _]) => {
columns.add(key);
})
})
this.#columns = [...columns];
}
#calcColumnWidth() {
const result = new Map();
// Add header to data fot calculate length
const headerData = {};
this.#columns.forEach(i => headerData[i] = i);
const data = [...this.data, headerData];
data.forEach(i => {
Object.entries(i).forEach(([key, value]) => {
const length = String(value ?? "").trim().length
if (!result.has(key)) {
result.set(key, length);
} else {
if ((result.get(key) ?? 0) < length) {
result.set(key, length)
}
}
})
});
this.#columnWidth = result;
}
#textAsWidth(text, width) {
if (width === undefined) return text;
let spaces = width - text.length;
if (spaces < 0) spaces = 0;
return text.trim() + " ".repeat(spaces);
}
#renderHeader() {
let header = '| ';
const last = this.#columns.length;
this.#columns.forEach((i, index) => {
const width = this.#columnWidth.get(i);
header += this.#textAsWidth(i, width);
header += last === (index + 1) ? " |" : " | ";
});
return header;
}
#renderHeaderSplit() {
let header = '|';
const last = this.#columns.length;
this.#columns.forEach((i, index) => {
const width = this.#columnWidth.get(i) ?? 0;
header += "-".repeat(width + 2) + "|";
});
return header;
}
#renderRow(item) {
if (typeof item === 'string') return `| ${item} |`
let row = '| ';
const last = this.#columns.length;
this.#columns.forEach((key, index) => {
const text = String(item[key] ?? '');
const width = this.#columnWidth.get(key) ?? 0;
row += this.#textAsWidth(text, width);
row += last === (index + 1) ? " |" : " | ";
});
return row;
}
}
module.exports = {
MDTable
}