Functional Weave
Code in TypeScript

money.apply-rate@1.0.0

impl/typescript.ts

952 bytes · the TypeScript implementation · view raw

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

import { type RoundingMode, roundDiv } from "./math_round_div.ts";  ← from math.round-div ^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

/**
 * Apply a rate given in basis points (10000 = 100%).
 *
 * Rates are integers, never floats, so VAT, discounts, interest and
 * commission all stay in exact arithmetic right up to the single rounding
 * step the caller asked for.
 */
export function applyRate(amount: Money, basisPoints: number, mode: RoundingMode = "half-up"): Money {
  if (!Number.isInteger(basisPoints)) {
    throw new TypeError(`basisPoints must be an integer, received ${basisPoints}`);
  }
  return money(roundDiv(amount.minor * basisPoints, 10000, mode), amount.currency);
}

/** The complement: what is left after the rate is taken off. */
export function applyRateComplement(amount: Money, basisPoints: number, mode: RoundingMode = "half-up"): Money {
  return money(amount.minor - applyRate(amount, basisPoints, mode).minor, amount.currency);
}