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

Add support for static evaluation of ?? operator #14837

Merged
merged 1 commit into from Aug 9, 2022
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
5 changes: 5 additions & 0 deletions packages/babel-traverse/src/path/evaluation.ts
Expand Up @@ -309,6 +309,11 @@ function _evaluate(path: NodePath, state: State): any {
if (!state.confident) return;

return left && right;
case "??":
state.confident = leftConfident && (left != null || rightConfident);
if (!state.confident) return;

return left ?? right;
}
}

Expand Down
8 changes: 8 additions & 0 deletions packages/babel-traverse/test/evaluation.js
Expand Up @@ -68,6 +68,14 @@ describe("evaluation", function () {
expect(getPath("0 && x === 'y'").get("body")[0].evaluate().value).toBe(0);
});

it("should handle ??", function () {
expect(getPath("null ?? 42").get("body")[0].evaluate().value).toBe(42);
expect(getPath("void 0 ?? 42").get("body")[0].evaluate().value).toBe(42);
expect(getPath("0 ?? 42").get("body")[0].evaluate().value).toBe(0);
expect(getPath("x ?? 42").get("body")[0].evaluate().confident).toBe(false);
expect(getPath("42 ?? x === 'y'").get("body")[0].evaluate().value).toBe(42);
});

it("should work with repeated, indeterminate identifiers", function () {
expect(
getPath("var num = foo(); (num > 0 && num < 100);")
Expand Down