Functional Weave
Code in TypeScript

hospitality.bill-split

Split a restaurant bill evenly, by item or by share, exactly to the penny, with the service charge shared in proportion.

1.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 25 tests, run in TypeScript, Python and Rust.

What it does

Splits a restaurant bill between diners so the shares add up to the bill exactly, to the penny. Diners are numbered from 0. Each gets their share of the items, their share of the service charge, and a total.

## Three methods

For example

  • billSplit(items ×3, £7.50, 3, even, ) → ×3 even three ways with 12.5% service
  • billSplit(items ×1, £0.00, 3, even, ) → ×3 even: 100.00 three ways, the odd penny to the first diner
  • billSplit(items ×1, £6.25, 2, even, ) → ×2 even: totals differ by a penny at most, service shared by what each pays

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

export function billSplit(items: readonly BillItem[], serviceCharge: Money, diners: number, method: SplitMethod, shares: readonly number[]): readonly DinerShare[]
itemsBillItem[]what was ordered, in one currency; [] for none
serviceChargeMoneythe bill's service charge (hospitality.service-charge); 0 for none
dinersinthow many people are paying, at least 1
methodSplitMethodeven, by-item or by-share
sharesint[]by-share only: one weight per diner, such as [2, 1, 1]; [] otherwise
returnsDinerShare[]one entry per diner, diner 0 first; the totals add up to the bill exactly

The types it declares, generated into your project

/** One thing ordered. */
export interface BillItem {
  readonly description: string;
  readonly amount: Money;
  /** by-item only: who shared it, as diner numbers from 0; [] for the whole table */
  readonly diners: readonly number[];
}

export type SplitMethod = "even" | "by-item" | "by-share";

/** What one diner pays. */
export interface DinerShare {
  /** 0 to diners - 1 */
  readonly diner: number;
  /** their share of the food and drink */
  readonly items: Money;
  /** their share of the service charge */
  readonly serviceCharge: Money;
  readonly total: Money;
}

Your code names it in one line, in the file that uses it

import { billSplit } from "#fune/hospitality.bill-split@^1";
impl/typescript.ts · 82 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { allocate } from "./money_allocate.ts";  ← from money.allocate ^1.0.0 · built alongside by fune
import { type Money, money } from "./money_amount.ts";  ← from money.amount ^1.0.0 · built alongside by fune
import { splitEven } from "./money_split_even.ts";  ← from money.split-even ^1.0.0 · built alongside by fune
import { sumMoney } from "./money_sum.ts";  ← from money.sum ^1.0.0 · built alongside by fune
import { type BillItem, type DinerShare, type SplitMethod } from "./hospitality_bill_split_types.ts";

/**
 * Split a bill between diners so that the shares add up to the bill exactly.
 *
 * even and by-share divide the whole bill (items plus service) by weight, so
 * even totals never differ by more than a penny. by-item gives each diner what
 * they ordered, with shared items split evenly between the people who shared
 * them. In every method the service charge is then shared in proportion to
 * what each diner pays for, so nobody pays service on someone else's steak.
 */
export function billSplit(
  items: readonly BillItem[],
  serviceCharge: Money,
  diners: number,
  method: SplitMethod,
  shares: readonly number[],
): readonly DinerShare[] {
  if (!Number.isInteger(diners) || diners < 1) throw new RangeError(`diners must be at least 1, received ${diners}`);
  if (method !== "even" && method !== "by-item" && method !== "by-share") {
    throw new RangeError(`unknown split method "${method}"`);
  }
  if (serviceCharge.minor < 0) throw new RangeError(`serviceCharge must not be negative, received ${serviceCharge.minor}`);
  for (const item of items) {
    if (item.amount.minor < 0) throw new RangeError(`item amounts must not be negative, received ${item.amount.minor} for "${item.description}"`);
  }
  const currency = serviceCharge.currency;
  const itemsTotal = sumMoney(
    items.map((item) => item.amount),
    currency,
  );
  if (method === "by-share") {
    if (shares.length !== diners) throw new RangeError(`shares must have one entry per diner: ${diners} diners, ${shares.length} shares`);
    for (const s of shares) {
      if (!Number.isInteger(s) || s < 0) throw new RangeError(`shares must not be negative, received ${s}`);
    }
    if (shares.every((s) => s === 0)) throw new RangeError("shares must not all be zero");
  } else if (shares.length !== 0) {
    throw new RangeError("shares are only used by the by-share method; pass []");
  }

  let itemShares: number[];
  let scShares: number[];
  if (method === "by-item") {
    itemShares = new Array<number>(diners).fill(0);
    for (const item of items) {
      const who = item.diners.length === 0 ? [...Array(diners).keys()] : [...item.diners];
      for (let i = 0; i < who.length; i++) {
        const d = who[i];
        if (!Number.isInteger(d) || d < 0 || d >= diners) {
          throw new RangeError(`diner ${d} is not at the table: diners are numbered 0 to ${diners - 1}`);
        }
        if (who.indexOf(d) !== i) throw new RangeError(`item "${item.description}" lists diner ${d} twice`);
      }
      const parts = splitEven(item.amount, who.length);
      who.forEach((d, i) => (itemShares[d] += parts[i].minor));
    }
    if (itemsTotal.minor === 0) {
      if (serviceCharge.minor !== 0) throw new RangeError("a service charge cannot be shared on a bill with no items");
      scShares = new Array<number>(diners).fill(0);
    } else {
      scShares = allocate(serviceCharge, itemShares).map((m) => m.minor);
    }
  } else {
    const weights = method === "even" ? new Array<number>(diners).fill(1) : [...shares];
    const grand = money(itemsTotal.minor + serviceCharge.minor, currency);
    const totals = allocate(grand, weights).map((m) => m.minor);
    scShares = grand.minor === 0 ? new Array<number>(diners).fill(0) : allocate(serviceCharge, totals).map((m) => m.minor);
    itemShares = totals.map((t, i) => t - scShares[i]);
  }

  return itemShares.map((minor, diner) => ({
    diner,
    items: money(minor, currency),
    serviceCharge: money(scShares[diner], currency),
    total: money(minor + scShares[diner], currency),
  }));
}

