Skip to content

Latest commit

 

History

History
90 lines (68 loc) · 2.33 KB

prefer-math-trunc.md

File metadata and controls

90 lines (68 loc) · 2.33 KB

Enforce the use of Math.trunc instead of bitwise operators

💼 This rule is enabled in the ✅ recommended config.

🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

Enforces a convention of using Math.trunc() instead of bitwise operations for clarity and more reliable results. It prevents the use of the following bitwise operations:

These hacks help truncate numbers but they are not clear and do not work in some cases.

This rule is fixable, unless the left-hand side in assignment has side effect.

Fail

const foo = 37.4;
console.log(foo | 0);
const foo = 37.4;
console.log(~~bar);
let foo = 37.4;
foo |= 0;
const foo = 37.4;
console.log(foo << 0);
const foo = 37.4;
console.log(foo >> 0);
const foo = {bar: 37.4};
console.log(foo.bar ^ 0);

Pass

const foo = 37.4;
console.log(Math.trunc(foo));
const foo = 37.4;
console.log(foo | 3);
let foo = 37.4;
foo = Math.trunc(foo);
const foo = 37.4;
console.log(~foo);
const foo = 37.4;
console.log(foo >> 3);
const foo = 37.4;
console.log(foo << 3);
const foo = 37.4;
console.log(foo ^ 3);