math/prefer-math-trunc
enforce the use of Math.trunc() instead of other truncations
- ⚙️ This rule is included in
"plugin:math/recommended"
. - 🔧 The
--fix
option on the command line can automatically fix some of the problems reported by this rule. - 💡 Some problems reported by this rule are manually fixable by editor suggestions.
📖 Rule Details
This rule aims to enforce the use of Math.trunc()
instead of other truncations.
/* eslint math/prefer-math-trunc: 'error' */
/* ✓ GOOD */
x = Math.trunc(n);
/* ✗ BAD */
x = n >= 0 ? Math.floor(n) : Math.ceil(n);
x = ~~n; // Same as `Math.trunc(n)` if `-(2 ** 31) - 1 < n < (2 ** 31)`.
x = n & -1; // Same as `Math.trunc(n)` if `-(2 ** 31) - 1 < n < (2 ** 31)`.
x = n | 0; // Same as `Math.trunc(n)` if `-(2 ** 31) - 1 < n < (2 ** 31)`.
x = n ^ 0; // Same as `Math.trunc(n)` if `-(2 ** 31) - 1 < n < (2 ** 31)`.
x = n >> 0; // Same as `Math.trunc(n)` if `-(2 ** 31) - 1 < n < (2 ** 31)`.
if (n >= 0) {
x = Math.floor(n);
} else {
x = Math.ceil(n);
}
🔧 Options
json
{
"math/prefer-math-trunc": [
"error",
{
"reportBitwise": true // false
}
]
}
reportBitwise
... Iftrue
, the rule reports bitwise operations that are equivalent toMath.trunc()
. Defaults totrue
.
📚 Further reading
- MDN - Math.trunc()
- MDN - Math.floor()
- MDN - Math.ceil()
- MDN - Bitwise NOT (
~
) - MDN - Bitwise AND (
&
) - MDN - Bitwise OR (
|
) - MDN - Bitwise XOR (
^
) - MDN - Right shift (
>>
)
🚀 Version
This rule was introduced in eslint-plugin-math v0.1.0