Skip to content

Generate random basic/complex tables for performance testing and debugging. #294

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions lib/generate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
const Table = require('..');

const cellContent = ({ x, y, colSpan = 1, rowSpan = 1 }) => {
return `${y}-${x} (${rowSpan}x${colSpan})`;
};

const generateBasicTable = (rows, cols, options = {}) => {
const table = new Table(options);
for (let y = 0; y < rows; y++) {
let row = [];
for (let x = 0; x < cols; x++) {
row.push(cellContent({ y, x }));
}
table.push(row);
}
return table;
};

const randomNumber = (min, max, op = 'round') => {
return Math[op](Math.random() * (max - min) + min);
};

const next = (alloc, idx, dir = 1) => {
if (alloc[idx]) {
return next(alloc, idx + 1 * dir);
}
return idx;
};

const generateComplexRow = (y, spanX, cols, alloc, options = {}) => {
let x = next(alloc, 0);
const row = [];
while (x < cols) {
const { colSpans = {} } = options;
const opt = {
colSpan: colSpans[x] || next(alloc, randomNumber(x + 1, options.maxCols || cols, 'ceil'), -1) - x,
rowSpan: randomNumber(1, spanX),
};
row.push({ content: cellContent({ y, x, ...opt }), ...opt });
if (opt.rowSpan > 1) {
for (let i = 0; i < opt.colSpan; i++) {
alloc[x + i] = opt.rowSpan;
}
}

x = next(alloc, x + opt.colSpan);
}
return row;
};

const generateComplexRows = (y, rows, cols, alloc = {}, options = {}) => {
const remaining = rows - y;
let spanX = remaining > 1 ? randomNumber(1, remaining) : 1;
let lines = [];
while (spanX > 0) {
lines.push(generateComplexRow(y, spanX, cols, alloc, options));
y++;
spanX--;
Object.keys(alloc).forEach((idx) => {
alloc[idx]--;
if (alloc[idx] <= 0) delete alloc[idx];
});
}
return lines;
};

const generateComplexTable = (rows, cols, options = {}) => {
const table = new Table(options.tableOptions);
while (table.length < rows) {
let y = table.length || (table.options.head && 1) || 0;
generateComplexRows(y, rows, cols, options).forEach((row) => table.push(row));
}
return table;
};

module.exports = {
generateBasicTable,
generateComplexTable,
generateComplexRow,
};
160 changes: 160 additions & 0 deletions scripts/generate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,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));
Loading