Chain API

chainAdd / chainSub / chainMul / chainDiv — chainable precision arithmetic.

Chain API

Chaining: chainAdd / chainSub / chainMul / chainDiv are the entry points, each returning an object you can continue calling .add().sub().mul().div() on. Terminate with empty parentheses () or by passing an IFormat object to get the final value.

Usage

chainAdd
(1, 2, 3)() // "6"
chainAdd
(10).
sub
(3).
mul
(2)() // "14"
chainAdd
(100, 200).
mul
(2)({
decimals
: 2,
thousands
: true }) // "600.00"
chainAdd
(1000, 2000)({
decimals
: 2,
thousands
: true }) // "3,000.00"

Try It Live

chainAdd(10).sub(3).mul(2)() // "14"
chainMul(2, 3).add(4)() // "10"
chainAdd(100, 200).mul(2)({ decimals: 2, thousands: true }) // "600.00"
在线运行⌘/Ctrl + Enter 运行

Signature

chainAdd(...args: (string | number | bigint)[]): IChain
chainSub(...args): IChain
chainMul(...args): IChain
chainDiv(...args): IChain

interface IChain {
    add(...args): IChain
    sub(...args): IChain
    mul(...args): IChain
    div(...args): IChain
    (format?: IFormat): string | number  // terminate
}

Multiple arguments passed to the entry function are reduced:

  • chainAdd(a, b, c)a + b + c
  • chainSub(a, b, c)a - b - c
  • chainMul(a, b, c)a * b * c
  • chainDiv(a, b, c)a / b / c

Difference from calc

  • calc uses a string expression — flexible but has parsing overhead
  • chain calls functions directly — more concise and better performance
// equivalent
calc
('(10 - 3) * 2') // "14"
chainAdd
(10).
sub
(3).
mul
(2)() // "14"