Skip to content

Fallback Values

The fallback syntax lets you specify multiple variable paths and returns the first non-empty value.

Basic Syntax

(var1 | var2 | var3 | ...)

The system tries each path left to right and returns the first non-empty value.

Basic Usage

javascript
import { calc } from "a-calc";

// First is null, falls back to second
calc("(a | b) + 1", { a: null, b: 10 }); // '11'
calc("(a | b) + 1", { a: undefined, b: 5 }); // '6'

// First is valid, uses it
calc("(a | b) * 2", { a: 3, b: 100 }); // '6'

// Three paths
calc("(a | b | c) + 1", { a: null, b: undefined, c: 7 }); // '8'

Complex Paths

javascript
// Object property paths
calc("(obj.a | obj.b) * 2", { obj: { a: null, b: 4 } }); // '8'

// Array index paths
calc("(arr[0] | arr[1]) + 5", { arr: [null, 10] }); // '15'

Custom Empty Value Detection

_empty_values

javascript
// Treat 0 as empty
calc("(a | b) + 1", {
  a: 0,
  b: 10,
  _empty_values: [null, undefined, 0],
}); // '11'

// Treat empty string as empty
calc("(a | b) + 1", {
  a: "",
  b: 5,
  _empty_values: [null, undefined, ""],
}); // '6'

_empty_check

javascript
// Negative numbers as empty
calc("(a | b) + 1", {
  a: -1,
  b: 10,
  _empty_check: (value) => value < 0,
}); // '11'

// Custom logic with path
calc("(price | defaultPrice) * qty", {
  price: 0,
  defaultPrice: 100,
  qty: 2,
  _empty_check: (value, path) => {
    if (path.includes("price")) return value <= 0;
    return value === null || value === undefined;
  },
}); // '200'

Error Handling

When all paths are empty:

javascript
calc("(a | b | c) + 1", {
  a: null,
  b: null,
  c: null,
  _error: "EMPTY",
}); // 'EMPTY'

Real-World Examples

Priority Data Sources

javascript
// User config > system config > default
const data = {
  userConfig: { precision: null },
  systemConfig: { precision: 4 },
  default: { precision: 2 },
};

calc(
  "(userConfig.precision | systemConfig.precision | default.precision)",
  data,
);
// '4'

Price Display

javascript
// Show sale price if available, otherwise original price
const product = { salePrice: null, originalPrice: 199 };
calc("(salePrice | originalPrice) | =2,", product); // '199.00'

Form Defaults

javascript
// User input > history > default
const form = {
  input: "",
  history: 50,
  default: 10,
  _empty_values: [null, undefined, ""],
};
calc("(input | history | default)", form); // '50'

Note

The | inside (a | b) is the fallback separator. The | outside is the formatting separator.

Released under the MIT License