# Add custom worksheet functions

> Define reusable workbook functions with LAMBDA and defined names, share them across sheets, and test them with the headless formula engine.

A costing sheet repeats the same calculation in every row: labour with overtime after eight hours, a total with VAT. Instead of copying a long formula down the column, define it once as a named `LAMBDA` and call it like a built-in function: `=LabourCost(C2, D2)`. The definitions live in the workbook, so they are saved with it, exported to xlsx and work in the headless engine.

**Live demo: Custom worksheet functions with LAMBDA** (runs on the HTML version of this page). Source of `demos/recipe-spreadsheet-custom-functions.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createSpreadsheet, type CellJSON } from '@birchui/spreadsheet';
import { docsTheme, layout, onDocsThemeChange } from './_shared';

export const meta = { title: 'Custom worksheet functions with LAMBDA', height: 520 };

const header = { bold: true, fill: '#1f3a5f', color: '#ffffff' };
const money = { numberFormat: '#,##0.00' };

const workOrders: [string, string, number, number, number][] = [
  ['WO-24101', 'Ana Ruiz', 6.5, 48, 120],
  ['WO-24102', 'Omar Haddad', 10, 52, 340.5],
  ['WO-24103', 'Li Wei', 3, 45, 0],
  ['WO-24104', 'Sam Patel', 9.25, 55, 612],
  ['WO-24105', 'Nora Lindqvist', 7.75, 50, 88.4],
  ['WO-24106', 'Ben Mensah', 12, 48, 1290],
];

function cells(): Record<string, CellJSON> {
  const result: Record<string, CellJSON> = {
    A1: { value: 'Work order', style: header },
    B1: { value: 'Technician', style: header },
    C1: { value: 'Hours', style: header },
    D1: { value: 'Rate', style: header },
    E1: { value: 'Parts', style: header },
    F1: { value: 'Labour', style: header },
    G1: { value: 'Total inc. VAT', style: header },
  };
  workOrders.forEach(([order, technician, hours, rate, parts], index) => {
    const r = index + 2;
    result[`A${r}`] = { value: order };
    result[`B${r}`] = { value: technician };
    result[`C${r}`] = { value: hours };
    result[`D${r}`] = { value: rate, style: money };
    result[`E${r}`] = { value: parts, style: money };
    result[`F${r}`] = { formula: `=LabourCost(C${r}, D${r})`, style: money };
    result[`G${r}`] = { formula: `=WithVat(F${r} + E${r})`, style: money };
  });
  const total = workOrders.length + 2;
  result[`A${total}`] = { value: 'Total', style: { bold: true } };
  result[`G${total}`] = { formula: `=SUM(G2:G${total - 1})`, style: { ...money, bold: true } };
  result.I1 = { value: 'VAT rate', style: { bold: true } };
  result.J1 = { value: 0.2, style: { numberFormat: '0%' } };
  result.I2 = { value: 'Overtime after', style: { bold: true } };
  result.J2 = { value: 8 };
  return result;
}

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  toolbar.append(
    'Columns F and G call LabourCost and WithVat, two workbook functions defined with LAMBDA. Change hours, rates or the VAT rate in J1.',
  );
  const sheet = createSpreadsheet(body, {
    theme: docsTheme(),
    height: '100%',
    data: {
      version: 1,
      sheets: [
        {
          name: 'Work orders',
          freeze: { rows: 1, columns: 0 },
          columnWidths: { A: 100, B: 140, F: 110, G: 130, I: 120 },
          cells: cells(),
        },
      ],
      names: [
        { name: 'VatRate', formula: "='Work orders'!$J$1" },
        { name: 'OvertimeAfter', formula: "='Work orders'!$J$2" },
        {
          name: 'LabourCost',
          formula:
            '=LAMBDA(hours, rate, IF(hours > OvertimeAfter, OvertimeAfter * rate + (hours - OvertimeAfter) * rate * 1.5, hours * rate))',
        },
        { name: 'WithVat', formula: '=LAMBDA(amount, ROUND(amount * (1 + VatRate), 2))' },
      ],
    },
  });
  const totalCell = `G${workOrders.length + 2}`;
  const offs = [
    sheet.on('cellChange', ({ address, source }) => {
      if (source !== 'edit' && source !== 'paste') return;
      status.textContent = `${address} changed. Invoice total is now ${sheet.getDisplayText(totalCell)}.`;
    }),
  ];
  status.textContent = `Invoice total ${sheet.getDisplayText(totalCell)}. Labour for WO-24102 (10 hours) is ${sheet.getDisplayText('F3')}.`;
  const stopTheme = onDocsThemeChange((theme) => sheet.update({ theme }));
  return () => {
    for (const off of offs) off();
    stopTheme();
    sheet.destroy();
  };
}
```

## Steps

1. Put the inputs your functions depend on, such as the VAT rate, in cells and give them names.
2. Define each function as a name whose formula is a `LAMBDA`.
3. Call the functions from cells like any other function.
4. Test them with `createFormulaEngine()` in a unit test.

## Define the functions

In the component, call `defineName(name, formula, sheet?)`:

