-
Notifications
You must be signed in to change notification settings - Fork 36
/
resolveDefiniteBinaryExpressions.js
35 lines (34 loc) · 1.31 KB
/
resolveDefiniteBinaryExpressions.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
import {badValue} from '../config.js';
import {Sandbox} from '../utils/sandbox.js';
import {evalInVm} from '../utils/evalInVm.js';
import {doesBinaryExpressionContainOnlyLiterals} from '../utils/doesBinaryExpressionContainOnlyLiterals.js';
/**
* Resolve definite binary expressions.
* E.g.
* 5 * 3 ==> 15;
* '2' + 2 ==> '22';
* @param {Arborist} arb
* @param {Function} candidateFilter (optional) a filter to apply on the candidates list
* @return {Arborist}
*/
function resolveDefiniteBinaryExpressions(arb, candidateFilter = () => true) {
let sharedSb;
for (let i = 0; i < arb.ast.length; i++) {
const n = arb.ast[i];
if (n.type === 'BinaryExpression' && doesBinaryExpressionContainOnlyLiterals(n) && candidateFilter(n)) {
sharedSb = sharedSb || new Sandbox();
const replacementNode = evalInVm(n.src, sharedSb);
if (replacementNode !== badValue) {
// Fix issue where a number below zero would be replaced with a string
if (replacementNode.type === 'UnaryExpression' && typeof n?.left?.value === 'number' && typeof n?.right?.value === 'number') {
const v = parseInt(replacementNode.argument.value + '');
replacementNode.argument.value = v;
replacementNode.argument.raw = `${v}`;
}
arb.markNode(n, replacementNode);
}
}
}
return arb;
}
export default resolveDefiniteBinaryExpressions;