At the core of manipulating money are mutations. The Dinero.js API provides functions to manipulate objects. Most of them are calculus-based: adding, multiplying, etc.
import { dinero, add } from 'dinero.js';
import { USD } from '@dinero.js/currencies';
const d1 = dinero({ amount: 500, currency: USD });
const d2 = dinero({ amount: 800, currency: USD });
add(d1, d2);
Copy linkCalculating new amounts
Any application that handles money needs to manipulate them. A classic example is a checkout page where you need to calculate the total, add shipping, subtract discounts, etc.
import { dinero, add, allocate, subtract } from 'dinero.js';
import { USD } from '@dinero.js/currencies';
const products = [
{
name: 'Apple iPhone 12',
price: dinero({ amount: 89900, currency: USD }),
},
{
name: 'Apple AirPods Pro',
price: dinero({ amount: 17495, currency: USD }),
},
];
const subtotal = products.reduce(
(acc, { price }) => add(acc, price),
dinero({ amount: 0, currency: USD })
);
const [discount] = allocate([20, 80]);
const discounted = subtract(subtotal, discount);
const shipping = dinero({ amount: 1000, currency: USD });
const total = add(subtotal, shipping);
Copy linkDinero objects are immutable
Even though such functions can be categorized as "mutations", Dinero objects are immutable. When you're using a mutation function, the existing objects remain intact.
import { dinero, add, toSnapshot } from 'dinero.js';
// ...
toSnapshot(add(d1, d2));
// {
// amount: 1300,
// currency: {
// code: 'EUR',
// base: 10,
// exponent: 2,
// },
// scale: 2,
// }
toSnapshot(d1);
// {
// amount: 500,
// currency: {
// code: 'EUR',
// base: 10,
// exponent: 2,
// },
// scale: 2,
// }
toSnapshot(d2);
// {
// amount: 800,
// currency: {
// code: 'EUR',
// base: 10,
// exponent: 2,
// },
// scale: 2,
// }