Skip to content

Commit fd7429e

Browse files
committed
feat: js no-implicit-coercion rule
1 parent 0367ae8 commit fd7429e

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
---
2+
title: Disallow shorthand type conversions
3+
tags: [good-practice]
4+
---
5+
This matches the [eslint rule](https://eslint.org/docs/latest/rules/no-implicit-coercion).
6+
7+
Check the [Playground](https://app.grit.io/studio?key=cle6qCCw_-XMW9Nxs-PKH)
8+
```grit
9+
engine marzano(1.0)
10+
language js
11+
12+
function parenthesized_or_not($exp){
13+
or {
14+
and {
15+
$exp <: parenthesized_expression(),
16+
return $exp
17+
},
18+
and {
19+
return `($exp)`
20+
}
21+
},
22+
}
23+
24+
pattern no_implicit_coercion() {
25+
26+
or {
27+
`!!$v` as $exp where {
28+
$e = parenthesized_or_not($v),
29+
$exp => `Boolean$e`
30+
},
31+
`~$v` as $exp where {
32+
$e = parenthesized_or_not($v),
33+
$exp => `$e !== -1`
34+
},
35+
or {
36+
`+$v`,
37+
`-(-$v)`,
38+
`$v - 0`,
39+
`1 * $v`,
40+
`$v * 1`
41+
} as $exp where {
42+
$e = parenthesized_or_not($v),
43+
$exp => `Number$e`
44+
},
45+
or {
46+
`"" + $v`,
47+
`$v + ""`,
48+
} as $exp where {
49+
$e = parenthesized_or_not($v),
50+
$exp => `String$e`
51+
},
52+
}
53+
}
54+
55+
```
56+
57+
Code examples:
58+
```js
59+
var b = !!foo;
60+
var b = !!(foo);
61+
var b = ~foo.indexOf(".");
62+
var b = ~(foo.indexOf("."));
63+
var n = +foo;
64+
var n = +(foo);
65+
var n = -(-foo);
66+
var n = -(-(foo));
67+
var n = foo - 0;
68+
var n = (foo) - 0;
69+
var n = 1 * foo;
70+
var n = 1 * (foo);
71+
var s = "" + foo;
72+
var s = "" + (foo);
73+
var s = !!isNice()
74+
var s = !!(isNice() && isGreat())
75+
```
76+
will become
77+
```js
78+
var b = Boolean(foo);
79+
var b = Boolean(foo);
80+
var b = (foo.indexOf(".")) !== -1;
81+
var b = (foo.indexOf(".")) !== -1;
82+
var n = Number(foo);
83+
var n = Number(foo);
84+
var n = Number(foo);
85+
var n = Number(foo);
86+
var n = Number(foo);
87+
var n = Number(foo);
88+
var n = Number(foo);
89+
var n = Number(foo);
90+
var s = String(foo);
91+
var s = String(foo);
92+
var s = Boolean(isNice())
93+
var s = Boolean(isNice() && isGreat())
94+
```

0 commit comments

Comments
 (0)