Registry
Mmohebifar avatar

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

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

mohebifar0 executions

  • javascript
  • typescript
  • jsx
  • ternary
  • conditional-expression
  • readability
  • refactor
Connect a repo
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
const value = a ? b : c ? d : e;

becomes:

js
let value;
if (a) {
  (value = (b));
} else if (c) {
  (value = (d));
} else {
  (value = (e));
}
js
const pick = () => a ? b : c ? d : e;

becomes:

js
const pick = () => {
  if (a) {
    return (b);
  } else if (c) {
    return (d);
  } else {
    return (e);
  }
};

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
# Run from the registry
codemod run disallow-nested-ternary-unfold-to-if-else

# Run the local package against a target repository
pnpm dlx codemod@latest workflow run -w . -t /path/to/repo

Development

bash
# Run fixture tests
pnpm test

# Validate the workflow
pnpm validate

# Type-check the codemod
pnpm check-types

License

MIT

Ready to evolve your codebase?

Build tailored, compiler-aware skills to assess, plan, and automate complex codebase changes.