npm package: @jexop/core
Description: Evaluate expressions with operators that are represented purely JSON objects
Author: Greg Bacchus
Latest version: 1.1.0

# JSON Expression Operators

The JSON Expression Operators library allows you to evaluate expressions with operators that are represented purely as JSON objects. It is completely extensible, giving you the ability to add or remove operators as required.

## Basic Usage

To use the library, first import the `evaluate` and `registry` functions from the `@jexop/core` package, then add the operators that you wish to use to the registry:

```typescript
import { evaluate, registry } from '@jexop/core';

// register all default operators
registry.addDefaults();
```

Now you can construct an expression as a JSON object. Here's an example:

```typescript
const expression = {
  op: 'if',
  condition: {
    op: '>',
    left: {
      op: 'context',
      path: 'x',
    },
    right: {
      op: 'context',
      path: 'y',
    },
  },
  then: {
    op: 'context',
    path: 'foo',
  },
  else: 'something else',
};
```

In this example, the expression is checking if the value of `x` is greater than the value of `y`. If the condition is true, it returns the value of `foo` that is in the given context, otherwise it returns the string `'something else'`.

Finally, you can evaluate the expression by calling the `evaluate` function and providing the context required:

```typescript
const context = {
  foo: 'bar',
  x: 19,
  y: 7,
};

const result = evaluate(expression, context);
```

The `result` variable will contain the result of the expression evaluation.

### Adding Custom Operators

In addition to the default operators provided by `@jexop/core`, you can also add custom operators. To add a custom operator, use the `set` or `add` functions on the `registry`.

Here's an example of adding a custom operator called 'is' that checks if two values are equal:

```typescript
registry.set('is', ({ a, b }, ctx) => a === b);
```

You can also add multiple custom operators at once using the `add` function:

```typescript
registry.add({
  'is': ({ a, b }, ctx) => a === b,
  "isn't": ({ a, b }, ctx) => a !== b,
});
```

Now you can use the custom operators in expressions. For example:

```typescript
const expression = {
  op: 'is',
  a: 45,
  b: 17,
};
const result = evaluate(expression); // result will be false
```

## Operators

The `@jexop/core` package provides many basic operators by default. These operators cover common use cases and provide a good starting point for most applications.

Additionally, there are more operators available in the following packages:

