Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { type Money, money } from "./money_amount.ts"; ← from money.amount ^1.0.0 · built alongside by fune
/**
* Split `amount` into `parts` near-equal shares that sum to exactly `amount`.
*
* The leftover minor units go one each to the first shares, and a negative
* amount splits as the mirror image of the positive one, so a refund undoes
* the original split share for share.
*/
export function splitEven(amount: Money, parts: number): readonly Money[] {
if (!Number.isInteger(parts)) {
throw new TypeError(`parts must be a whole number, received ${parts}`);
}
if (parts < 1) {
throw new RangeError(`parts must be at least 1, received ${parts}`);
}
const sign = amount.minor < 0 ? -1 : 1;
const magnitude = Math.abs(amount.minor);
const base = Math.floor(magnitude / parts);
const leftover = magnitude - base * parts;
const shares: Money[] = [];
for (let i = 0; i < parts; i++) {
const share = base + (i < leftover ? 1 : 0);
// `0 * -1` is -0 in JavaScript; keep zero shares plain zero.
shares.push(money(share === 0 ? 0 : sign * share, amount.currency));
}
return shares;
}