Skip to content

Commit da31b01

Browse files
authored
Add support for static evaluation of ?? operator (#14837)
1 parent e2442e1 commit da31b01

2 files changed

Lines changed: 13 additions & 0 deletions

File tree

packages/babel-traverse/src/path/evaluation.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,11 @@ function _evaluate(path: NodePath, state: State): any {
309309
if (!state.confident) return;
310310

311311
return left && right;
312+
case "??":
313+
state.confident = leftConfident && (left != null || rightConfident);
314+
if (!state.confident) return;
315+
316+
return left ?? right;
312317
}
313318
}
314319

packages/babel-traverse/test/evaluation.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,14 @@ describe("evaluation", function () {
6868
expect(getPath("0 && x === 'y'").get("body")[0].evaluate().value).toBe(0);
6969
});
7070

71+
it("should handle ??", function () {
72+
expect(getPath("null ?? 42").get("body")[0].evaluate().value).toBe(42);
73+
expect(getPath("void 0 ?? 42").get("body")[0].evaluate().value).toBe(42);
74+
expect(getPath("0 ?? 42").get("body")[0].evaluate().value).toBe(0);
75+
expect(getPath("x ?? 42").get("body")[0].evaluate().confident).toBe(false);
76+
expect(getPath("42 ?? x === 'y'").get("body")[0].evaluate().value).toBe(42);
77+
});
78+
7179
it("should work with repeated, indeterminate identifiers", function () {
7280
expect(
7381
getPath("var num = foo(); (num > 0 && num < 100);")

0 commit comments

Comments
 (0)