MCPcopy Create free account
hub / github.com/mikro-orm/mikro-orm / compareObjects

Function compareObjects

packages/core/src/utils/Utils.ts:38–104  ·  view source on GitHub ↗
(a: any, b: any)

Source from the content-addressed store, hash-verified

36
37/** Deeply compares two objects for equality, handling dates, regexes, and raw fragments. */
38export function compareObjects(a: any, b: any): boolean {
39 if (a === b || (a == null && b == null)) {
40 return true;
41 }
42
43 if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {
44 return false;
45 }
46
47 // Raw fragments are compared by `sql` + `params` *before* the constructor
48 // check, so that two fragments carrying the same SQL but constructed by
49 // different CJS/ESM copies of this module (different classes, different
50 // prototypes) still compare as equal. Without this, the dual-package hazard
51 // would produce spurious change-set diffs when a raw fragment is used as a
52 // property value.
53 if (isRaw(a) && isRaw(b)) {
54 // eslint-disable-next-line @typescript-eslint/no-use-before-define
55 return a.sql === b.sql && compareArrays(a.params, b.params);
56 }
57
58 if (!compareConstructors(a, b)) {
59 return false;
60 }
61
62 if (a instanceof Date && b instanceof Date) {
63 const timeA = a.getTime();
64 const timeB = b.getTime();
65 if (isNaN(timeA) || isNaN(timeB)) {
66 throw new Error('Comparing invalid dates is not supported');
67 }
68 return timeA === timeB;
69 }
70
71 /* v8 ignore next */
72 if (
73 (typeof a === 'function' && typeof b === 'function') ||
74 (a instanceof RegExp && b instanceof RegExp) ||
75 (a instanceof String && b instanceof String) ||
76 (a instanceof Number && b instanceof Number)
77 ) {
78 return a.toString() === b.toString();
79 }
80
81 const keys = Object.keys(a);
82 const length = keys.length;
83
84 if (length !== Object.keys(b).length) {
85 return false;
86 }
87
88 for (let i = length; i-- !== 0; ) {
89 if (!Object.hasOwn(b, keys[i])) {
90 return false;
91 }
92 }
93
94 for (let i = length; i-- !== 0; ) {
95 const key = keys[i];

Callers 3

GHx6.test.tsFile · 0.90
equalsFunction · 0.85
Utils.win.test.tsFile · 0.85

Calls 6

isRawFunction · 0.85
compareArraysFunction · 0.85
compareConstructorsFunction · 0.85
equalsFunction · 0.85
toStringMethod · 0.45
keysMethod · 0.45

Tested by

no test coverage detected