-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathgenerate.js
More file actions
160 lines (140 loc) · 4.59 KB
/
generate.js
File metadata and controls
160 lines (140 loc) · 4.59 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
/**
* See generate.md
*/
const { performance } = require('perf_hooks');
const { generateBasicTable, generateComplexTable, generateComplexRow } = require('../lib/generate');
const argv = process.argv;
const timeScales = [
['millisecond', 1000],
['second', 60],
['minute', 60],
];
const duration = (v, scales = [...timeScales]) => {
const [unit, min] = scales.shift();
if (v > min && scales.length) {
return duration(v / min, scales);
}
let locale = undefined;
if (process.env.LANG) {
const userLocale = process.env.LANG.match(/[a-z]{2}_[A-Z]{2}/).shift();
if (userLocale.match(/^[a-z]{2}[-_][A-Z]{2}$/)) {
locale = userLocale.replace(/_/, '-');
}
}
return v.toLocaleString(locale, { style: 'unit', unit });
};
const argVal = (idx, def = 10) => {
if (argv[idx] && argv[idx].match(/^[0-9]+$/)) {
return parseInt(argv[idx], 10);
}
return def;
};
const optEnabled = (opt) => argv.indexOf(opt) > -1;
const optValue = (opt) => {
const idx = argv.indexOf(opt);
return idx > -1 ? argv[idx + 1] : 0;
};
const logMemory = (text = '') => {
let suffix = 'kb';
let used = process.memoryUsage().heapUsed / 1024;
if (used % 1024 > 1) {
used = used / 1024;
suffix = 'mb';
}
return `Memory usage ${text}: ${used}${suffix}`;
};
const printHelp = () => {
console.log(`node scripts/generate [ROWS = 10] [COLS = 10]`);
[
['--print', 'Print the generated table to the screen.'],
['--dump', 'Print the generated table code to the screen.'],
['--complex', 'Generate a complex table (basic tables are generated by default)'],
['--debug', 'Print table debugging output (warnings only).'],
].forEach(([opt, desc]) => console.log(` ${opt} ${desc}`));
};
const dumpTable = (t) => {
const lines = [];
lines.push(`const table = new Table();`);
lines.push(`table.push(`);
t.forEach((row) => {
if (row.length) {
let prefix = ' ';
let suffix = '';
const multiLine = row.length > 1 && row.some((v) => v.content !== undefined);
if (multiLine) {
lines.push(' [');
}
const cellLines = [];
row.forEach((cell) => {
if (cell.content) {
const attrib = [];
Object.entries(cell).forEach(([k, v]) => {
if (!['style'].includes(k)) {
attrib.push(`${k}: ${typeof v === 'string' ? `'${v}'` : v}`);
}
});
cellLines.push(`{ ${attrib.join(', ')} },`);
} else {
cellLines.push(`${typeof cell === 'string' ? `'${cell}'` : cell}`);
}
});
if (multiLine) {
cellLines.forEach((cl) => lines.push([prefix, cl, suffix].join('')));
lines.push(' ],');
} else {
lines.push(` [${cellLines.join(',')}]`);
}
} else {
lines.push(' [],');
}
});
lines.push(');');
lines.push('console.log(table.toString());');
return lines.forEach((line) => console.log(line));
};
if (optEnabled('--help')) {
printHelp();
process.exit(0);
}
const results = [];
results.push(logMemory('at startup'));
const rows = argVal(2);
const cols = argVal(3);
const maxRowSpan = rows > 10 ? Math.ceil(Math.round(rows * 0.1)) : Math.ceil(rows / 2);
const maxColSpan = cols;
const complex = optEnabled('--complex');
console.log(`Generating ${complex ? 'complex' : 'basic'} table with ${rows} rows and ${cols} columns:`);
if (complex) {
console.log(`Max rowSpan: ${maxRowSpan}`, `Max colSpan ${maxColSpan}`);
}
const options = {
tableOptions: {},
};
if (optEnabled('--compact')) {
options.tableOptions.style = { compact: true };
}
if (optEnabled('--head')) {
const head = generateComplexRow(0, 1, cols, {}, { maxCols: cols - 1 });
options.tableOptions.head = head;
}
const colWidth = optValue('--col-width');
if (colWidth) {
options.tableOptions.colWidths = [];
for (let i = 0; i < cols; i++) {
options.tableOptions.colWidths.push(parseInt(colWidth, 10));
}
}
// console.log(`table: ${rows} rows X ${cols} columns; ${rows * cols} total cells`);
// console.time('build table');
const buildStart = performance.now();
const table = complex ? generateComplexTable(rows, cols, options) : generateBasicTable(rows, cols, options);
// console.timeEnd('build table');
results.push(logMemory('after table build'));
results.push(`table built in ${duration(performance.now() - buildStart)}`);
const start = performance.now();
const output = table.toString();
results.push(logMemory('after table rendered'));
results.push(`table rendered in ${duration(performance.now() - start)}`);
if (optEnabled('--print')) console.log(output);
if (optEnabled('--dump')) dumpTable(table);
results.forEach((result) => console.log(result));