Skip to content

Commit 5d24d43

Browse files
committed
refactor: @putout/plugin-remove-unreachable-code: siblings
1 parent e109fd2 commit 5d24d43

File tree

1 file changed

+37
-33
lines changed

1 file changed

+37
-33
lines changed
Lines changed: 37 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,58 @@
11
'use strict';
22

33
const {types, operator} = require('putout');
4+
const {remove} = operator;
5+
46
const {
57
isExpressionStatement,
68
isFunctionDeclaration,
79
isBlockStatement,
810
} = types;
911

10-
const {remove} = operator;
12+
const not = (fn) => (...a) => !fn(...a);
1113

1214
module.exports.report = () => `Unreachable code`;
1315

14-
module.exports.fix = ({siblings}) => {
15-
for (const sibling of siblings) {
16-
remove(sibling);
17-
}
18-
};
19-
20-
const processBlock = (push, path, leaf) => {
21-
const siblings = path.getAllNextSiblings();
22-
23-
if (!siblings.length)
24-
return;
25-
26-
if (leaf) {
27-
const [first] = siblings;
28-
29-
if (!path.node.argument && (isBlockStatement(first) || isExpressionStatement(first)))
30-
return false;
31-
}
32-
33-
for (const sibling of siblings) {
34-
if (isFunctionDeclaration(sibling))
35-
continue;
36-
37-
push({
38-
path: sibling,
39-
siblings: [sibling],
40-
});
41-
}
16+
module.exports.fix = (path) => {
17+
remove(path);
4218
};
4319

4420
module.exports.traverse = ({push}) => ({
4521
'ReturnStatement|ThrowStatement'(path) {
46-
let leaf = true;
47-
4822
while (path.parentPath?.isBlockStatement()) {
49-
processBlock(push, path, leaf);
23+
const siblings = path.getAllNextSiblings();
24+
const {argument} = path.node;
25+
5026
path = path.parentPath;
51-
leaf = false;
27+
28+
if (checkFirstSibling({argument, siblings}))
29+
continue;
30+
31+
processSiblings({
32+
push,
33+
siblings,
34+
});
5235
}
5336
},
5437
});
38+
39+
const processSiblings = ({push, siblings}) => {
40+
if (!siblings.length)
41+
return;
42+
43+
siblings
44+
.filter(not(isFunctionDeclaration))
45+
.map(push);
46+
};
47+
48+
function checkFirstSibling({argument, siblings}) {
49+
if (argument)
50+
return false;
51+
52+
const [first] = siblings;
53+
54+
if (isBlockStatement(first))
55+
return true;
56+
57+
return isExpressionStatement(first);
58+
}

0 commit comments

Comments
 (0)