Functional Weave
Code in TypeScript

retail.gift-card-balance@1.0.0

impl/typescript.ts

878 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 { subtractMoney } from "./money_add.ts";  ← from money.add ^1.0.0 · built alongside by fune
import { type Money } from "./money_amount.ts";  ← from money.amount ^1.0.0 · built alongside by fune
import { minMoney } from "./money_compare.ts";  ← from money.compare ^1.0.0 · built alongside by fune
import { type GiftCardRedemption } from "./retail_gift_card_balance_types.ts";

/** Pay as much of `amountDue` as the card's balance allows. */
export function redeemGiftCard(balance: Money, amountDue: Money): GiftCardRedemption {
  if (balance.minor < 0) throw new RangeError(`balance must not be negative, received ${balance.minor}`);
  if (amountDue.minor < 0) {
    throw new RangeError(`amountDue must not be negative, received ${amountDue.minor}; a refund to a gift card is a top-up`);
  }
  const applied = minMoney(balance, amountDue);
  const stillDue = subtractMoney(amountDue, applied);
  return {
    applied,
    remainingBalance: subtractMoney(balance, applied),
    stillDue,
    fullyPaid: stillDue.minor === 0,
  };
}