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

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