Skip to content

Commit

Permalink
Update: add fixer for no-floating-decimal (fixes #7070) (#7081)
Browse files Browse the repository at this point in the history
  • Loading branch information
not-an-aardvark authored and nzakas committed Sep 9, 2016
1 parent 2a3f699 commit cec65e3
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 6 deletions.
2 changes: 2 additions & 0 deletions docs/rules/no-floating-decimal.md
@@ -1,5 +1,7 @@
# Disallow Floating Decimals (no-floating-decimal)

(fixable) The `--fix` option on the [command line](../user-guide/command-line-interface#fix) automatically fixes problems reported by this rule.

Float values in JavaScript contain a decimal point, and there is no requirement that the decimal point be preceded or followed by a number. For example, the following are all valid JavaScript numbers:

```js
Expand Down
16 changes: 13 additions & 3 deletions lib/rules/no-floating-decimal.js
Expand Up @@ -17,7 +17,9 @@ module.exports = {
recommended: false
},

schema: []
schema: [],

fixable: "code"
},

create(context) {
Expand All @@ -27,10 +29,18 @@ module.exports = {

if (typeof node.value === "number") {
if (node.raw.indexOf(".") === 0) {
context.report(node, "A leading decimal point can be confused with a dot.");
context.report({
node,
message: "A leading decimal point can be confused with a dot.",
fix: fixer => fixer.insertTextBefore(node, "0")
});
}
if (node.raw.indexOf(".") === node.raw.length - 1) {
context.report(node, "A trailing decimal point can be confused with a dot.");
context.report({
node,
message: "A trailing decimal point can be confused with a dot.",
fix: fixer => fixer.insertTextAfter(node, "0")
});
}
}
}
Expand Down
23 changes: 20 additions & 3 deletions tests/lib/rules/no-floating-decimal.js
Expand Up @@ -24,8 +24,25 @@ ruleTester.run("no-floating-decimal", rule, {
"var x = \"2.5\";"
],
invalid: [
{ code: "var x = .5;", errors: [{ message: "A leading decimal point can be confused with a dot.", type: "Literal"}] },
{ code: "var x = -.5;", errors: [{ message: "A leading decimal point can be confused with a dot.", type: "Literal"}] },
{ code: "var x = 2.;", errors: [{ message: "A trailing decimal point can be confused with a dot.", type: "Literal"}] }
{
code: "var x = .5;",
output: "var x = 0.5;",
errors: [{ message: "A leading decimal point can be confused with a dot.", type: "Literal" }]
},
{
code: "var x = -.5;",
output: "var x = -0.5;",
errors: [{ message: "A leading decimal point can be confused with a dot.", type: "Literal" }]
},
{
code: "var x = 2.;",
output: "var x = 2.0;",
errors: [{ message: "A trailing decimal point can be confused with a dot.", type: "Literal" }]
},
{
code: "var x = -2.;",
output: "var x = -2.0;",
errors: [{ message: "A trailing decimal point can be confused with a dot.", type: "Literal" }]
}
]
});

0 comments on commit cec65e3

Please sign in to comment.