LibJS: Implement logical assignment operators (&&=, ||=, ??=)

TC39 proposal, stage 4 as of 2020-07.
https://tc39.es/proposal-logical-assignment/
This commit is contained in:
Linus Groh 2020-10-05 16:49:43 +01:00 committed by Andreas Kling
parent d8d00d3ac7
commit aa71dae03c
Notes: sideshowbarker 2024-07-19 02:02:06 +09:00
6 changed files with 108 additions and 6 deletions

View file

@ -1,4 +1,4 @@
let x;
let x, o;
test("basic functionality", () => {
x = 1;
@ -54,6 +54,48 @@ test("basic functionality", () => {
expect(x).toBe(2);
});
test("logical assignment operators", () => {
// short circuiting evaluation
x = false;
expect((x &&= expect.fail())).toBeFalse();
x = true;
expect((x ||= expect.fail())).toBeTrue();
x = "foo";
expect((x ??= expect.fail())).toBe("foo");
const prepareObject = (shortCircuitValue, assignmentValue) => ({
get shortCircuit() {
return shortCircuitValue;
},
set shortCircuit(_) {
// assignment will short circuit in all test cases
// so its setter must never be called
expect().fail();
},
assignment: assignmentValue,
});
o = prepareObject(false, true);
expect((o.shortCircuit &&= "foo")).toBeFalse();
expect(o.shortCircuit).toBeFalse();
expect((o.assignment &&= "bar")).toBe("bar");
expect(o.assignment).toBe("bar");
o = prepareObject(true, false);
expect((o.shortCircuit ||= "foo")).toBeTrue();
expect(o.shortCircuit).toBeTrue();
expect((o.assignment ||= "bar")).toBe("bar");
expect(o.assignment).toBe("bar");
o = prepareObject("test", null);
expect((o.shortCircuit ??= "foo")).toBe("test");
expect(o.shortCircuit).toBe("test");
expect((o.assignment ??= "bar")).toBe("bar");
expect(o.assignment).toBe("bar");
});
test("evaluation order", () => {
for (const op of [
"=",
@ -69,6 +111,9 @@ test("evaluation order", () => {
"<<=",
">>=",
">>>=",
"&&=",
"||=",
"??=",
]) {
var a = [];
function b() {