Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add no-unneeded-ternary rule #1034

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/rules/no_unneeded_ternary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Disallows ternary operators when simpler alternatives exist.

It's a common mistake to use a conditional expression to select between two
Boolean values instead of using ! to convert the test to a Boolean.

### Invalid:

```typescript
// You don't need a ternary when a simple `const foo = !condition` will do
const foo = condition ? false : true;
// use `const foo = condition` instead
const foo = condition ? true : false;
```

### Valid:

```typescript
const foo = x === 2 ? "Yes" : "No";
const foo = x === 2 ? "Yes" : false;
const foo = x === 2 ? true : "No";
```
2 changes: 2 additions & 0 deletions src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ pub mod no_this_before_super;
pub mod no_throw_literal;
pub mod no_top_level_await;
pub mod no_undef;
pub mod no_unneeded_ternary;
pub mod no_unreachable;
pub mod no_unsafe_finally;
pub mod no_unsafe_negation;
Expand Down Expand Up @@ -305,6 +306,7 @@ fn get_all_rules_raw() -> Vec<Arc<dyn LintRule>> {
no_throw_literal::NoThrowLiteral::new(),
no_top_level_await::NoTopLevelAwait::new(),
no_undef::NoUndef::new(),
no_unneeded_ternary::NoUnneededTernary::new(),
no_unreachable::NoUnreachable::new(),
no_unsafe_finally::NoUnsafeFinally::new(),
no_unsafe_negation::NoUnsafeNegation::new(),
Expand Down
123 changes: 123 additions & 0 deletions src/rules/no_unneeded_ternary.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// Copyright 2020-2022 the Deno authors. All rights reserved. MIT license.
use super::{Context, LintRule};
use crate::handler::{Handler, Traverse};
use crate::{Program, ProgramRef};
use deno_ast::swc::common::Spanned;
use deno_ast::view as ast_view;
use if_chain::if_chain;
use std::sync::Arc;

#[derive(Debug)]
pub struct NoUnneededTernary;

const CODE: &str = "no-unneeded-ternary";
const MESSAGE: &str =
"Unnecessary use of boolean literals in conditional expression";

impl LintRule for NoUnneededTernary {
fn new() -> Arc<Self> {
Arc::new(NoUnneededTernary)
}

fn code(&self) -> &'static str {
CODE
}

fn lint_program(&self, _context: &mut Context, _program: ProgramRef<'_>) {
unreachable!();
}

fn lint_program_with_ast_view(
&self,
context: &mut Context,
program: Program<'_>,
) {
NoUnneededTernaryHandler.traverse(program, context);
}

#[cfg(feature = "docs")]
fn docs(&self) -> &'static str {
include_str!("../../docs/rules/no_unneeded_ternary.md")
}
}

struct NoUnneededTernaryHandler;

impl Handler for NoUnneededTernaryHandler {
fn cond_expr(&mut self, cond_expr: &ast_view::CondExpr, ctx: &mut Context) {
if_chain! {
if cond_expr.cons.is::<ast_view::Bool>();
if cond_expr.alt.is::<ast_view::Bool>();
then {
ctx.add_diagnostic(cond_expr.span(), CODE, MESSAGE);
}
}
}
}

// https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-unneeded-ternary.js
#[cfg(test)]
mod tests {
use super::*;

#[test]
fn no_unneeded_ternary_valid() {
assert_lint_ok! {
NoUnneededTernary,
r#"config.newIsCap = config.newIsCap !== false"#,
r#"var a = x === 2 ? 'Yes' : 'No';"#,
r#"var a = x === 2 ? true : 'No';"#,
r#"var a = x === 2 ? 'Yes' : false;"#,
r#"var a = x === 2 ? 'true' : 'false';"#,
};
}

#[test]
fn no_unneeded_ternary_invalid() {
assert_lint_err! {
NoUnneededTernary,
r#"x === 2 ? true : false;"#: [
{
col: 0,
message: MESSAGE,
},
],
r#"x >= 2 ? true : false;"#: [
{
col: 0,
message: MESSAGE,
},
],
r#"x ? true : false;"#: [
{
col: 0,
message: MESSAGE,
},
],
r#"x === 1 ? false : true;"#: [
{
col: 0,
message: MESSAGE,
},
],
r#"x != 1 ? false : true;"#: [
{
col: 0,
message: MESSAGE,
},
],
r#"foo() ? false : true;"#: [
{
col: 0,
message: MESSAGE,
},
],
r#"!foo() ? false : true;"#: [
{
col: 0,
message: MESSAGE,
},
],
};
}
}
5 changes: 5 additions & 0 deletions www/public/docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,11 @@
"docs": "",
"tags": []
},
{
"code": "no-unneeded-ternary",
"docs": "Disallows ternary operators when simpler alternatives exist.\n\nIt's a common mistake to use a conditional expression to select between two\nBoolean values instead of using ! to convert the test to a Boolean.\n\n### Invalid:\n\n```typescript\n// You don't need a ternary when a simple `const foo = !condition` will do\nconst foo = condition ? false : true;\n// use `const foo = condition` instead\nconst foo = condition ? true : false;\n```\n\n### Valid:\n\n```typescript\nconst foo = x === 2 ? \"Yes\" : \"No\";\nconst foo = x === 2 ? \"Yes\" : false;\nconst foo = x === 2 ? true : \"No\";\n```\n",
"tags": []
},
{
"code": "no-unreachable",
"docs": "Disallows the unreachable code after the control flow statements.\n\nBecause the control flow statements (`return`, `throw`, `break` and `continue`)\nunconditionally exit a block of code, any statements after them cannot be\nexecuted.\n\n### Invalid:\n\n```typescript\nfunction foo() {\n return true;\n console.log(\"done\");\n}\n```\n\n```typescript\nfunction bar() {\n throw new Error(\"Oops!\");\n console.log(\"done\");\n}\n```\n\n```typescript\nwhile (value) {\n break;\n console.log(\"done\");\n}\n```\n\n```typescript\nthrow new Error(\"Oops!\");\nconsole.log(\"done\");\n```\n\n```typescript\nfunction baz() {\n if (Math.random() < 0.5) {\n return;\n } else {\n throw new Error();\n }\n console.log(\"done\");\n}\n```\n\n```typescript\nfor (;;) {}\nconsole.log(\"done\");\n```\n\n### Valid\n\n```typescript\nfunction foo() {\n return bar();\n function bar() {\n return 1;\n }\n}\n```\n",
Expand Down