Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.