Skip to content

Instantly share code, notes, and snippets.

@wolframkriesing
Last active October 23, 2015 13:56
Show Gist options
  • Save wolframkriesing/af7c17b5ed8f375c7b40 to your computer and use it in GitHub Desktop.
Save wolframkriesing/af7c17b5ed8f375c7b40 to your computer and use it in GitHub Desktop.
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
Copy link

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