- **[@jexop/color](https://www.npmjs.com/package/@jexop/color):** This package provides color-related operators using the dependency of [chroma-js](https://www.npmjs.com/package/chroma-js).
- **[@jexop/date-time](https://www.npmjs.com/package/@jexop/date-time):** This package provides date and time-related operators using the dependency of [luxon](https://www.npmjs.com/package/luxon).

You can install and use these packages to access a wider range of operators for your expressions.

## Literal properties and operator

Any property value that is not an object will be considered a literal value. Arrays will have each item evaluated.

Objects that have no `op` property will also be considered literal. Further to that there is a `literal` operator to ensure that the value is passed as-is. This may be useful
for returning objects that have an `op` property that are not intended to be evaluated.

### `literal`

Returns `value` as-it, without evaluation.

| Property           | Description                  |
| ------------------ | ---------------------------- |
| `value` (optional) | Literal value to be returned |

Examples

```jsonc
{
  "op": "literal",
  "value": {
    "op": "anything",
    "foo": "bar"
  }
}
```

```jsonc
{
  "op": "literal",
  "value": 17
}
```

```jsonc
{
  "op": "literal",
  "value": "could be anything"
}
```

## Array Operators

### `array:map`

| Property | Description                                                          |
| -------- | -------------------------------------------------------------------- |
| `items`  | Array that will be run over                                          |
| `to`     | Object to evaluate with additional `item` and `index` in the context |

Examples

```json
{
  "op": "array:map",
  "items": [2, 4, 6],
  "to": {
    "op": "<",
    "left": {
      "op": "context",
      "path": "item"
    },
    "right": 5
  }
}
```

## Boolean Operators

### `not`, `!`

Returns the logical `not` of the value.

| Property | Description |
| -------- | ----------- |
| `value`  | Input       |

Examples

```jsonc
// returns true
{
  "op": "not",
  "value": false
}
```

```jsonc
// returns false
{
  "op": "!",
  "values": [
    {
      "op": "=",
      "a": 100,
      "b": {
        "op": "plus",
        "a": 1,
        "b": 99
      }
    }
  ]
}
```

### `and`, `&&`

Returns the result of all values combined with the logical `and` operation.

| Property | Description |
| -------- | ----------- |
| `values` | Inputs      |

Examples

```jsonc
// returns false
{
  "op": "and",
  "values": [true, false]
}
```

```jsonc
// returns true
{
  "op": "and",
  "values": [
    true,
    {
      "op": "=",
      "a": 100,
      "b": {
        "op": "plus",
        "a": 1,
        "b": 99
      }
    }
  ]
}
```

### `nand`

Returns the result of all values combined with the logical `nand` operation.

| Property | Description |
| -------- | ----------- |
| `values` | Inputs      |

Examples

```jsonc
// returns true
{
  "op": "nand",
  "values": [true, false]
}
```

```jsonc
// returns false
{
  "op": "nand",
  "values": [
    true,
    {
      "op": "=",
      "a": 100,
      "b": {
        "op": "plus",
        "a": 1,
        "b": 99
      }
    }
  ]
}
```

### `or`, `||`

Returns the result of all values combined with the logical `or` operation.

| Property | Description |
| -------- | ----------- |
| `values` | Inputs      |

Examples

```jsonc
// returns true
{
  "op": "or",
  "values": [true, false]
}
```

```jsonc
// returns false
{
  "op": "or",
  "values": [
    false,
    {
      "op": "!=",
      "a": 100,
      "b": {
        "op": "plus",
        "a": 1,
        "b": 99
      }
    }
  ]
}
```

### `nor`

Returns the result of all values combined with the logical `nor` operation.

| Property | Description |
| -------- | ----------- |
| `values` | Inputs      |

Examples

```jsonc
// returns false
{
  "op": "nor",
  "values": [true, false]
}
```

```jsonc
// returns true
{
  "op": "nor",
  "values": [
    false,
    {
      "op": "!=",
      "a": 100,
      "b": {
        "op": "plus",
        "a": 1,
        "b": 99
      }
    }
  ]
}
```

## Branch Operators

### `if`

| Property    | Description                     |
| ----------- | ------------------------------- |
| `condition` | Condition to check              |
| `then`      | Returned if condition is truthy |
| `else`      | Returned if condition is falsey |

NOTE: both `then` and `else` are evaluated no matter what the condition is.

### `switch`

| Property   | Description                                             |
| ---------- | ------------------------------------------------------- |
| `expr`     | Input value (string) to match against keys in `options` |
| `options`  | Key-value dictionary/object                             |
| `fallback` | Returned if no `options` match `expr`                   |

Examples

```json
// given context = { "foo": "bar" }, returns { "one": "thing" }
// given context = { "foo": "another" }, returns 7
// given context = { "foo": "other" }, returns "default case"
{
  "op": "switch",
  "expr": {
    "op": "context",
    "path": "foo"
  },
  "options": {
    "bar": { "one": "thing" },
    "another": 7
  },
  "fallback": "default case"
}
```

```json
// given context = { "foo": "bar" }, returns { "one": "thing" }
// given context = { "foo": "another", "value": 9 }, returns 9
// given context = { "foo": "other" }, returns "default case"
{
  "op": "switch",
  "expr": {
    "op": "context",
    "path": "foo"
  },
  "options": {
    "bar": { "one": "thing" },
    "another": {
      "op": "context",
      "path": "value"
    }
  },
  "fallback": "default case"
}
```

## Equality Operators

### `eq`, `=`, `==`, `===`

Returns `true` if inputs are exactly equal. Otherwise, returns `false`.

| Property | Description |
| -------- | ----------- |
| `a`      | Input       |
| `b`      | Input       |

Examples

```jsonc
// returns false
{
  "op": "eq",
  "a": "foo",
  "b": "bar"
}
```

```jsonc
// returns true
{
  "op": "=",
  "a": 100,
  "b": {
    "op": "plus",
    "a": 1,
    "b": 99
  }
}
```

### `ne`, `!=`, `!==`

Returns `false` if inputs are exactly equal. Otherwise, returns `true`.

| Property | Description |
| -------- | ----------- |
| `left`   | Input       |
| `right`  | Input       |

Examples

```jsonc
// returns false
{
  "op": "ne",
  "a": "foo",
  "b": "bar"
}
```

```jsonc
// returns true
{
  "op": "!=",
  "a": 100,
  "b": {
    "op": "plus",
    "a": 1,
    "b": 99
  }
}
```

## Numeric Operators

### `add`, `plus`, `+`

Adds two numbers.

| Property | Description |
| -------- | ----------- |
| `a`      | Augend      |
| `b`      | Addend      |

Computes `a` + `b`.

If `a` or `b` are not numeric they are defaulted to `0`.

Examples

```jsonc
// returns 12
{
  "op": "add",
  "a": 10,
  "b": 2
}
```

```jsonc
// returns 110
{
  "op": "+",
  "a": 10,
  "b": {
    "op": "plus",
    "a": 1,
    "b": 99
  }
}
```

### `clamp`

Ensures that a value is between a given `min` and `max` (inclusive).

| Property | Description                |
| -------- | -------------------------- |
| `min`    | Lower bound                |
| `max`    | Upper bound                |
| `value`  | Input number to be clamped |

If `value` is less that `min`, then `min` is returned. If `value` is greater than `max` then `max` is returned. Otherwise, `value` is returned.

Examples

```json
// returns 25
{
  "op": "clamp",
  "min": 10,
  "max": 50,
  "value": 25
}
```

```json
// returns 50
{
  "op": "clamp",
  "min": 10,
  "max": 50,
  "value": {
    "op": "plus",
    "a": 1,
    "b": 99
  }
}
```

### `comparison`

Compares two numbers

| Property | Description |
| -------- | ----------- |
| `left`   | Input       |
| `right`  | Input       |

| Operator   | Comparison                                 |
| ---------- | ------------------------------------------ |
| `lt`, `<`  | `left` is less than `right`                |
| `le`, `<=` | `left` is less than or equal to `right`    |
| `gt`, `>`  | `left` is greater than `right`             |
| `ge`, `>=` | `left` is greater than or equal to `right` |

Examples

```json
// returns true
{
  "op": "<",
  "left": 10,
  "right": 50
}
```

```json
// returns false
{
  "op": "ge",
  "left": 10,
  "right": 50
}
```

### `divide`, `/`

Divides one number by another.

| Property | Description |
| -------- | ----------- |
| `a`      | Dividend    |
| `b`      | Divisor     |

Computes `a` ÷ `b`

Examples

```json
// returns 5
{
  "op": "divide",
  "a": 10,
  "b": 2
}
```

```json
// returns 5
{
  "op": "/",
  "a": {
    "op": "divide",
    "a": 100,
    "b": 2
  },
  "b": 10
}
```

### `is-number`

Returns `true` if the `value` is a number. Otherwise, returns `false`.

| Property | Description    |
| -------- | -------------- |
| `value`  | Value to check |

### `multiply`, `*`

Multiplies two numbers.

| Property | Description  |
| -------- | ------------ |
| `a`      | Multiplier   |
| `b`      | Multiplicand |

Computes `a` × `b`

Examples

```json
// returns 20
{
  "op": "multiply",
  "a": 10,
  "b": 2
}
```

```json
// returns 2000
{
  "op": "*",
  "a": {
    "op": "multiply",
    "a": 100,
    "b": 2
  },
  "b": 10
}
```

### `normalize`

Converts the input `value` to a number in the range 0-1.

| Property | Description  |
| -------- | ------------ |
| `min`    | Lower bound  |
| `max`    | Upper bound  |
| `value`  | Input number |

If `value` is less that `min`, then `min` is returned. If `value` is greater than `max` then `max` is returned. Otherwise, `value` is returned.

Examples

```json
// returns 0.2
{
  "op": "normalize",
  "min": 0,
  "max": 5,
  "value": 1
}
```

```json
// returns 0.5
{
  "op": "normalize",
  "min": 40,
  "max": 50,
  "value": 45
}
```

```json
// returns 1
{
  "op": "normalize",
  "min": -100,
  "max": 100,
  "value": {
    "op": "plus",
    "a": 1,
    "b": 99
  }
}
```

```json
// returns 1
{
  "op": "normalize",
  "min": 0,
  "max": 10,
  "value": 99
}
```

### `number`

Convert to number if possible.

| Property             | Description                                |
| -------------------- | ------------------------------------------ |
| `value`              | Input                                      |
| `default` (optional) | Value to use if conversion is not possible |

If `value` is an array, the length of the array is returned.

The `default` property will also be converted to number if necessary.

Examples

```json
// returns 123
{
  "op": "number",
  "value": "123"
}
```

```json
// returns 3
{
  "op": "number",
  "value": [9, 8, 7]
}
```

```json
// returns null
{
  "op": "number",
  "value": "foo"
}
```

```json
// returns 0
{
  "op": "number",
  "value": "foo",
  "default": 0
}
```

```json
// returns 7
{
  "op": "number",
  "value": "foo",
  "default": "7"
}
```

### `subtract`, `minus`, `-`

Subtracts one number from another.

| Property | Description |
| -------- | ----------- |
| `a`      | Minuend     |
| `b`      | Subtrahend  |

Computes `a` - `b`.

If `a` or `b` are not numeric they are defaulted to `0`.

Examples

```jsonc
// returns 8
{
  "op": "subtract",
  "a": 10,
  "b": 2
}
```

```jsonc
// returns -88
{
  "op": "minus",
  "a": 10,
  "b": {
    "op": "-",
    "a": 1,
    "b": 99
  }
}
```

## Object Operators

### `context`

Returns the context or part of it.

| Property             | Description                                                                          |
| -------------------- | ------------------------------------------------------------------------------------ |
| `path` (optional)    | Property path to check                                                               |
| `default` (optional) | Value to be returned if the property doesn't exist or the value is null or undefined |

Examples

```jsonc
// given context = { "foo": "bar" }, returns { "foo": "bar" }
{
  "op": "context"
}
```

```jsonc
// given context = { "foo": "bar" }, returns "bar"
{
  "op": "context",
  "path": "foo"
}
```

```jsonc
// given context = { "foo": "bar" }, returns "this is the fallback"
{
  "op": "context",
  "path": "other",
  "default": "this is the fallback"
}
```

### `get`

Gets the value of the given property at the given `path` from the input `object`.

| Property             | Description                                                                          |
| -------------------- | ------------------------------------------------------------------------------------ |
| `path`               | Property path to check                                                               |
| `object`             | Input object                                                                         |
| `default` (optional) | Value to be returned if the property doesn't exist or the value is null or undefined |

Examples

```jsonc
// returns { "bar": 17 }
{
  "op": "get",
  "path": "foo",
  "object": {
    "foo": {
      "bar": 17
    }
  }
}
```

```jsonc
// returns 17
{
  "op": "get",
  "path": "foo.bar",
  "object": {
    "foo": {
      "bar": 17
    }
  }
}
```

```jsonc
// returns 17
{
  "op": "get",
  "path": ["foo", "bar"],
  "object": {
    "foo": {
      "bar": 17
    }
  }
}
```

```jsonc
// returns "not-found'
{
  "op": "get",
  "path": ["prop"],
  "object": {
    "foo": {
      "bar": 17
    }
  },
  "default": "not-found"
}
```

### `object:has`

True if the input `object` has a property at the given `path`.

| Property | Description            |
| -------- | ---------------------- |
| `object` | Input object           |
| `path`   | Property path to check |

Examples

```jsonc
// returns true
{
  "op": "object:has",
  "path": "foo.bar",
  "object": {
    "foo": {
      "bar": 17
    }
  }
}
```

```jsonc
// returns true
{
  "op": "object:has",
  "path": ["foo", "bar"],
  "object": {
    "foo": {
      "bar": 17
    }
  }
}
```

```jsonc
// returns false
{
  "op": "object:has",
  "path": "other",
  "object": {
    "foo": {
      "bar": 17
    }
  }
}
```

### `object:keys`

Returns the object's keys as an array.

| Property          | Description                          |
| ----------------- | ------------------------------------ |
| `object`          | Input object                         |
| `path` (optional) | Evaluate child property at this path |

Examples

```jsonc
// returns ["foo", "bar"]
{
  "op": "object:keys",
  "object": {
    "foo": 12,
    "bar": 17
  }
}
```

```jsonc
// returns ["bar"]
{
  "op": "object:keys",
  "path": "foo",
  "object": {
    "foo": {
      "bar": 17
    }
  }
}
```

### `object:transform`

| Property | Description                                                                 |
| -------- | --------------------------------------------------------------------------- |
| `object` | Object whose entries (key-value pairs) will be transformed                   |
| `to`     | Object to evaluate for each entry, with additional `key` and `value` in context |

#### Behavior

- Iterates over each key-value pair of the provided `object`.
- For each entry, evaluates the `to` expression.
- During evaluation, adds `key` and `value` to the context.
- Returns a new object with the same keys, where each value is the result of the evaluated `to` expression.

#### Example

```jsonc
// returns { "a": 10, "b": 20, "c": 30 }
{
  "op": "object:transform",
  "object": {
    "a": 1,
    "b": 2,
    "c": 3
  },
  "to": {
    "op": "*",
    "a": {
      "op": "context",
      "path": "value"
    },
    "b": 10
  }
}
```