crumbsplit
v0.1.0
Published
Split integer units and decimal amounts exactly using largest remainders.
Maintainers
Readme
crumbsplit
Split integer units and decimal amounts exactly using largest remainders.
Node.js 22+. No runtime dependencies. CommonJS, ES modules and TypeScript declarations. MIT licensed. This is the JavaScript edition; no Python installation is needed.
Install
npm install crumbsplitJavaScript
import { allocate, splitAmount } from 'crumbsplit';
console.assert(JSON.stringify(splitAmount('100.00', [1, 1, 1])) ===
JSON.stringify(['33.34', '33.33', '33.33']));
console.assert(JSON.stringify(allocate(10, [1, 2, 3])) === '[2,3,5]');
console.assert(allocate(9007199254740993n, [1])[0] === 9007199254740993n);CommonJS is also supported: const api = require('crumbsplit');.
ES modules support both named exports and a default API object.
Command line
npx crumbsplit 100.00 --parts 3
npx crumbsplit 10 --integer --weights 1 2 3
npx crumbsplit 0.02 --parts 3 --offset 1Use --help for usage and --version for the package version.
You can install globally with npm install -g crumbsplit to run the command directly.
API and behavior
allocate(total, weights, {offset = 0}) distributes non-negative integer units by
Hamilton's largest-remainder method, preserving the exact total. A safe integer
number total returns number[]; a bigint total returns bigint[]. Weights are
non-negative numbers, bigint values, or decimal/fraction strings. At least one
weight must be positive. Zero weights receive zero.
splitAmount(amount, weights, {places = 2, offset = 0}) returns fixed-precision
decimal strings, never floating-point amounts. Precision is 0 through 18 places.
An amount with excess precision is rejected, not rounded. Ties follow input order
starting at offset and wrapping around (negative offsets are supported).
Use decimal strings for money and bigint for large integer totals. Unsafe number integers, booleans, negative values and non-finite numbers are rejected. A number argument may already contain floating-point rounding before reaching this API. No currency conversion is performed.
CLI output always uses JSON strings, including --integer, so large values can be
read without precision loss. Use exactly one of --parts N or --weights W...;
put AMOUNT before options. Exit codes: 0 success, 2 invalid input.
Development
In the source checkout, run npm test. Tests use Node's built-in test runner;
there are no test framework dependencies. npm pack builds the publishable tarball.
Tests and local state are excluded from the tarball.
