39 lines
787 B
TypeScript
39 lines
787 B
TypeScript
|
|
import { shallowEqual } from "shallow-equal-object";
|
||
|
|
|
||
|
|
export abstract class ValueObject<T> {
|
||
|
|
protected readonly value: T;
|
||
|
|
|
||
|
|
protected constructor(value: T) {
|
||
|
|
if (value === null || value === undefined) {
|
||
|
|
throw new Error("ValueObject value cannot be null or undefined");
|
||
|
|
}
|
||
|
|
this.value = typeof value === "object" ? Object.freeze(value) : value;
|
||
|
|
|
||
|
|
Object.freeze(this);
|
||
|
|
}
|
||
|
|
|
||
|
|
equals(other: ValueObject<T>): boolean {
|
||
|
|
if (!(other instanceof ValueObject)) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (other.value === undefined) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
return shallowEqual(this.value, other.value);
|
||
|
|
}
|
||
|
|
|
||
|
|
getValue(): T {
|
||
|
|
return this.value;
|
||
|
|
}
|
||
|
|
|
||
|
|
toString(): string {
|
||
|
|
return String(this.value);
|
||
|
|
}
|
||
|
|
|
||
|
|
clone(): this {
|
||
|
|
return Object.create(this);
|
||
|
|
}
|
||
|
|
}
|