Skip to content

Commit

Permalink
Add support for static evaluation of ?? operator (#14837)
Browse files Browse the repository at this point in the history
  • Loading branch information
djpohly committed Aug 9, 2022
1 parent e2442e1 commit da31b01
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
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

0 comments on commit da31b01

Please sign in to comment.