MCPcopy Create free account
hub / github.com/cortex-js/compute-engine / exprToStringRecursive

Function exprToStringRecursive

test/utils.ts:44–100  ·  view source on GitHub ↗

* Special printing utility for printing the *MathJson* representation - of either a boxed or * un-boxed expression. * * If an *Expression*, the **pretty** (prettified) MathJson representation is printed. * * Conveniently - prints on one line if expr. is less than local `MAX_LINE_LENGTH` (e.g. 7

(expr: ExpressionInput, start: number)

Source from the content-addressed store, hash-verified

42 */
43function exprToStringRecursive(expr: ExpressionInput, start: number): string {
44 const indent = ' '.repeat(start);
45
46 if (start > 50) return indent + '...';
47
48 if (expr === null) return 'null';
49 if (expr instanceof _BoxedExpression) {
50 const ce = expr.engine;
51 return exprToStringRecursive(
52 ce.expr(expr, { form: 'raw' }).toMathJson({ prettify: true }), // The default is 'prettify: true'
53 start
54 );
55 }
56
57 if (Array.isArray(expr)) {
58 const elements = expr.map((x) => exprToStringRecursive(x, start + 2));
59 const result = `[${elements.join(', ')}]`;
60 if (start + result.length < MAX_LINE_LENGTH) return result;
61 return `[\n${indent} ${elements.join(`,\n${indent} `)}\n${indent}]`;
62 }
63 if (typeof expr === 'object') {
64 const elements = {};
65
66 for (const key of Object.keys(expr)) {
67 if (expr[key] instanceof _BoxedExpression) {
68 elements[key] = exprToStringRecursive(
69 expr[key] as ExpressionInput,
70 start + 2
71 );
72 } else if (expr[key] === null) {
73 elements[key] = 'null';
74 } else if (expr[key] === undefined) {
75 elements[key] = 'undefined';
76 } else if (typeof expr[key] === 'object' && 'json' in expr[key]) {
77 elements[key] = exprToStringRecursive(expr[key], start + 2);
78 } else elements[key] = exprToStringRecursive(expr[key], start + 2);
79 }
80
81 const result = `{${Object.keys(expr)
82 .map((key) => `${key}: ${elements[key]}`)
83 .join('; ')}}`;
84 if (start + result.length < MAX_LINE_LENGTH) return result;
85 return (
86 `{\n` +
87 Object.keys(expr)
88 .map((key) => `${indent} ${key}: ${elements[key]}`)
89 .join(`;\n${indent}`) +
90 '\n' +
91 indent +
92 '}'
93 );
94 }
95 if (typeof expr === 'string' && start === 0) return expr;
96 if (typeof expr === 'string') return `"${expr}"`;
97
98 return JSON.stringify(expr, null, 2);
99}
100
101export function exprToString(expr: ExpressionInput | null | undefined): string {

Callers 1

exprToStringFunction · 0.85

Calls 4

toMathJsonMethod · 0.65
exprMethod · 0.65
mapMethod · 0.65
keysMethod · 0.65

Tested by

no test coverage detected