> ## Documentation Index
> Fetch the complete documentation index at: https://codegeninc-tawsif-change-additional-tools-to-tools.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Reducing Conditions

Codegen provides powerful APIs for reducing conditional logic to constant values. This is particularly useful for removing feature flags, cleaning up dead code paths, and simplifying conditional logic.

## Overview

The `reduce_condition()` method is available on various conditional constructs:

* [If/else statements](/api-reference/core/IfBlockStatement#reduce-condition)
* [Ternary expressions](/api-reference/core/TernaryExpression#reduce-condition)
* [Binary expressions](/api-reference/core/BinaryExpression#reduce-condition)
* [Function calls](/api-reference/core/FunctionCall#reduce-condition)

When you reduce a condition to `True` or `False`, Codegen automatically:

1. Evaluates which code path(s) to keep
2. Removes unnecessary branches
3. Preserves proper indentation and formatting

### Motivating Example

For example, consider the following code:

```python
flag = get_feature_flag('MY_FEATURE')
if flag:
    print('MY_FEATURE: ON')
else:
    print('MY_FEATURE: OFF')
```

`.reduce_condition` allows you to deterministically reduce this code to the following:

```python
print('MY_FEATURE: ON')
```

This is useful when a feature flag is fully "rolled out".

## Implementations

### [IfBlockStatements](/api-reference/core/IfBlockStatement#reduce-condition)

You can reduce if/else statements to either their "true" or "false" branch.

For example, in the code snippet above:

```python
# Grab if statement
if_block = file.code_block.statements[1]

# Reduce to True branch
if_block.reduce_condition(True)
```

This will remove the `else` branch and keep the `print` statement, like so:

```python
flag = get_feature_flag('MY_FEATURE')
print('MY_FEATURE: ON')
```

### Handling Elif Chains

Codegen intelligently handles elif chains when reducing conditions:

```python
# Original code
if condition_a:
    print("A")
elif condition_b:
    print("B")
else:
    print("C")

# Reduce first condition to False
if_block.reduce_condition(False)
# Result:
if condition_b:
    print("B")
else:
    print("C")

# Reduce elif condition to True
elif_block.reduce_condition(True)
# Result:
print("B")
```

## Ternary Expressions

Ternary expressions (conditional expressions) can also be reduced:

```python
# Original code
result = 'valueA' if condition else 'valueB'

# Reduce to True
ternary_expr.reduce_condition(True)
# Result:
result = 'valueA'

# Reduce to False
ternary_expr.reduce_condition(False)
# Result:
result = 'valueB'
```

### Nested Ternaries

Codegen handles nested ternary expressions correctly:

```python
# Original code
result = 'A' if a else 'B' if b else 'C'

# Reduce outer condition to False
outer_ternary.reduce_condition(False)
# Result:
result = 'B' if b else 'C'

# Then reduce inner condition to True
inner_ternary.reduce_condition(True)
# Result:
result = 'B'
```

## Binary Operations

Binary operations (and/or) can be reduced to simplify logic:

```python
# Original code
result = (x or y) and b

# Reduce x to True
x_assign.reduce_condition(True)
# Result:
result = b

# Reduce y to False
y_assign.reduce_condition(False)
# Result:
result = x and b
```

## Function Calls

[Function calls](/api-reference/core/FunctionCall#reduce-condition) can also be reduced, which is particularly useful when dealing with hooks or utility functions that return booleans:

```typescript
// Original code
const isEnabled = useFeatureFlag("my_feature");
return isEnabled ? <NewFeature /> : <OldFeature />;

// After reducing useFeatureFlag to True
return <NewFeature />;
```

### Feature Flag Hooks

A common use case is reducing feature flag hooks to constants. Consider the following code:

```typescript
// Original code
function MyComponent() {
  const showNewUI = useFeatureFlag("new_ui_enabled");

  if (showNewUI) {
    return <NewUI />;
  }
  return <OldUI />;
}
```

We can reduce the `useFeatureFlag` hook to a constant value like so, with [FunctionCall.reduce\_condition](/api-reference/core/FunctionCall#reduce-condition):

```python
hook = codebase.get_function("useFeatureFlag")
for usage in hook.usages():
    if isinstance(usage.match, FunctionCall):
        fcall = usage.match
        if fcall.args[0].value.content == 'new_ui_enabled':
            # This will automatically reduce any conditions using the flag
            fcall.reduce_condition(True)
```

This produces the following code:

```typescript
function MyComponent() {
  return <NewUI />;
}
```

### Comprehensive Example

Here's a complete example of removing a feature flag from both configuration and usage:

```python
feature_flag_name = "new_ui_enabled"
target_value = True

# 1. Remove from config
config_file = codebase.get_file("src/featureFlags/config.ts")
feature_flag_config = config_file.get_symbol("FEATURE_FLAG_CONFIG").value
feature_flag_config.pop(feature_flag_name)

# 2. Find and reduce all usages
hook = codebase.get_function("useFeatureFlag")
for usage in hook.usages():
    fcall = usage.match
    if isinstance(fcall, FunctionCall):
        # Check if this usage is for our target flag
        first_arg = fcall.args[0].value
        if isinstance(first_arg, String) and first_arg.content == feature_flag_name:
            print(f'Reducing in: {fcall.parent_symbol.name}')
            # This will automatically reduce:
            # - Ternary expressions using the flag
            # - If statements checking the flag
            # - Binary operations with the flag
            fcall.reduce_condition(target_value)

# Commit changes to disk
codebase.commit()
```

This example:

1. Removes the feature flag from configuration
2. Finds all usages of the feature flag hook
3. Reduces each usage to a constant value
4. Automatically handles all conditional constructs using the flag

<Note>
  When reducing a function call, Codegen automatically handles all dependent
  conditions. This includes: - [If/else
  statements](/api-reference/core/IfBlockStatement#reduce-condition) - [Ternary
  expressions](/api-reference/core/TernaryExpression#reduce-condition) - [Binary
  operations](/api-reference/core/BinaryExpression#reduce-condition)
</Note>

## TypeScript and JSX Support

Condition reduction works with TypeScript and JSX, including conditional rendering:

```typescript
// Original JSX
const MyComponent: React.FC = () => {
  let isVisible = true;
  return (
    <div>
      {isVisible && <span>Visible</span>}
      {!isVisible && <span>Hidden</span>}
    </div>
  );
};

// After reducing isVisible to True
const MyComponent: React.FC = () => {
  return (
    <div>
      <span>Visible</span>
    </div>
  );
};
```

<Tip>
  Condition reduction is particularly useful for cleaning up feature flags in
  React components, where conditional rendering is common.
</Tip>
