node/tools/eslint/lib/rules/no-duplicate-case.js
Roman Reiss d91e10b3bd tools: update eslint to 0.24.0
PR-URL: https://github.com/nodejs/io.js/pull/2072
Reviewed-By: Yosuke Furukawa <yosuke.furukawa@gmail.com>
Reviewed-by: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Alex Kocharin <alex@kocharin.ru>
2015-06-29 19:02:17 +02:00

68 lines
2.1 KiB
JavaScript

/**
* @fileoverview Rule to disallow a duplicate case label.
* @author Dieter Oberkofler
* @copyright 2015 Dieter Oberkofler. All rights reserved.
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = function(context) {
/**
* Get a hash value for the node
* @param {ASTNode} node The node.
* @returns {string} A hash value for the node.
* @private
*/
function getHash(node) {
if (node.type === "Literal") {
return node.type + typeof node.value + node.value;
} else if (node.type === "Identifier") {
return node.type + typeof node.name + node.name;
} else if (node.type === "MemberExpression") {
return node.type + getHash(node.object) + getHash(node.property);
} else if (node.type === "CallExpression") {
return node.type + getHash(node.callee) + node.arguments.map(getHash).join("");
} else if (node.type === "BinaryExpression") {
return node.type + getHash(node.left) + node.operator + getHash(node.right);
} else if (node.type === "ConditionalExpression") {
return node.type + getHash(node.test) + getHash(node.consequent) + getHash(node.alternate);
}
}
var switchStatement = [];
return {
"SwitchStatement": function(/*node*/) {
switchStatement.push({});
},
"SwitchStatement:exit": function(/*node*/) {
switchStatement.pop();
},
"SwitchCase": function(node) {
var currentSwitch = switchStatement[switchStatement.length - 1],
hashValue;
if (node.test) {
hashValue = getHash(node.test);
if (typeof hashValue !== "undefined" && currentSwitch.hasOwnProperty(hashValue)) {
context.report(node, "Duplicate case label.");
} else {
currentSwitch[hashValue] = true;
}
}
}
};
};
module.exports.schema = [];