value-object.js
Value Object
- objects that matter only as the combination of their
properties. Two value objects with the same values for all their properties are
considered equal.
This library provides a convenient way to define strict, immutable value
objects.
Install
npm install value-object
Defining value objects
Use subclasses to define value objects with type constraints:
const ValueObject = require('value-object')
class Currency extends ValueObject.define({
code: 'string',
name: 'string'
}) {}
class Money extends ValueObject.define({
currency: Currency,
amount: 'number'
}) {}
...or don't use classes, if you prefer:
var Money = ValueObject.define({
amount: 'number',
currency: { code: 'string' }
})
Instantiating value objects
Use the new
keyword:
const gbp = new Currency({ code: 'GBP', name: 'British Pounds' })
const price = new Money({ currency: gbp, amount: 12.34 })
const other = new Money({ currency: { code: 'USD', name: 'US Dollars' }, amount: 14.56 })
The type constraints prevent value objects from being instantiated with
incorrect arguments:
new Currency({ code: 'USD', name: 123 })
new Currency({ code: 'NZD', name: 'New Zealand Dollars', colour: 'All black' })
new Money({ amount: 123 })
Equality
Value objects are considered to be equal if their properties are equal:
gbp.isEqualTo(new Currency({ code: 'GBP', name: 'British Pounds' }))
gbp.isEqualTo(new Currency({ code: 'EUR', name: 'Euros' }))
const gbpPrice = new Money({ amount: 123, currency: gbp })
const eurPrice = new Money({ amount: 123, currency: eur })
gbpPrice.isEqualTo(eurPrice)
eurPrice.isEqualTo(new Money({ amount: 123, currency: eur }))
Array values
To specify array values wrap the type definition (e.g. 'number'
, Date
) in []
class Point extends ValueObject.define({
x: 'number',
y: 'number'
}) {}
class Polygon extends ValueObject.define({
vertices: [Point]
}) {}
Creating new value objects from existing value objects
Use with(newAttributes)
to create new value objects
var salePrice = price.with({ amount: 12.00 })
salePrice.currency.code
Converting value objects to JSON
Use toJSON()
to create an object that can be passed to JSON.stringify()
JSON.stringify(gbp.toJSON())
Converting value objects from JSON
Use ValueObject.deserializeForNamespaces()
to create a deserialize function
that can turn the resulting JSON string back into objects
const deserialize = ValueObject.deserializeForNamespaces([{ Currency }])
const gbp2 = deserialize('{"__type__":"Currency","code":"GBP","name":"British Pounds"}')
gbp2.isEqualTo(gbp)
Immutability
Value objects cannot be updated. Use strict mode
to throw errors when attempts to set property values are made.
gbp.code = 'USD'