math/abs
enforce the conversion to absolute values to be the method you prefer
- 🔧 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 conversion to absolute values to be the method you prefer, promoting consistency and clarity in your codebase.
The rule supports two different approaches for calculating absolute values:
Math.abs()
method: The standard JavaScript function for absolute values- Conditional expression: Using ternary operators like
n < 0 ? -n : n
Why This Rule Matters
Different approaches to calculating absolute values can lead to:
- Inconsistency: Mixed patterns make code harder to read and maintain
- Type safety issues: Some methods don't work with all numeric types (e.g., BigInt)
- Performance variations: Different approaches may have different performance characteristics
- Readability concerns: Some patterns are more explicit about their intent than others
Default Behavior: Prefer Math.abs()
Alternative: Prefer Conditional Expressions
🔧 Options
{
"math/abs": [
"error",
{
"prefer": "Math.abs", // or "expression"
"aggressive": false
}
]
}
prefer
... enforces the conversion to absolute values to be the method you prefer. (default:"Math.abs"
)"Math.abs"
... enforces the conversion to absolute values to be the methodMath.abs(n)
."expression"
... enforces the conversion to absolute values to be the expressionn < 0 ? -n : n
.
aggressive
... configure the aggressive mode for only this rule. (default:false
)
The aggressive
mode
This plugin never reports negative expressions by default. Because it's hard to know the type of objects, it will cause false positives.
If you configured the aggressive
mode, this plugin reports negative expressions even if the rules couldn't know the type of operands.
If using this plugin and TypeScript, this plugin reports negative expressions by default because we can easily know types.
📚 Further reading
🚀 Version
This rule was introduced in eslint-plugin-math v0.3.0