```ts title="work-order-costing.ts"
import { createSpreadsheet } from '@birchui/spreadsheet';

const sheet = createSpreadsheet(document.querySelector<HTMLElement>('#costing')!, { data: costingWorkbook });

sheet.defineName('VatRate', "='Work orders'!$J$1");
sheet.defineName('OvertimeAfter', "='Work orders'!$J$2");
sheet.defineName(
  'LabourCost',
  '=LAMBDA(hours, rate, IF(hours > OvertimeAfter, OvertimeAfter * rate + (hours - OvertimeAfter) * rate * 1.5, hours * rate))',
);
sheet.defineName('WithVat', '=LAMBDA(amount, ROUND(amount * (1 + VatRate), 2))');

sheet.setFormula('F2', '=LabourCost(C2, D2)');
sheet.setFormula('G2', '=WithVat(F2 + E2)');
```

Or ship them in the workbook JSON, under `names`:

```ts title="costing-workbook.ts"
import type { WorkbookJSON } from '@birchui/spreadsheet';

export const costingWorkbook: WorkbookJSON = {
  version: 1,
  sheets: [
    {
      name: 'Work orders',
      cells: {
        A1: { value: 'Work order' },
        C1: { value: 'Hours' },
        D1: { value: 'Rate' },
        E1: { value: 'Parts' },
        F1: { value: 'Labour' },
        G1: { value: 'Total inc. VAT' },
        A2: { value: 'WO-24102' },
        C2: { value: 10 },
        D2: { value: 52 },
        E2: { value: 340.5 },
        F2: { formula: '=LabourCost(C2, D2)' },
        G2: { formula: '=WithVat(F2 + E2)' },
        J1: { value: 0.2 },
        J2: { value: 8 },
      },
    },
  ],
  names: [
    { name: 'VatRate', formula: "='Work orders'!$J$1" },
    { name: 'OvertimeAfter', formula: "='Work orders'!$J$2" },
    {
      name: 'LabourCost',
      formula:
        '=LAMBDA(hours, rate, IF(hours > OvertimeAfter, OvertimeAfter * rate + (hours - OvertimeAfter) * rate * 1.5, hours * rate))',
    },
    { name: 'WithVat', formula: '=LAMBDA(amount, ROUND(amount * (1 + VatRate), 2))' },
  ],
};
```

Here `F2` is `572` (8 hours at 52, plus 2 hours at 78) and `G2` is `1095`.

## Apply a function to a whole column

`MAP`, `BYROW` and `REDUCE` take a `LAMBDA`, including a named one, so one formula can fill a column:

```text
=MAP(C2:C7, D2:D7, LabourCost)
=REDUCE(0, G2:G7, LAMBDA(total, value, total + value))
```

The first formula spills six labour costs down from the cell it is in.

## Test the functions

The headless engine evaluates the same formulas without a DOM, so the functions can have unit tests:

```ts title="labour-cost.test.ts"
import { createFormulaEngine } from '@birchui/spreadsheet';
import { describe, expect, it } from 'vitest';
import { costingWorkbook } from './costing-workbook';

describe('LabourCost', () => {
  const engine = createFormulaEngine();
  engine.fromJSON(costingWorkbook);

  it('pays time and a half after eight hours', () => {
    expect(engine.evaluate('=LabourCost(10, 52)')).toBe(572);
  });

  it('pays the plain rate up to eight hours', () => {
    expect(engine.evaluate('=LabourCost(6.5, 48)')).toBe(312);
  });

  it('adds VAT and rounds to pence', () => {
    expect(engine.evaluate('=WithVat(912.5)')).toBe(1095);
  });
});
```

## How it works

- A defined name whose formula is a `LAMBDA` becomes a function for the whole workbook. Without a sheet argument it is workbook-wide; with one it is scoped to that sheet.
- Names inside the `LAMBDA` body, such as `VatRate`, are resolved when the function runs, so changing `J1` recalculates every cell that calls `WithVat`.
- Names are stored in `WorkbookJSON.names`, so `toJSON()` and `fromJSON()` keep them, and they are written to and read from xlsx files.

## Pitfalls

- **Name rules.** Names start with a letter, underscore or backslash and cannot look like a cell address: `defineName('VAT1', …)` throws an error, `VatRate` is fine.
- **Wrong argument count** gives `#VALUE!`. `=LabourCost(10)` with one argument is an error, not a default.
- **No JavaScript functions.** Worksheet functions are written in the formula language. For logic that needs your code or your server, compute the value in JavaScript and write it into a cell with `setCell` or `setRange`.
- **Not in `listFunctions()`.** Named functions are part of the workbook, so they do not appear in the function list or in the [function reference](https://docs.birchui.com/spreadsheet/functions.md).

## Related

- [LET and LAMBDA](https://docs.birchui.com/spreadsheet/formulas.md#let-and-lambda).
- [Defined names](https://docs.birchui.com/spreadsheet/formulas.md#defined-names).
- [Headless engine](https://docs.birchui.com/spreadsheet/headless-engine.md).
- [Load and save xlsx files](https://docs.birchui.com/recipes/spreadsheet-load-save-xlsx.md).
