ts-money
ts-money copied to clipboard
Operations not working
Hello,
Looks like this package does not work when respecting the doc examples
Not working code:
const fiveEur = new Money(500, Currencies.EUR); // 5 EUR
// add
fiveEur.add(new Money(250, Currencies.EUR)); // 7.50 EUR
console.log(fiveEur);
Money { amount: 500, currency: 'EUR' }
Looks like 250 was not added
Working code:
const fiveEur = new Money(500, Currencies.EUR).add(new Money(250, Currencies.EUR));
console.log(fiveEur);
Money { amount: 7500, currency: 'EUR' }
Hi @bitbreakr, thanks for creating this issue. Functions on Money
objects always return a new Money
instance. This is why the third line of the example (fiveEur.subtract(new Money(470, Currencies.EUR));
) returns 0.30 EUR
(5.00 - 4.70
) and not 2.80 EUR
(7.50 - 4.70
). Though I agree it could perhaps be a bit clearer. I will add some clarifications in the example this weekend.
@macor161 Any specific reason you went with immutable objects? Is there a disadvantage to allowing the modification of Money objects?
@49e94b8f256530dc0d41f740dfe8a4c1, I can not speak to the authors reasoning; however here are some thoughts about immutable and mutable objects, and why a library might use immutable objects (especially one dealing with money where getting the value wrong can be very costly).
From my research, immutable objects
are especially applicable for value types, where objects don't have an identity so they can be easily replaced. And they can make concurrent programming way safer and cleaner (most of the notoriously hard to find concurrency bugs are ultimately caused by mutable state shared between threads).
- https://softwareengineering.stackexchange.com/a/151735
- https://frontstuff.io/how-to-handle-monetary-values-in-javascript#why-immutable