UNPKG

domain-objects

Version:

A simple, convenient way to represent domain objects, leverage domain knowledge, and add runtime validation in your code base.

65 lines 2.21 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.withClone = exports.withImmute = void 0; const isOfDomainObject_1 = require("../../instantiation/inherit/isOfDomainObject"); const clone_1 = require("../../manipulation/clone/clone"); /** * .what = applies withImmute to a single object only (shallow) * .why = original behavior, available when recursive is not needed * .note = idempotent: safe to call multiple times on same object */ const singular = (obj) => { // skip if already has .clone() (idempotent) if ('clone' in obj) return obj; Object.defineProperty(obj, 'clone', { enumerable: false, configurable: false, writable: false, value: (updates) => (0, exports.withImmute)((0, clone_1.clone)(obj, updates)), }); return obj; }; /** * .what = applies withImmute to all domain objects in a value tree * .why = ensures nested domain objects also receive .clone() */ const recursive = (value) => { // apply to domain objects if ((0, isOfDomainObject_1.isOfDomainObject)(value)) { singular(value); // recurse into properties for nested domain objects Object.keys(value).forEach((key) => { recursive(value[key]); }); return value; } // recurse into arrays if (Array.isArray(value)) { value.forEach(recursive); return value; } // recurse into plain objects if (typeof value === 'object' && value !== null) { Object.keys(value).forEach((key) => { recursive(value[key]); }); } return value; }; /** * .what = adds immute operations (.clone) to domain objects * .why = enables immutable updates for safer, more maintainable code * * variants: * - withImmute(value) = recursive (default, pit of success) * - withImmute.recursive(value) = explicit recursive * - withImmute.singular(obj) = single object only (shallow) */ exports.withImmute = Object.assign(recursive, { recursive, singular }); /** * .what = alias for withImmute * .why = intuitive name for what it does (adds .clone()) */ exports.withClone = exports.withImmute; //# sourceMappingURL=withImmute.js.map