# Logic in Expressions

Canonical page: https://www.adaptabletools.com/docs/adaptable-ql-expression-advanced-logic

- AdapTableQL supports Logic in Expressions - this comes in 2 formats:
  - `IF` - function form or ternary `? :` shortcut
  - `CASE` statements (designed when using multiple clauses)

Expressions can also include custom Logic.

This can be provided in 2 ways:

- via ternary logic (essentially an IF function)
- using CASE Statements

## `IF` Function

Expressions can include conditional logic via the IF function.

You can write it as `IF(condition, trueValue, falseValue)` or with the ternary shortcut `? :`. These are the same Expression:

```ts
IF([Comments] > 100, 'Big', 'Small')
// is the same as
[Comments] > 100 ? 'Big' : 'Small'
```

The ternary form is made up of 3 parts:
1. a Boolean Expression to evaluate followed by a question mark (`?`)
2. the return value if the expression is true, followed by a colon (`:`)
3. the return value if the Expression is false

```ts [[1, 2, "[Comments] > 100 "], [2, 2, "Big"], [3, 2, "Small"]]
 // Return 'Big' if more than 100 Comments, otherwise 'Small'
 [Comments] > 100 ? 'Big' : 'Small'
```

There is no limit on the number of Ternary Operators in an Expression - which enables multiple conditions:

```ts [[1, 2, "[Comments] > 100 "], [2, 2, "Big"], [3, 2, "[Comments] > 50 "], [4, 2, "Medium"], [5, 2, "Small"]]
 // Return 'Big' if more than 100 Comments, 'Medium' if more than 50, otherwise 'Small'
 [Comments] > 100 ? 'Big' : [Comments] > 50 ? 'Medium' : 'Small'
```

**Example: Expression Logic: IF Function**

Using Ternary Operator in Expressions

- This demo contains a Calculated Column which is evaluated using Ternary Logic
- `Popularity` examines the number of stars in `Github Stars` and returns an appropriate string value using the following logic:
  - Greater than 100,000 - "Very Popular"
  - Greater than 30,000 - "Popular"
  - Others - "Trending"

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Ternary Logic',
  initialState: {
    Dashboard: {
      ModuleButtons: ['CalculatedColumn'],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Layout', 'CalculatedColumn'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_watchers',
            'github_stars',
            'popularity',
            'license',
            'open_issues_count',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
    CalculatedColumn: {
      CalculatedColumns: [
        {
          FriendlyName: 'Popularity',
          ColumnId: 'popularity',
          Expression: '[github_stars] > 100000 ? "Very Popular" : [github_stars] > 30000 ? "Popular" : "Trending"',
          CalculatedColumnSettings: {
            DataType: 'text',
          },
        },
      ],
    },
  },
};
```

## CASE Statements

Sometimes the logic required in an Expression will make the Ternary Operator feel verbose or unsuitable.

For this reason, AdapTableQL also offers switch-type logic common in many languages.

It is provided by `CASE` statements which take this form:

```ts
CASE [case_value]
    WHEN when_value THEN statement_list
    [WHEN when_value THEN statement_list] ...
    [ELSE statement_list]
END
```

As can be seen they are made up of (up to) 4 parts:

1. `CASE` keyword followed - optionally - by the value being evaluated
2. Any number of conditions which each take the form `WHEN` x `THEN` y
3. A final, optional, `ELSE` to return the value if no conditions are met
4. An `END` statement which wraps up the section

```ts [[1, 1, "CASE [day]"], [2, 1, "WHEN 'Saturday' THEN 'weekend'"], [3, 1, "ELSE 'workday'"], [4, 1, "END"]]
 CASE [day] WHEN 'Saturday' THEN 'weekend' WHEN 'Sunday' THEN 'weekend' ELSE 'workday' END 
```

As noted, the initial evaluation after CASE is optional and can be omitted:

```ts [[1, 1, "CASE"], [2, 1, "WHEN [price] < 10 THEN 'low'"], [3, 1, "ELSE 'high'"], [4, 1, "END"]]
 CASE WHEN [price] < 10 THEN 'low' WHEN [price] < 50 THEN 'medium' ELSE 'high' END
```

**Example: Expression Logic: Case Statements**

Using Case Statements in Expressions

- This demo contains 2 Calculated Columns which are evaluated using Case Statements
- `Popularity` examines the number of stars in `Github Stars` and returns an appropriate string value using the following logic:
  - Greater than 100,000 - "Very High"
  - Greater than 40,000 - "Quite High"
  - Greater than 20,000 - "Low"
  - Else - "None"
- `File` returns the correct file type for the `Language` column using the following logic:
  - `JavaScript` - ".js"
  - `TypeScript` - ".ts"
  - Else - ".html"

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Case Logic',
  initialState: {
    Dashboard: {
      ModuleButtons: ['CalculatedColumn'],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Layout', 'CalculatedColumn'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'file',
            'github_stars',
            'popularity',
            'license',
            'open_issues_count',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
    CalculatedColumn: {
      CalculatedColumns: [
        {
          FriendlyName: 'Popularity',
          ColumnId: 'popularity',
          Expression: "CASE WHEN [github_stars] > 100000 THEN 'Very High' WHEN [github_stars] > 40000 THEN 'Quite High' WHEN [github_stars] > 20000 THEN 'Low' ELSE 'None' END",
          CalculatedColumnSettings: {
            DataType: 'text',
            Resizable: true,
            Filterable: true,
          },
        },
        {
          FriendlyName: 'File',
          ColumnId: 'file',
          Expression: "CASE [language] WHEN 'JavaScript' THEN '.js' WHEN 'TypeScript' THEN '.ts' ELSE '.html' END",
          CalculatedColumnSettings: {
            DataType: 'text',
            Resizable: true,
            Filterable: true,
          },
        },
      ],
    },
  },
};
```
