Build an Immutable Money Value
Write the code, see it run, pass the checks.
The problem
- easy
- Code
Write a class Money that keeps an amount in whole cents, so sums never pick up floating-point errors. new Money(cents, currency) takes the amount in cents and a currency code such as "GBP", and throws a RangeError if cents isn't an integer. It has cents and currency properties, and a Money never changes once it's made: assigning to them has no effect. add(other) and subtract(other) return a new Money, leaving both untouched, and throw a TypeError if the currencies differ. equals(other) returns true when both the cents and the currency match, false otherwise. toString() gives the amount in units with two decimal places, a space and the currency: "12.05 GBP" for 1205 cents, "-0.50 GBP" for -50.
Your code must pass
- Adds and subtracts into a new Money
- Never changes after it's made
- Throws a TypeError when currencies differ
- Throws a RangeError for cents that aren't whole
- Compares with equals
- Formats as amount and currency