unicorn/prefer-math-trunc Pedantic
作用
倾向于使用 Math.trunc() 而不是位运算,以获得更清晰且更可靠的结果。
它会禁止使用以下位运算:
x | 0(bitwise OR与 0)~~x(两个bitwise NOT)x >> 0(Signed Right Shift与 0)x << 0(Left Shift与 0)x ^ 0(bitwise XOR Shift与 0)
为什么这不好?
使用位运算来截断数字并不清晰,而且在某些情况下并不起作用。
示例
此规则的错误代码示例:
javascript
const foo = 1.1 | 0;此规则的正确代码示例:
javascript
const foo = Math.trunc(1.1);如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"rules": {
"unicorn/prefer-math-trunc": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
rules: {
"unicorn/prefer-math-trunc": "error",
},
});bash
oxlint --deny unicorn/prefer-math-trunc版本
此规则在 v0.0.18 中添加。
