Skip to content

Instantly share code, notes, and snippets.

@unicornware
Created January 1, 2022 03:37
Show Gist options
  • Save unicornware/7c5f5a370715a96c523ab1c9ad3d1ddb to your computer and use it in GitHub Desktop.
Save unicornware/7c5f5a370715a96c523ab1c9ad3d1ddb to your computer and use it in GitHub Desktop.
ValueObject model
import type { ObjectPlain } from '@flex-development/tutils'
import isNIL from '@flex-development/tutils/guards/is-nil.guard'
import { shallowEqual } from 'shallow-equal-object'
/**
* @file Models - ValueObject
* @module models/ValueObject
*/
/**
* Base value object class.
*
* A value object is an object that can have its equality determined through
* its structrual property, rather than its identity (like an entity).
*
* @see https://khalilstemmler.com/articles/typescript-value-object
*
* @template T - Value object props
*/
export default class ValueObject<T extends ObjectPlain = ObjectPlain> {
constructor(readonly props: T) {
this.props = Object.freeze(props)
}
/**
* Determines if the current value object is equal to `obj`.
*
* @template T1 - Value object props for {@link obj}
*
* @param {ValueObject<any>} obj - Value object to check
* @return {boolean} `true` if equal, `false`, otherwise
*/
equals<T1 extends ObjectPlain = ObjectPlain>(obj: ValueObject<T1>): boolean {
if (isNIL(obj) || obj.props === undefined) return false
return shallowEqual(this.props, obj.props)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment