Skip to content

Commit

Permalink
Implement support for evaluating computed properties. (#15313)
Browse files Browse the repository at this point in the history
  • Loading branch information
JBYoshi committed Jan 2, 2023
1 parent 7d20fdf commit c814643
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
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

0 comments on commit c814643

Please sign in to comment.