Skip to content

Commit

Permalink
handle default statements with fallthrough properly [fix babel#423]
Browse files Browse the repository at this point in the history
  • Loading branch information
vigneshshanmugam committed Mar 21, 2017
1 parent 2379fc1 commit d1dcc76
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 15 deletions.
26 changes: 26 additions & 0 deletions packages/babel-plugin-minify-simplify/__tests__/simplify-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3098,4 +3098,30 @@ describe("simplify-plugin", () => {
}
expect(transform(source)).toBe(expected);
});

it("should fix issue#423 with fallthrough in default case", () => {
const source = unpad(
`
function foo(bar) {
switch (bar) {
case 'a':
return 1;
case 'b':
default:
return 4;
case 'c':
return 3;
}
}
`
);
const expected = unpad(
`
function foo(bar) {
return bar === 'a' ? 1 : bar === 'c' ? 3 : 4;
}
`
);
expect(transform(source)).toBe(expected);
});
});
24 changes: 9 additions & 15 deletions packages/babel-plugin-minify-simplify/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1263,7 +1263,7 @@ module.exports = ({ types: t }) => {
return;
}

const consTestPairs = [];
let consTestPairs = [];
let fallThru = [];
let defaultRet;
for (const switchCase of node.cases) {
Expand All @@ -1273,6 +1273,7 @@ module.exports = ({ types: t }) => {

const cons = switchCase.consequent[0];

// default case
if (!switchCase.test) {
if (!t.isReturnStatement(cons)) {
return;
Expand All @@ -1282,11 +1283,7 @@ module.exports = ({ types: t }) => {
}

if (!switchCase.consequent.length) {
if (fallThru.length) {
fallThru.push(switchCase.test);
} else {
fallThru = [switchCase.test];
}
fallThru.push(switchCase.test);
continue;
}

Expand All @@ -1300,7 +1297,8 @@ module.exports = ({ types: t }) => {
node.discriminant,
switchCase.test
);
if (fallThru.length) {

if (fallThru.length && !defaultRet) {
test = fallThru.reduceRight(
(right, test) =>
t.logicalExpression(
Expand All @@ -1310,8 +1308,8 @@ module.exports = ({ types: t }) => {
),
test
);
fallThru = [];
}
fallThru = [];

consTestPairs.push([test, cons.argument || VOID_0]);
}
Expand Down Expand Up @@ -1387,11 +1385,7 @@ module.exports = ({ types: t }) => {
}

if (!switchCase.consequent.length) {
if (fallThru.length) {
fallThru.push(switchCase.test);
} else {
fallThru = [switchCase.test];
}
fallThru.push(switchCase.test);
continue;
}

Expand All @@ -1416,7 +1410,7 @@ module.exports = ({ types: t }) => {
node.discriminant,
switchCase.test
);
if (fallThru.length) {
if (fallThru.length && !defaultExpr) {
test = fallThru.reduceRight(
(right, test) =>
t.logicalExpression(
Expand All @@ -1426,8 +1420,8 @@ module.exports = ({ types: t }) => {
),
test
);
fallThru = [];
}
fallThru = [];

exprTestPairs.push([test, cons.expression]);
}
Expand Down

0 comments on commit d1dcc76

Please sign in to comment.