Skip to content

Latest commit

Β 

History

History
95 lines (69 loc) Β· 2.69 KB

prefer-math-trunc.md

File metadata and controls

95 lines (69 loc) Β· 2.69 KB

prefer-math-trunc

πŸ“ Prefer Math.trunc() for truncating numbers.

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ’‘ This rule is manually fixable by editor suggestions.

Enforces a convention of using Math.trunc() instead of less clear truncation patterns. It prevents the use of the following patterns:

These patterns help truncate numbers but they are not clear and do not work in some cases. For example, parseInt(String(x), 10) can produce unexpected results for very large or very small numbers that stringify to exponential notation.

None of these patterns is exactly equivalent to Math.trunc(x), so the rule only offers suggestions. The bitwise patterns convert the value to a 32-bit integer, so they wrap values outside that range and turn NaN into 0 (~~(2 ** 32) is 0, while Math.trunc(2 ** 32) is 4294967296). There is no suggestion for an assignment whose left-hand side has a side effect, or when a comment would be lost.

Examples

const foo = 37.4;

// ❌
console.log(foo | 0);

// ❌
console.log(~~foo);

// ❌
console.log(foo << 0);

// ❌
console.log(foo >> 0);

// ❌
console.log(foo.bar ^ 0);

// ❌
console.log(parseInt(String(foo), 10));

// ❌
console.log(Number.parseInt(String(foo), 10));

// βœ…
console.log(Math.trunc(foo));
let foo = 37.4;

// ❌
foo |= 0;

// βœ…
foo = Math.trunc(foo);
// βœ…
const foo = 37.4;
console.log(foo | 3);
// βœ…
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);