Skip to content
← Back to rules

unicorn/prefer-math-min-max Pedantic

🛠️ An auto-fix is available for this rule.

作用

在进行简单比较时,优先使用 Math.min()Math.max(),而不是三元表达式。

为什么这不好?

对于简单比较来说,使用 Math.min()Math.max() 比三元表达式更简洁、更易理解,也更不容易出错。它们能清楚地表达出寻找最小值或最大值的意图。

示例

以下是此规则的错误代码示例:

javascript
height > 50 ? 50 : height;
height > 50 ? height : 50;

以下是此规则的正确代码示例:

javascript
Math.min(height, 50);
Math.max(height, 50);

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "unicorn/prefer-math-min-max": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/prefer-math-min-max": "error",
  },
});
bash
oxlint --deny unicorn/prefer-math-min-max

版本

此规则在 v0.10.1 中添加。

参考资料