Mmohebifar

disallow-nested-ternary-unfold-to-if-else

Rewrite nested ternaries in statement-safe JavaScript, TypeScript, and JSX contexts into equivalent if/else control flow.

javascripttypescriptjsxternaryconditional-expressionreadabilityrefactor
Public
0 executions

Run locally

npx codemod disallow-nested-ternary-unfold-to-if-else

disallow-nested-ternary-unfold-to-if-else

Unfold nested JavaScript-family ternaries into explicit if / else if / else statements when the ternary appears in a statement-safe context.

What It Transforms

This codemod rewrites nested ConditionalExpression trees in these contexts:

  • Single-declarator let / var initializers
  • Assignment expression statements
  • Return statements
  • Expression-bodied arrow functions whose body is the nested ternary

Examples:

js

becomes:

js
js

becomes:

js

No-Op Cases

The codemod leaves these shapes unchanged:

  • Single-level ternaries
  • const declarator initializers
  • Multi-declarator variable declarations
  • Nested ternaries in call arguments
  • Nested ternaries in JSX prop expressions
  • Nested ternaries in template literal interpolations
  • Nested ternaries in loop headers
  • Assignment expressions whose operator is not plain =
  • Assignment expressions whose left-hand side is not a bare identifier
  • Nodes preceded by codemod-ignore no-nested-ternary

File Coverage

The workflow runs the TSX parser across *.js, *.jsx, *.mjs, *.cjs, *.ts, and *.tsx files so JSX and TypeScript syntax can coexist with plain JavaScript input.

This codemod is intentionally conservative in declaration and assignment contexts where preserving JavaScript runtime semantics would otherwise be ambiguous.

Usage

bash

Development

bash

License

MIT

Before

This is one example from the codemod's test cases. The codemod may handle many more cases.

Ready to contribute?

Build your own codemod and share it with the community.