Skip to content

Commit

Permalink
Fix: no-implicit-coercion string concat false positive (fixes #7057)
Browse files Browse the repository at this point in the history
  • Loading branch information
kaicataldo committed Sep 5, 2016
1 parent 3960617 commit 00270a5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
26 changes: 23 additions & 3 deletions lib/rules/no-implicit-coercion.js
Expand Up @@ -105,15 +105,35 @@ function getNonNumericOperand(node) {
return null;
}

/**
* Checks whether a node is a string literal or not.
* @param {ASTNode} node The node to check.
* @returns {boolean} Whether or not the passed in node is a
* string literal or not.
*/
function isString(node) {
return node.type === "Literal" && typeof node.value === "string";
}

/**
* Checks whether a node is an empty string literal or not.
* @param {ASTNode} node The node to check.
* @returns {boolean} Whether or not the passed in node is an
* empty string literal or not.
*/
function isEmptyString(node) {
return isString(node) && node.value === "";
}

/**
* Checks whether or not a node is a concatenating with an empty string.
* @param {ASTNode} node - A BinaryExpression node to check.
* @returns {boolean} Whether or not the node is a concatenating with an empty string.
*/
function isConcatWithEmptyString(node) {
return node.operator === "+" && (
(node.left.type === "Literal" && node.left.value === "") ||
(node.right.type === "Literal" && node.right.value === "")
(isEmptyString(node.left) && !isString(node.right)) ||
(isEmptyString(node.right) && !isString(node.left))
);
}

Expand All @@ -123,7 +143,7 @@ function isConcatWithEmptyString(node) {
* @returns {boolean} Whether or not the node is appended with an empty string.
*/
function isAppendEmptyString(node) {
return node.operator === "+=" && node.right.type === "Literal" && node.right.value === "";
return node.operator === "+=" && isEmptyString(node.right);
}

/**
Expand Down
4 changes: 4 additions & 0 deletions tests/lib/rules/no-implicit-coercion.js
Expand Up @@ -64,6 +64,10 @@ ruleTester.run("no-implicit-coercion", rule, {
{code: "0 + foo"},
{code: "~foo.bar()"},

// https://github.com/eslint/eslint/issues/7057
{code: "'' + 'foo'"},
{code: "+42"},

{code: "!!foo", options: [{boolean: false}]},
{code: "~foo.indexOf(1)", options: [{boolean: false}]},
{code: "+foo", options: [{number: false}]},
Expand Down

0 comments on commit 00270a5

Please sign in to comment.