UNPKG

1.67 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag `else` after a `return` in `if`
3 * @author Ian Christian Myers
4 */
5
6//------------------------------------------------------------------------------
7// Rule Definition
8//------------------------------------------------------------------------------
9
10module.exports = function(context) {
11
12 "use strict";
13
14 //--------------------------------------------------------------------------
15 // Helpers
16 //--------------------------------------------------------------------------
17
18 function checkForReturnStatement(node, alternate) {
19 if (node.type === "ReturnStatement") {
20 context.report(alternate, "Unexpected 'else' after 'return'​.");
21 }
22 }
23
24 //--------------------------------------------------------------------------
25 // Public API
26 //--------------------------------------------------------------------------
27
28 return {
29
30 "IfStatement": function(node) {
31
32 // Don't bother finding a ReturnStatement, if there's no `else`.
33 if (node.alternate && node.consequent) {
34
35 // If we have a BlockStatement, check each consequent body node.
36 if (node.consequent.type === "BlockStatement") {
37 node.consequent.body.forEach(function (bodyNode) {
38 checkForReturnStatement(bodyNode, node.alternate);
39 });
40
41 // If not a block statement, make sure the consequent isn't a
42 // ReturnStatement
43 } else {
44 checkForReturnStatement(node.consequent, node.alternate);
45 }
46 }
47 }
48
49 };
50
51};