no_unneeded_ternary

package
v0.5.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 7, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var NoUnneededTernaryRule = rule.Rule{
	Name: "no-unneeded-ternary",
	Run: func(ctx rule.RuleContext, ruleOptions any) rule.RuleListeners {
		opts := parseOptions(ruleOptions)

		condExprMsg := rule.RuleMessage{
			Id:          "unnecessaryConditionalExpression",
			Description: "Unnecessary use of boolean literals in conditional expression.",
		}
		condAssignMsg := rule.RuleMessage{
			Id:          "unnecessaryConditionalAssignment",
			Description: "Unnecessary use of conditional expression for default assignment.",
		}

		return rule.RuleListeners{
			ast.KindConditionalExpression: func(node *ast.Node) {
				cond := node.AsConditionalExpression()
				if cond == nil {
					return
				}

				consVal, consOk := boolKind(cond.WhenTrue)
				altVal, altOk := boolKind(cond.WhenFalse)
				if consOk && altOk {
					if fixes := buildBooleanLiteralFix(ctx.SourceFile, cond, consVal, altVal); fixes != nil {
						ctx.ReportNodeWithFixes(node, condExprMsg, fixes...)
					} else {
						ctx.ReportNode(node, condExprMsg)
					}
					return
				}

				if !opts.defaultAssignment && matchesDefaultAssignment(cond.Condition, cond.WhenTrue) {
					ctx.ReportNodeWithFixes(node, condAssignMsg, buildDefaultAssignmentFix(ctx.SourceFile, cond)...)
				}
			},
		}
	},
}

NoUnneededTernaryRule disallows ternary operators when simpler alternatives exist: `x ? true : false` → `x` / `!!x`, and (with `defaultAssignment: false`) `a ? a : b` → `a || b`.

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL