Open NoLongerBreathedIn opened 10 months ago
This issue persists since 2021 which is really bad for such a far reaching library. We have the same issue. It happens when both objects contain a Date. Duplicate of #278
Workaround: when creating the objects to compare, use toIsoString beforehand. e.g. bug = new Date('2032-01-04').toIsoString();
Error Source: // src/duplex.ts line 148 to 149 if (typeof obj.toJSON === "function") { obj = obj.toJSON(); } Explanation:
Possible Solution:
Here's a little helper function which patches Date
values - it traverses over arrays and objects:
/**
* The function takes an input value and applies data type patches if the input value is:
* - `Date` --> JSON representation as fast-json-patch cannot handle Dates
* - an `object` --> traverses the object tree applying patches to properties where necessary
* - an `array` --> traverses the array elements applying patches to properties where necessary
*
* All other data types - e.g. `string`, `number` will stay unpatched.
*
* @returns patched input when necessary
*/
export function patchDataTypes<T>(input: T): any {
if (input instanceof Date) {
return input.toJSON() as string;
} else if (typeof input === 'object' && input !== null) {
if (Array.isArray(input)) {
// If it's an array, recursively convert each element
return input.map(patchDataTypes);
} else {
// If it's an object, recursively convert each property
const result: Record<string, unknown> = {};
for (const key in input) {
result[key] = patchDataTypes(input[key]);
}
return result;
}
} else {
return input;
}
}
For example, suppose you have the following objects:
Then
compare(mirror, obj);
returns the following array: