Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend JSX Binary Operations Evaluation #546

Merged
merged 2 commits into from
Aug 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 41 additions & 19 deletions packages/compiler/react/evaluator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,25 +160,10 @@ export const evaluateAstNode = (
}

if (t.isBinaryExpression(ast)) {
if (ast.operator === '+') {
const left = evaluateAstNode(ast.left, staticContext) as number;
const right = evaluateAstNode(ast.right, staticContext) as number;
return left + right;
} else if (ast.operator === '-') {
return (
evaluateAstNode(ast.left, staticContext) -
evaluateAstNode(ast.right, staticContext)
);
} else if (ast.operator === '*') {
return (
evaluateAstNode(ast.left, staticContext) *
evaluateAstNode(ast.right, staticContext)
);
} else if (ast.operator === '/') {
return (
evaluateAstNode(ast.left, staticContext) /
evaluateAstNode(ast.right, staticContext)
);
const left = evaluateAstNode(ast.left, staticContext);
const right = evaluateAstNode(ast.right, staticContext);
if (typeof left === 'number' && typeof right === 'number') {
return evaluateBinaryExpression(left, right, ast.operator);
}
}

Expand Down Expand Up @@ -210,3 +195,40 @@ export const valueToAst = (value: unknown) => {
throw new Error(`Cannot convert value to AST: ${String(value)}`);
}
};

function evaluateBinaryExpression(
left: number,
right: number,
operator: t.BinaryExpression['operator'],
): any {
switch (operator) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
case '<':
return left < right;
case '>':
return left > right;
case '<=':
return left <= right;
case '>=':
return left >= right;
case '==':
// eslint-disable-next-line eqeqeq
return left == right;
case '!=':
// eslint-disable-next-line eqeqeq
return left != right;
case '===':
return left === right;
case '!==':
return left !== right;
default:
return undefined;
}
}