import transform from 'lodash.transform'; import { isObject } from './isObject'; /** * Deep diff between two object, using lodash * @param {Object} object Object compared * @param {Object} base Object to compare with * @return {Object} Return a new object who represent the diff */ export function difference( object: T, base: T | any[] | object = {}, ): T | T[] | Record { if (Array.isArray(object)) { return object.filter((x) => !(base as any[]).includes(x)); } const mergedObject = { ...base, ...object, }; function changes( subObject: T | Record, subBase: T | Record, subMergedObject?: Record, ): Record { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition return transform(subMergedObject || {}, (result, _value, key) => { const value = subObject[key]; if (!Object.prototype.hasOwnProperty.call(subBase, key)) { result[key] = value; // eslint-disable-next-line eqeqeq } else if (value != subBase[key]) { const newValue = (isObject(value) && isObject(subBase[key])) ? changes(value, subBase[key], { ...subBase[key], ...value, }) : value; result[key] = newValue; } }); } return changes(object, base, mergedObject); } export function isDifference(object: any, base: any = {}): boolean { return Array.isArray(object) ? (difference(object, base)).length > 0 : Object.keys(difference(object, base)).length > 0; }