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

Implement support for evaluating computed properties. #15313

Merged
merged 2 commits into from Jan 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 16 additions & 4 deletions packages/babel-traverse/src/path/evaluation.ts
Expand Up @@ -158,20 +158,32 @@ function _evaluate(path: NodePath, state: State): any {
return evaluateCached(path.get("expression"), state);
}

// "foo".length
// "foo".length, "foo"[0]
if (
path.isMemberExpression() &&
!path.parentPath.isCallExpression({ callee: path.node })
) {
const property = path.get("property");
const object = path.get("object");

if (object.isLiteral() && property.isIdentifier()) {
if (object.isLiteral()) {
// @ts-expect-error todo(flow->ts): instead of typeof - would it be better to check type of ast node?
const value = object.node.value;
const type = typeof value;
if (type === "number" || type === "string") {
return value[property.node.name];

let key = null;
if (path.node.computed) {
key = evaluateCached(property, state);
if (!state.confident) return;
} else if (property.isIdentifier()) {
key = property.node.name;
}
if (
(type === "number" || type === "string") &&
key != null &&
(typeof key === "number" || typeof key === "string")
) {
return value[key];
}
}
}
Expand Down
10 changes: 10 additions & 0 deletions packages/babel-traverse/test/evaluation.js
Expand Up @@ -114,6 +114,16 @@ describe("evaluation", function () {
.get("body.0.declarations.0.init")
.evaluate().value,
).toBe(3);
expect(
getPath("var x = 'hello world'[6]")
.get("body.0.declarations.0.init")
.evaluate().value,
).toBe("w");
expect(
getPath("var length = 1; var x = 'abc'[length];")
.get("body.1.declarations.0.init")
.evaluate().value,
).toBe("b");
const member_expr = getPath(
"var x = Math.min(2,Math.max(3,4));var y = Math.random();",
);
Expand Down