-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathgenerate.js
More file actions
80 lines (71 loc) · 2.03 KB
/
generate.js
File metadata and controls
80 lines (71 loc) · 2.03 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
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,
};