Skip to content

Amount

sum

1.0.0

Gets the total sum of all amounts in an AmountArray by adding all values together.

amountArray.sum();
  • Returns a new Amount instance with the total sum
  • Requires all amounts to have the same currency
  • Maintains immutability - original array remains unchanged
  • Uses the add() method internally for precise calculations
  • Throws error for empty arrays or mixed currencies
  • Simple and intuitive API
  • Comprehensive testing
ArgTypeDefault ValueRequired
No arguments required

From an AmountArray instance, use the sum() method to get the total sum of all amounts.

import { amount, AmountArray } from '@inpulse-ui/utils';
const amounts = new AmountArray(
amount(100, 'USD'),
amount(50, 'USD'),
amount(25, 'USD'),
amount(75, 'USD')
);
const result = amounts.sum();
console.log(result); // Results in Amount instance with value 250 USD

It requires all amounts to have the same currency:

const validAmounts = new AmountArray(
amount(33.33, 'EUR'),
amount(33.33, 'EUR'),
amount(33.34, 'EUR')
);
const result = validAmounts.sum();
console.log(result); // Results in Amount instance with value 100.00 EUR

It throws an error for mixed currencies:

const mixedAmounts = new AmountArray(
amount(100, 'USD'),
amount(50, 'EUR') // Different currency
);
// This will throw: "All amounts must have the same currency for sum operation."
const result = mixedAmounts.sum();

It throws an error for empty arrays:

const emptyArray = new AmountArray();
// This will throw: "Cannot sum an empty AmountArray."
const result = emptyArray.sum();

Works with negative values:

const amountsWithNegatives = new AmountArray(
amount(100, 'GBP'),
amount(-25, 'GBP'), // Discount
amount(50, 'GBP')
);
const result = amountsWithNegatives.sum();
console.log(result); // Results in Amount instance with value 125 GBP

Imagine a scenario in an e-commerce application. You need to sum all cart items to present the final total to the user at checkout.

import { amount, AmountArray } from '@inpulse-ui/utils';
// Shopping cart items
const subtotal = amount(89.99, 'USD');
const shipping = amount(9.99, 'USD');
const tax = amount(8.50, 'USD');
const discount = amount(-10.00, 'USD'); // Promotional discount
// Create array with all cart components
const cartComponents = new AmountArray(
subtotal,
shipping,
tax,
discount
);
// Calculate final total for checkout page
const finalTotal = cartComponents.sum();
console.log(`Cart Total: ${finalTotal}`); // Cart Total: 98.48 USD
// Present to user on checkout page
document.getElementById('cart-total').textContent = finalTotal.toString();

Project

Built with by Jo Santana in Brazil.

© 2026 Inpulse. All rights reserved.