{{ message }}

Instantly share code, notes, and snippets.

# wolframkriesing/MonetaryAmount.js

Last active Oct 23, 2015
Value Object in JavaScript, or non-primitve value
 const valueSymbol = Symbol('value'); class MonetaryAmount { constructor(value) { this[valueSymbol] = value; } add(amount) { return new MonetaryAmount(amount.value + this.value); } equal(amount) { return amount.value == this.value; } get value() { return this[valueSymbol]; } } describe('monetary value object', () => { let oneEuro, twoEuro, threeEuro; beforeEach(() => { oneEuro = new MonetaryAmount(1); twoEuro = new MonetaryAmount(2); threeEuro = new MonetaryAmount(3); }); it('`oneEuro` equals `new MonetaryAmount(1)`', () => { assert.ok(oneEuro.equal(new MonetaryAmount(1))); }); it('1 + 2 = 3', () => { let result = oneEuro.add(twoEuro); assert.ok(result.equal(threeEuro)); }); it('`oneEuro + twoEuro` does NOT modify `oneEuro`', () => { oneEuro.add(twoEuro); assert.ok(oneEuro.equal(new MonetaryAmount(1))); }); it('`oneEuro + twoEuro` does NOT modify `twoEuro`', () => { oneEuro.add(twoEuro); assert.ok(twoEuro.equal(new MonetaryAmount(2))); }); it('the inner value may be readable, but not modifiable', () => { assert.throws(() => { oneEuro.value = 2; }); }); });

### marcoemrich commented Oct 23, 2015

 Great Example! Do you think it could be usefull to add a toNumber-Method to avoid duplicating all arithmetic methods like add, sub, ... ? Or it this against the concept?