diff --git a/src/lib/utils/functions.ts b/src/lib/utils/functions.ts index 6c36967..9adc948 100644 --- a/src/lib/utils/functions.ts +++ b/src/lib/utils/functions.ts @@ -1,6 +1,7 @@ import { ITrackable } from '../listing/models/trackable'; import moment from 'moment'; import { FormGroup } from '@angular/forms'; +import _ from 'lodash'; export function capitalize(value: string): string { if (!value) { @@ -82,3 +83,33 @@ export function getLeftDateTime(ISOString: string) { return { daysLeft, hoursLeft, minutesLeft }; } + +export function deepDiffObj(base: Record, object: Record) { + if (!object) { + throw new Error(`The object compared should be an object: ${object}`); + } + + if (!base) { + return object; + } + + const res = _.transform(object, (result: Record, value, key) => { + if (!_.has(base, key)) { + result[key] = value; + } // fix edge case: not defined to explicitly defined as undefined + if (!_.isEqual(value, base[key])) { + result[key] = + _.isPlainObject(value) && _.isPlainObject(base[key]) + ? deepDiffObj(base[key] as Record, value as Record) + : value; + } + }); + // map removed fields to undefined + _.forOwn(base, (value, key) => { + if (!_.has(object, key)) { + res[key] = undefined; + } + }); + + return res; +}