Install

fune build

With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 4 dependencies, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add hospitality.bill-split
Download for TypeScript hospitality.bill-split-1.0.0-typescript.fune · 23,884 bytes sha256 4d005909883b363b930c241472d27decd277627ce7001c89ae9450fdcb223c38

The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./hospitality.bill-split-1.0.0-typescript.fune, or fetch it from a terminal with fune pull hospitality.bill-split@1.0.0:typescript.

The whole function, every language, is one file too: hospitality.bill-split-1.0.0.fune, 33,657 bytes, sha256 27a4d9bd67451248d4e95373ee278994c6967160d4e722656396787618ac3f6a. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before hospitality.bill-split

after — your function gets the result and the arguments, and returns the final result.

// fune: after hospitality.bill-split

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

// fune: replace money.allocate in hospitality.bill-split
// fune: replace money.amount in hospitality.bill-split
// fune: replace money.split-even in hospitality.bill-split
// fune: replace money.sum in hospitality.bill-split

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show hospitality.bill-split --steps.

// fune: step hospitality.bill-split after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
even three ways with 12.5% service items ×3, £7.50, 3, even, → ×3
even: 100.00 three ways, the odd penny to the first diner items ×1, £0.00, 3, even, → ×3
even: totals differ by a penny at most, service shared by what each pays items ×1, £6.25, 2, even, → ×2
even: splitting items and service separately would make totals 2p apart items ×1, £0.11, 2, even, → ×2
by item: each pays for what they had, shared items split, service in proportion items ×5, £11.13, 3, by-item, → ×3
by item: a shared item's odd penny goes to the first diner listed on it, not diner 0 items ×1, £0.00, 3, by-item, → ×3
by item: a diner who ordered nothing pays nothing items ×1, £0.38, 2, by-item, → ×2
by share: one pays for two items ×1, £10.00, 3, by-share, 2, 1, 1 → ×3
by share: a guest with share 0 pays nothing items ×1, £0.00, 3, by-share, 1, 0, 1 → ×3
one diner pays everything items ×3, £7.50, 1, even, → ×1
Show the other 15 tests
CaseArgumentsExpected
an empty bill splits to nothing , £0.00, 2, even, → ×2
an empty bill by item splits to nothing , £0.00, 2, by-item, → ×2
euros items ×1, €9.00, 4, even, → ×4
no diners is an error items ×3, £0.00, 0, even, → error: diners must be at least 1
an unknown method is an error items ×3, £0.00, 2, by-weight, → error: unknown split method "by-weight"
a diner who is not at the table is an error items ×1, £0.00, 3, by-item, → error: diner 3 is not at the table
a diner listed twice on an item is an error items ×1, £0.00, 3, by-item, → error: item "wine" lists diner 1 twice
shares with the even method are an error items ×3, £0.00, 2, even, 1, 1 → error: shares are only used by the by-share method
the wrong number of shares is an error items ×3, £0.00, 3, by-share, 1, 1 → error: shares must have one entry per diner
all-zero shares are an error items ×3, £0.00, 2, by-share, 0, 0 → error: shares must not all be zero
a negative share is an error items ×3, £0.00, 2, by-share, 2, -1 → error: shares must not be negative
a negative item is an error items ×1, £0.00, 2, even, → error: item amounts must not be negative
a negative service charge is an error items ×3, -£0.01, 2, even, → error: serviceCharge must not be negative
mixed currencies are an error items ×1, £0.00, 2, even, → error: currency mismatch
service on a bill with no items is an error , £1.00, 2, by-item, → error: a service charge cannot be shared on a bill with no items

More from the author

- **even**: the whole bill (items plus service) is split into near-equal totals with `money.allocate`, so no two diners' totals differ by more than a penny. The odd pennies go to the lowest-numbered diners. - **by-item**: each item is paid for by the diners listed on it (`diners`), split evenly between them with `money.split-even`. An empty list means the whole table shared it. The odd penny of a shared item goes to the first diner *listed on that item*, so the caller can decide who picks it up. - **by-share**: like even, but weighted: `shares` `[2, 1, 1]` means diner 0 pays half. A share of 0 pays nothing.

`shares` is only for by-share and must be `[]` otherwise. `BillItem.diners` is only read by by-item.

## The service charge

In every method the service charge is shared in proportion to what each diner pays for. Nobody pays service on someone else's steak, and in an even split the service shares follow the totals, so the totals stay within a penny. Splitting items and service separately and adding them up is the naive way, and it can leave even totals two pennies apart (5.07 and 5.05 on a 10.12 bill, where this gives 5.06 each).

Work the charge out first with `hospitality.service-charge`, then split.

## Edge cases and errors

- A bill with no items splits to zero for everyone. Any service charge on it is split evenly or by share, but refused by item, since there is nothing to share it by. - Item amounts and the service charge must not be negative. Apply a voucher before splitting, or split it as its own by-share bill. - Every amount must be in the service charge's currency. - A diner number outside 0 to diners - 1, or listed twice on one item, is an error.

Files

PathBytes
README.md1,965
impl/python.py3,969
impl/rust.rs5,450
impl/typescript.ts3,860
vectors.json12,670