-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinspect.js
91 lines (82 loc) · 2.29 KB
/
inspect.js
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
const indent = ' '.repeat(2);
const indentData = ' '.repeat(4);
export function inspectMatrix() {
return inspectMatrixWithOptions(this);
}
export function inspectMatrixWithOptions(matrix, options = {}) {
const {
maxRows = 15,
maxColumns = 10,
maxNumSize = 8,
padMinus = 'auto',
} = options;
return `${matrix.constructor.name} {
${indent}[
${indentData}${inspectData(matrix, maxRows, maxColumns, maxNumSize, padMinus)}
${indent}]
${indent}rows: ${matrix.rows}
${indent}columns: ${matrix.columns}
}`;
}
function inspectData(matrix, maxRows, maxColumns, maxNumSize, padMinus) {
const { rows, columns } = matrix;
const maxI = Math.min(rows, maxRows);
const maxJ = Math.min(columns, maxColumns);
const result = [];
if (padMinus === 'auto') {
padMinus = false;
loop: for (let i = 0; i < maxI; i++) {
for (let j = 0; j < maxJ; j++) {
if (matrix.get(i, j) < 0) {
padMinus = true;
break loop;
}
}
}
}
for (let i = 0; i < maxI; i++) {
let line = [];
for (let j = 0; j < maxJ; j++) {
line.push(formatNumber(matrix.get(i, j), maxNumSize, padMinus));
}
result.push(`${line.join(' ')}`);
}
if (maxJ !== columns) {
result[result.length - 1] += ` ... ${columns - maxColumns} more columns`;
}
if (maxI !== rows) {
result.push(`... ${rows - maxRows} more rows`);
}
return result.join(`\n${indentData}`);
}
function formatNumber(num, maxNumSize, padMinus) {
return (
num >= 0 && padMinus
? ` ${formatNumber2(num, maxNumSize - 1)}`
: formatNumber2(num, maxNumSize)
).padEnd(maxNumSize);
}
function formatNumber2(num, len) {
// small.length numbers should be as is
let str = num.toString();
if (str.length <= len) return str;
// (7)'0.00123' is better then (7)'1.23e-2'
// (8)'0.000123' is worse then (7)'1.23e-3',
let fix = num.toFixed(len);
if (fix.length > len) {
fix = num.toFixed(Math.max(0, len - (fix.length - len)));
}
if (
fix.length <= len &&
!fix.startsWith('0.000') &&
!fix.startsWith('-0.000')
) {
return fix;
}
// well, if it's still too long the user should've used longer numbers
let exp = num.toExponential(len);
if (exp.length > len) {
exp = num.toExponential(Math.max(0, len - (exp.length - len)));
}
return exp.slice(0);
}