Last active
October 23, 2015 13:56
-
-
Save wolframkriesing/af7c17b5ed8f375c7b40 to your computer and use it in GitHub Desktop.
Value Object in JavaScript, or non-primitve value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; }); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?