# Math Operations

> Performs mathematical calculations or aggregations on data.

Source: https://docs.sommatic.ai/en/nodes/data.math/

- Slug: `data.math`
- Family: Data
- Version: 1.0.0
- Status: Available
- Execution: sync

Performs mathematical calculations or aggregations on data.

This operator provides standard arithmetic and aggregation functions. It does not use JSONata: in `expr` mode the result is the value already resolved by the Sommatic AI Expression Engine.

**Operations:**
- **Sum/Avg/Min/Max:** Aggregations over `values` (an array of numbers in the input payload). Non-numeric entries are ignored; an empty list returns 0.
- **Advanced (Expr):** A `{{ }}` JavaScript expression (e.g. `{{ Math.round($json.price * 1.2 * 100) / 100 }}`). The resolved value is returned as `result` without further evaluation.

**Use Cases:**
- Calculating the total value of items in a shopping cart.
- Finding the highest bid in an auction list.
- Computing tax percentages.

## Configuration

- `op` (string, optional): Default: `sum`. Allowed values: `sum`, `avg`, `min`, `max`, `expr`.
- `expression` (string, optional, accepts expressions): Expression Engine calculation wrapped in {{ }} (required if op is "expr"), e.g. {{ $json.price * 1.2 }}. JSONata is not supported.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `out` (default): Result
- `error`: Error

## Input contract

- `values` (array<number>, optional): List of numbers (for aggregations).
- `payload` (object, optional): Context for custom expressions.

## Output contract

- `result` (number, optional): Calculation result.

## In expressions

What a later node can read from this node's output with `$("Math Operations").item.json.<path>` (write your node's label instead of `Math Operations`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `out`, from the output shown in Ports.

- `$("Math Operations").item.json.result` (number) = `42.5`: Calculation result.


## How it works

Aggregates the `values` array of the incoming payload (sum, average, minimum, maximum) or returns a value computed by an Expression Engine `{{ }}`, as `{ result }`.

1. Resolves the config; `op` defaults to `sum`. `{{ }}` in `expression` are evaluated by the Expression Engine (JavaScript, 100 ms limit).
2. `expr`: `result` is the resolved `expression` as is, of any type. JSONata is not used.
3. `sum`, `avg`, `min`, `max`: read `values` from the incoming payload (not configurable). A string fails; each entry is converted with `Number()` and `NaN` entries are dropped; an empty list gives 0.
4. Returns `{ result }` through `out`; the incoming payload is not passed through.

## In a workflow

### Node

```json
{
  "node_id": "node-cart-total",
  "label": "Cart total",
  "operator_slug": "data.math",
  "operator_version": "1.0.0",
  "config": {
    "op": "expr",
    "expression": "{{ Math.round(_.sum($json.items.map(item => item.price * item.qty)) * 100) / 100 }}"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": 42.5
  },
  "port": "out"
}
```

## Output ports (behaviour in the code)

### `out`

The calculation finished.

```json
{
  "result": 42.5
}
```

### `error`

Unknown `op`, or `values` cannot be read as a list.

```json
{
  "ok": false,
  "errors": [
    "Math Error: Values must be an array for aggregation"
  ],
  "port": "error"
}
```

## Behaviour in the code

- `expression`: Used only with `op` `expr`. Without `{{ }}` the literal text is returned. If a whole-value `{{ }}` throws, the resolver keeps the original text, so `result` is the `{{ ... }}` string and the node still leaves through `out`.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Math Error: Unknown op: <op>` | `error` | `op` is not `sum`, `avg`, `min`, `max` or `expr`. |
| `Math Error: Values must be an array for aggregation` | `error` | `values` in the payload is a string. |
| `Math Error: (values \|\| []).map is not a function` | `error` | `values` is a number, an object or `true`. |

## Notes and limits

- `null`, empty strings and booleans in `values` convert to 0 or 1 and are counted.
- To aggregate another field, shape it first (for example a `data.transform` that returns `{ "values": items.price }`) or use `expr` with `{{ _.sum($json.items.map(item => item.price)) }}`.
- When the envelope has no `data` (or `data` is falsy), the engine stores the whole envelope as the node output: on `error` the next node receives `{ ok: false, errors: [...], port: "error" }` as its payload.


## Contracts (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "data.math",
  "name": "Math Operations",
  "category": "data",
  "version": "1.0.0",
  "description": "Performs mathematical calculations or aggregations on data.\n\n  This operator provides standard arithmetic and aggregation functions. It does not use JSONata: in `expr` mode the result is the value already resolved by the Sommatic AI Expression Engine.\n\n  **Operations:**\n  - **Sum/Avg/Min/Max:** Aggregations over `values` (an array of numbers in the input payload). Non-numeric entries are ignored; an empty list returns 0.\n  - **Advanced (Expr):** A `{{ }}` JavaScript expression (e.g. `{{ Math.round($json.price * 1.2 * 100) / 100 }}`). The resolved value is returned as `result` without further evaluation.\n\n  **Use Cases:**\n  - Calculating the total value of items in a shopping cart.\n  - Finding the highest bid in an auction list.\n  - Computing tax percentages.",
  "capabilities": [
    "math",
    "calculation",
    "aggregation"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "op": {
        "type": "string",
        "enum": [
          "sum",
          "avg",
          "min",
          "max",
          "expr"
        ],
        "default": "sum",
        "title": "Operation"
      },
      "expression": {
        "type": "string",
        "format": "expression",
        "title": "Custom Expression",
        "description": "Expression Engine calculation wrapped in {{ }} (required if op is \"expr\"), e.g. {{ $json.price * 1.2 }}. JSONata is not supported."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "values": {
        "type": "array",
        "items": {
          "type": "number"
        },
        "description": "List of numbers (for aggregations)."
      },
      "payload": {
        "type": "object",
        "description": "Context for custom expressions."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "number",
        "description": "Calculation result."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Result",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "math",
    "calc",
    "sum",
    "stats"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "op": {
      "type": "string",
      "enum": [
        "sum",
        "avg",
        "min",
        "max",
        "expr"
      ],
      "default": "sum",
      "title": "Operation"
    },
    "expression": {
      "type": "string",
      "format": "expression",
      "title": "Custom Expression",
      "description": "Expression Engine calculation wrapped in {{ }} (required if op is \"expr\"), e.g. {{ $json.price * 1.2 }}. JSONata is not supported."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "values": {
      "type": "array",
      "items": {
        "type": "number"
      },
      "description": "List of numbers (for aggregations)."
    },
    "payload": {
      "type": "object",
      "description": "Context for custom expressions."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": "number",
      "description": "Calculation result."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Result",
    "is_default": true
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
