UNPKG

fast-equals

Version:

A blazing-fast equality comparison utility for a variety of use-cases

984 lines (978 loc) • 42.4 kB
'use strict'; const { getOwnPropertyDescriptor: getOwnPropertyDescriptor$1, getOwnPropertyNames, getOwnPropertySymbols } = Object; const { hasOwnProperty, toString: toString$1 } = Object.prototype; /** * Whether the own properties from `end` onward are equal with strict property checking, where the * caller has already verified that both objects have the same number of own properties. */ function areStrictPropertiesEqual(a, b, state, properties, end) { let index = properties.length; let property; let descriptorA; let descriptorB; // Decrementing `while` showed faster results than either incrementing or // decrementing `for` loop and than an incrementing `while` loop. Declarative // methods like `some` / `every` were not used to avoid incurring the garbage // cost of anonymous callbacks. while (index-- > end) { property = properties[index]; if (!isReactProperty(a, b, property) && (!hasOwn(b, property) || !state.equals(a[property], b[property], property, property, a, b, state))) { return false; } descriptorA = getOwnPropertyDescriptor$1(a, property); descriptorB = getOwnPropertyDescriptor$1(b, property); if ((descriptorA || descriptorB) && (!descriptorA || !descriptorB || descriptorA.configurable !== descriptorB.configurable || descriptorA.enumerable !== descriptorB.enumerable || descriptorA.writable !== descriptorB.writable)) { return false; } } return true; } /** * Whether the own properties of objects whose value is compared by other means (`Date`, `RegExp`, * TypedArrays, primitive wrappers, etc.) are equal with strict property checking. Own properties * before `start` are intrinsic to the type and already covered by the value comparison, so only the * ones after them are compared. When `intrinsic` properties have been compared by the caller but are * not guaranteed to be listed first (`RegExp`'s `lastIndex`), objects with only those return early, * and otherwise every property from `start` is compared. * * @note * These objects rarely have own properties beyond their intrinsic ones, so that case returns before * any circular tracking is done. When they do, the properties can reference the object itself, so * the pair is tracked in the cache (when present) here rather than by wrapping the comparator with * `createIsCircular`. This keeps the cost of tracking off the common case. */ function areOwnPropertiesEqualStrict(a, b, state, start, intrinsic) { const properties = getOwnKeys(a); const length = properties.length; if (getOwnKeys(b).length !== length) { return false; } if (length === intrinsic) { return true; } const cache = state.cache; if (!cache) { return areStrictPropertiesEqual(a, b, state, properties, start); } const cachedA = cache.get(a); const cachedB = cache.get(b); if (cachedA && cachedB) { return cachedA === b && cachedB === a; } cache.set(a, b); cache.set(b, a); const result = areStrictPropertiesEqual(a, b, state, properties, start); cache.delete(a); cache.delete(b); return result; } /** * Wrap the provided `areItemsEqual` method to manage the circular state, allowing * for circular references to be safely included in the comparison without creating * stack overflows. */ function createIsCircular(areItemsEqual) { return function isCircular(a, b, state) { if (!a || !b || typeof a !== 'object' || typeof b !== 'object') { return areItemsEqual(a, b, state); } const { cache } = state; const cachedA = cache.get(a); const cachedB = cache.get(b); if (cachedA && cachedB) { return cachedA === b && cachedB === a; } cache.set(a, b); cache.set(b, a); const result = areItemsEqual(a, b, state); cache.delete(a); cache.delete(b); return result; }; } /** * Get the properties to strictly examine, which include both own properties that are * not enumerable and symbol properties. */ function getStrictProperties(object) { const symbols = getOwnPropertySymbols(object); return symbols.length ? getOwnPropertyNames(object).concat(symbols) : getOwnPropertyNames(object); } /** * Identify the element type of TypedArrays across realms and subclasses. */ const getTypedArrayTag = getOwnPropertyDescriptor$1(Object.getPrototypeOf(Int8Array.prototype), Symbol.toStringTag).get; /** * Get all own properties of the object, both strings and symbols, in the same order as * `getStrictProperties`. `Reflect.ownKeys` is used when available because it is faster for objects * like `Date` / `RegExp` / TypedArrays in V8. It is slower for plain objects without symbols, which * is why `getStrictProperties` is still used directly for those. */ const getOwnKeys = (typeof Reflect !== 'undefined' && Reflect.ownKeys) || getStrictProperties; /** * Whether the object contains the property passed as an own property. */ const hasOwn = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition Object.hasOwn || ((object, property) => hasOwnProperty.call(object, property)); /** * Whether a null-prototype object is being compared with a plain object. Only one side can be * null-prototype when the constructors differ. The other side must be a plain object by * constructor, or by tag when it comes from another realm. */ function isNullPrototypeComparable(a, b) { const aConstructor = a.constructor; const bConstructor = b.constructor; if (aConstructor == null) { return bConstructor === Object || toString$1.call(b) === '[object Object]'; } if (bConstructor == null) { return aConstructor === Object || toString$1.call(a) === '[object Object]'; } return false; } /** * Whether the property passed is a property specific to React/Preact elements. These are ignored in comparison, as they * are deeply circular and will return frequent false negatives for the comparison that matters, which is often the * React element's aspects (`props`, `type`, etc.). */ function isReactProperty(a, b, property) { return ( // _owner -> React owner // __o -> Preact owner // __v -> Preact vnode (property === '_owner' || property === '__o' || property === '__v') && !!(a.$$typeof || b.$$typeof)); } /** * Reorder a serialized query string so that params holding the same pairs compare as equal * regardless of the order they appear in. * * @note * The serializer percent-encodes `&` and `=` wherever they appear inside a name or a value, so * splitting on `&` recovers exactly the pairs and nothing else. */ function sortSearchParams(serialized) { return serialized.split('&').sort().join('&'); } /** * Above this many keys, out-of-position keys are checked with `propertyIsEnumerable` rather than by * scanning the other object's keys. Measured in V8: scanning wins up to 50 keys and loses from 100. */ const MAX_SCANNED_PROPERTIES = 64; const { getOwnPropertyDescriptor, keys } = Object; const { propertyIsEnumerable } = Object.prototype; const { valueOf: stringValueOf } = String.prototype; /** * Whether the values passed are equal based on a [SameValue](https://262.ecma-international.org/7.0/#sec-samevalue) basis. * Simplified, this maps to if the two values are referentially equal to one another (`a === b`) or both are `NaN`. * * @note * When available in the environment, this is just a re-export of the global * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) method. */ const sameValueEqual = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition Object.is || function sameValueEqual(a, b) { return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b; }; /** * Whether the values passed are equal based on a [SameValue](https://262.ecma-international.org/7.0/#sec-samevaluezero) basis. * Simplified, this maps to if the two values are referentially equal to one another (`a === b`), both are `NaN`, or both * are either positive or negative zero. */ function sameValueZeroEqual(a, b) { return a === b || (a !== a && b !== b); } /** * Whether the values passed are equal based on a * [Strict Equality Comparison](https://262.ecma-international.org/7.0/#sec-strict-equality-comparison) basis. * Simplified, this maps to if the two values are referentially equal to one another (`a === b`). * * @note * This is mainly available as a convenience function, such as being a default when a function to determine equality between * two objects is used. */ function strictEqual(a, b) { return a === b; } /** * Whether the array buffers are equal in value. */ function areArrayBuffersEqual(a, b) { return a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a), new Uint8Array(b)); } /** * Whether the array buffers are equal in value with strict property checking. */ function areArrayBuffersEqualStrict(a, b, state) { return areArrayBuffersEqual(a, b) && areOwnPropertiesEqualStrict(a, b, state, 0, 0); } /** * Whether the arrays are equal in value. */ function areArraysEqual(a, b, state) { let index = a.length; if (b.length !== index) { return false; } while (index-- > 0) { if (!state.equals(a[index], b[index], index, index, a, b, state)) { return false; } } return true; } /** * Whether the dataviews are equal in value. */ function areDataViewsEqual(a, b) { return (a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength))); } /** * Whether the dataviews are equal in value with strict property checking. */ function areDataViewsEqualStrict(a, b, state) { return areDataViewsEqual(a, b) && areOwnPropertiesEqualStrict(a, b, state, 0, 0); } /** * Whether the dates passed are equal in value. */ function areDatesEqual(a, b) { return sameValueEqual(a.getTime(), b.getTime()); } /** * Whether the dates passed are equal in value with strict property checking. */ function areDatesEqualStrict(a, b, state) { return areDatesEqual(a, b) && areOwnPropertiesEqualStrict(a, b, state, 0, 0); } /** * Whether the errors passed are equal in value. * * @note * `name`, `message` and `stack` are own properties but are not enumerable, so they are compared * explicitly. `cause` and `errors` are compared by value rather than by reference, matching how * every other nested value in the comparison is treated. They are compared exactly once, regardless * of whether they were assigned (enumerable) or set by the constructor (non-enumerable). Other own * enumerable properties (which custom `Error` subclasses commonly add) are compared afterward. * * The own property comparison is inlined rather than extracted, which measured faster in V8 when * recursing through `cause`. Keep the bytecode under V8's 460-byte TurboFan inlining limit (383 bytes * at time of writing; check with `node --print-bytecode --print-bytecode-filter=areErrorsEqual`), or * this stops being inlined into its callers. */ function areErrorsEqual(a, b, state) { if (a.name !== b.name || a.message !== b.message || a.stack !== b.stack) { return false; } const causeA = a.cause; const causeB = b.cause; if (causeA !== causeB && !state.equals(causeA, causeB, 'cause', 'cause', a, b, state)) { return false; } const errorsA = a.errors; const errorsB = b.errors; if (errorsA !== errorsB && !state.equals(errorsA, errorsB, 'errors', 'errors', a, b, state)) { return false; } const propertiesA = keys(a); const propertiesB = keys(b); let index = propertiesA.length; // Constructed errors rarely have enumerable own properties. if (!index && !propertiesB.length) { return true; } let compared = 0; let property; while (index-- > 0) { property = propertiesA[index]; // Already compared above regardless of enumerability, so we can ignore them. if (property === 'cause' || property === 'errors') { continue; } // `propertyIsEnumerable` rather than `hasOwn`, so that a non-enumerable own property on `b` cannot // stand in for an enumerable one. Keys in the same position are trivially enumerable on `b`. if ((property !== propertiesB[index] && !propertyIsEnumerable.call(b, property)) || !state.equals(a[property], b[property], property, property, a, b, state)) { return false; } ++compared; } // Every compared key is enumerable on `b`, so any of `b`'s keys left over must be `cause` / `errors`. const remaining = propertiesB.length - compared; return (!remaining || remaining === (propertyIsEnumerable.call(b, 'cause') ? 1 : 0) + (propertyIsEnumerable.call(b, 'errors') ? 1 : 0)); } /** * Whether the errors passed are equal in value. * * @note * `name`, `message` and `stack` are own properties but are not enumerable, so they are compared * explicitly. `cause` and `errors` are own properties, so `areObjectsEqualStrict` compares them along * with every other own property; they are not compared explicitly to avoid comparing them twice. */ function areErrorsEqualStrict(a, b, state) { return a.name === b.name && a.message === b.message && a.stack === b.stack && areObjectsEqualStrict(a, b, state); } /** * Whether the `Map`s are equal in value. */ function areMapsEqual(a, b, state) { const size = a.size; if (size !== b.size) { return false; } if (!size) { return true; } const matchedIndices = new Array(size); const aIterable = a.entries(); let aResult; let bResult; let index = 0; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while ((aResult = aIterable.next())) { if (aResult.done) { break; } const bIterable = b.entries(); let hasMatch = false; let matchIndex = 0; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while ((bResult = bIterable.next())) { if (bResult.done) { break; } if (matchedIndices[matchIndex]) { matchIndex++; continue; } const aEntry = aResult.value; const bEntry = bResult.value; if (state.equals(aEntry[0], bEntry[0], index, matchIndex, a, b, state) && state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a, b, state)) { hasMatch = matchedIndices[matchIndex] = true; break; } matchIndex++; } if (!hasMatch) { return false; } index++; } return true; } /** * Whether the `Map`s are equal in value with strict property checking. * * @note * The entries can be circular, so this is wrapped with `createIsCircular` in circular mode like * other containers, and the own properties are compared without additional tracking. */ function areMapsEqualStrict(a, b, state) { return areMapsEqual(a, b, state) && areObjectsEqualStrict(a, b, state); } /** * Whether the objects are equal in value. */ function areObjectsEqual(a, b, state) { const properties = keys(a); const propertiesB = keys(b); let index = properties.length; if (propertiesB.length !== index) { return false; } const isScannable = index <= MAX_SCANNED_PROPERTIES; let property; // Decrementing `while` showed faster results than either incrementing or // decrementing `for` loop and than an incrementing `while` loop. Declarative // methods like `some` / `every` were not used to avoid incurring the garbage // cost of anonymous callbacks. while (index-- > 0) { property = properties[index]; if (isReactProperty(a, b, property)) { continue; } // Objects built the same way list their keys in the same order, in which case the key is // already known to be an own enumerable property of `b` and the lookup can be skipped. // Otherwise, `propertiesB` is exactly `b`'s own enumerable keys. Scanning it is faster than // `propertyIsEnumerable` for smaller objects, but it is linear per key, so larger objects // (where reordering would make it quadratic) use the lookup instead. if ((property !== propertiesB[index] && !(isScannable ? propertiesB.includes(property) : propertyIsEnumerable.call(b, property))) || !state.equals(a[property], b[property], property, property, a, b, state)) { return false; } } return true; } /** * Whether the objects are equal in value with strict property checking. */ function areObjectsEqualStrict(a, b, state) { const properties = getStrictProperties(a); return getStrictProperties(b).length === properties.length && areStrictPropertiesEqual(a, b, state, properties, 0); } /** * Whether the primitive wrappers passed are equal in value. */ function arePrimitiveWrappersEqual(a, b) { return sameValueEqual(a.valueOf(), b.valueOf()); } /** * Whether the primitive wrappers passed are equal in value with strict property checking. * * @note * A `String` wrapper's characters are own index properties, listed first and in order, followed * by `length`. They are covered by the value comparison, so they are skipped, but only when the * value comes from the native `valueOf`. Otherwise (overridden or cross-realm `valueOf`) the value * may not reflect the characters, so they are compared as properties. */ function arePrimitiveWrappersEqualStrict(a, b, state) { const value = a.valueOf(); if (!sameValueEqual(value, b.valueOf())) { return false; } // `length` follows the characters, so a native `String` wrapper without other own properties has one more. return typeof value === 'string' && a.valueOf === stringValueOf && b.valueOf === stringValueOf ? areOwnPropertiesEqualStrict(a, b, state, value.length, value.length + 1) : areOwnPropertiesEqualStrict(a, b, state, 0, 0); } /** * Whether the regexps passed are equal in value. */ function areRegExpsEqual(a, b) { return a.source === b.source && a.flags === b.flags; } /** * Whether the regexps passed are equal in value with strict property checking. * * @note * `lastIndex` is an own property that every regexp has, and usually the only one. It is compared * directly so that the common case avoids the full property comparison. If it differs in identity or * writability, or there are other own properties, every own property is compared (including * `lastIndex`, since index properties may be listed before it). */ function areRegExpsEqualStrict(a, b, state) { if (!areRegExpsEqual(a, b)) { return false; } // Environments that predate (or polyfill around) `lastIndex` being an own property may not have // it, in which case there is nothing to shortcut and every own property is compared. const descriptorA = getOwnPropertyDescriptor(a, 'lastIndex'); const descriptorB = getOwnPropertyDescriptor(b, 'lastIndex'); return areOwnPropertiesEqualStrict(a, b, state, 0, descriptorA && descriptorB && a.lastIndex === b.lastIndex && descriptorA.configurable === descriptorB.configurable && descriptorA.enumerable === descriptorB.enumerable && descriptorA.writable === descriptorB.writable ? 1 : 0); } /** * Whether the search params passed are equal in value. * * @note * Order is not significant, matching how the other unordered collections in the library are * compared. Repeated keys are, so this is a comparison of multisets rather than of sets: * `a=1&a=2` is equal to `a=2&a=1`, but not to `a=1&a=1`. */ function areUrlSearchParamsEqual(a, b) { const serializedA = a.toString(); const serializedB = b.toString(); // Identical serializations are equal under any ordering, and this is by far the common case, so // it is worth checking before sorting anything. return serializedA === serializedB || sortSearchParams(serializedA) === sortSearchParams(serializedB); } /** * Whether the search params passed are equal in value with strict property checking. */ function areUrlSearchParamsEqualStrict(a, b, state) { return areUrlSearchParamsEqual(a, b) && areOwnPropertiesEqualStrict(a, b, state, 0, 0); } /** * Whether the `Set`s are equal in value. */ function areSetsEqual(a, b, state) { const size = a.size; if (size !== b.size) { return false; } if (!size) { return true; } const matchedIndices = new Array(size); const aIterable = a.values(); let aResult; let bResult; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while ((aResult = aIterable.next())) { if (aResult.done) { break; } const bIterable = b.values(); let hasMatch = false; let matchIndex = 0; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while ((bResult = bIterable.next())) { if (bResult.done) { break; } if (!matchedIndices[matchIndex] && state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a, b, state)) { hasMatch = matchedIndices[matchIndex] = true; break; } matchIndex++; } if (!hasMatch) { return false; } } return true; } /** * Whether the `Set`s are equal in value with strict property checking. * * @note * See `areMapsEqualStrict` for why the own properties are compared without additional tracking. */ function areSetsEqualStrict(a, b, state) { return areSetsEqual(a, b, state) && areObjectsEqualStrict(a, b, state); } /** * Whether the TypedArray instances are equal in value. */ function areTypedArraysEqual(a, b) { let index = a.length; // `byteOffset` is where the view starts in its buffer, not part of its value: two views holding // the same elements are equal wherever they sit, the same as `DataView` and `ArrayBuffer` // comparisons. Node.js `Buffer`s are views into a shared pool at varying offsets, so checking it // would make equal `Buffer`s compare unequal. if (b.length !== index) { return false; } // Only float-backed views can hold `NaN`, and the additional check needed to treat it as equal // to itself measurably slows the loop, so integer views keep the plain comparison. This is // hoisted out of the loop so the cost is paid once per call rather than once per element. const tag = getTypedArrayTag.call(a); if (tag === 'Float64Array' || tag === 'Float32Array' || tag === 'Float16Array') { while (index-- > 0) { // `NaN` is the only value not equal to itself, and it is treated as equal here to match // the SameValueZero semantics used for every other numeric comparison in the library. if (a[index] !== b[index] && (a[index] === a[index] || b[index] === b[index])) { return false; } } return true; } while (index-- > 0) { if (a[index] !== b[index]) { return false; } } return true; } /** * Whether the TypedArray instances are equal in value with strict property checking. * * @note * Indexed elements are also own properties, listed first and in order, with descriptors fixed by the * spec. They are compared once by `areTypedArraysEqual`, so only the own properties after them * (including symbols) are compared with strict property checking. */ function areTypedArraysEqualStrict(a, b, state) { return areTypedArraysEqual(a, b) && areOwnPropertiesEqualStrict(a, b, state, a.length, a.length); } /** * Whether the URL instances are equal in value. */ function areUrlsEqual(a, b) { // `href` is the normalized serialization of every component, so matching hrefs are equal without // any further work. Only a difference in query parameter ordering can survive a mismatch here. if (a.href === b.href) { return true; } return (a.protocol === b.protocol && a.username === b.username && a.password === b.password // `host` covers both the hostname and the port. && a.host === b.host && a.pathname === b.pathname && a.hash === b.hash && areUrlSearchParamsEqual(a.searchParams, b.searchParams)); } /** * Whether the URL instances are equal in value with strict property checking. */ function areUrlsEqualStrict(a, b, state) { return areUrlsEqual(a, b) && areOwnPropertiesEqualStrict(a, b, state, 0, 0); } const { toString } = Object.prototype; const toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag; /** * Create a comparator method based on the type-specific equality comparators passed. */ function createEqualityComparator(config) { const supportedComparatorMap = createSupportedComparatorMap(config); const { areArraysEqual, areDatesEqual, areFunctionsEqual, areMapsEqual, areNumbersEqual, areObjectsEqual, areRegExpsEqual, areSetsEqual, getUnsupportedCustomComparator, strictNullPrototypeComparison, } = config; /** * Whether the custom objects are equal in value, based on their string tag. If not matching any tags * that require a specific type of comparison, then we hard-code false because the only thing remaining * is strict equality, which has already been compared. This is for a few reasons: * - Certain types that cannot be introspected (e.g., `WeakMap`). For these types, this is the only * comparison that can be made. * - For types that can be introspected but do not have an objective definition of what * equality is (`Error`, etc.), the subjective decision is to be conservative and strictly compare. * In all cases, these decisions should be reevaluated based on changes to the language and * common development practices. * * When `Symbol.toStringTag` is a non-empty string (TypedArrays, `ArrayBuffer`, `DataView`, `Map`, `URL`, * etc.), `toString()` returns `[object ${stringTag}]` regardless of the object's type, so the comparator * is looked up by the `Symbol.toStringTag` value directly. This avoids building (and then hashing) the * full tag string for every comparison. Otherwise the tag depends on the built-in type, and is captured * with `toString()` as before. * * Capturing the tag is reasonably performant in modern environments like v8 and SpiderMonkey. This is * kept out of the main comparator so that it stays within the engine's bytecode budget for inlining. * See [#207](https://github.com/planttheidea/fast-equals/pull/207) for more details. */ const areTaggedObjectsEqual = getUnsupportedCustomComparator ? function areTaggedObjectsEqual(a, b, state) { const stringTag = toStringTag && a[toStringTag]; const tag = stringTag && typeof stringTag === 'string' ? stringTag : toString.call(a); const supportedComparator = supportedComparatorMap[tag]; if (supportedComparator) { return supportedComparator(a, b, state); } const unsupportedCustomComparator = getUnsupportedCustomComparator(a, b, state, tag === stringTag ? toString.call(a) : tag); return unsupportedCustomComparator ? unsupportedCustomComparator(a, b, state) : false; } : function areTaggedObjectsEqual(a, b, state) { const stringTag = toStringTag && a[toStringTag]; const supportedComparator = supportedComparatorMap[stringTag && typeof stringTag === 'string' ? stringTag : toString.call(a)]; return supportedComparator ? supportedComparator(a, b, state) : false; }; /** * compare the value of the two objects and return true if they are equivalent in values */ return function comparator(a, b, state) { // If the items are strictly equal, no need to do a value comparison. if (a === b) { return true; } // If either of the items are nullish and fail the strictly equal check // above, then they must be unequal. if (a == null || b == null) { return false; } const type = typeof a; if (type !== typeof b) { return false; } if (type !== 'object') { if (type === 'number' || type === 'bigint') { return areNumbersEqual(a, b, state); } if (type === 'function') { return areFunctionsEqual(a, b, state); } // If a primitive value that is not strictly equal, it must be unequal. return false; } const constructor = a.constructor; // Checks are listed in order of commonality of use-case: // 1. Common complex object types (plain object, array) // 2. Common data values (date, regexp) // 3. Less-common complex object types (map, set, null-prototype object) // 4. Less-common data values (promise, primitive wrappers) // Inherently this is both subjective and assumptive, however // when reviewing comparable libraries in the wild this order // appears to be generally consistent. // Constructors should match, otherwise there is potential for false positives // between class and subclass or custom object and POJO. if (constructor !== b.constructor) { return strictNullPrototypeComparison ? false : isNullPrototypeComparable(a, b) && areObjectsEqual(a, b, state); } // Try to fast-path equality checks for other complex object types in the // same realm to avoid capturing the string tag. Strict equality is used // instead of `instanceof` because it is more performant for the common // use-case. If someone is creating a subclass from a native class, it will be // handled with the string tag comparison. if (constructor === Object) { return areObjectsEqual(a, b, state); } if (constructor === Array) { return areArraysEqual(a, b, state); } if (constructor === Date) { return areDatesEqual(a, b, state); } if (constructor === RegExp) { return areRegExpsEqual(a, b, state); } if (constructor === Map) { return areMapsEqual(a, b, state); } if (constructor === Set) { return areSetsEqual(a, b, state); } if (constructor == null) { // Objects with a prototype of `null` are plain objects. return areObjectsEqual(a, b, state); } if (constructor === Promise) { // Avoid tag checks for promise values, since we know if they are not referentially equal // then they are not equal. return false; } // `isArray()` works on subclasses and is cross-realm, so we can avoid capturing // the string tag or doing an `instanceof` in edge cases. if (Array.isArray(a)) { return areArraysEqual(a, b, state); } // Since this is a custom object, use the string tag to determine its type. return areTaggedObjectsEqual(a, b, state); }; } /** * Create the configuration object used for building comparators. */ function createEqualityComparatorConfig({ circular, createCustomConfig, strict, strictNullPrototypeComparison = true, }) { // In strict mode, every type compares its own properties in addition to its value, because any // object can have properties assigned to it (`date.foo = 'bar'`). For types that hold their value // internally (`Date`, `RegExp`, TypedArrays, etc.), only the properties after the intrinsic ones // are compared, and circular references among them are tracked by the comparator itself (see // `areOwnPropertiesEqualStrict`). let config = { areArrayBuffersEqual: strict ? areArrayBuffersEqualStrict : areArrayBuffersEqual, areArraysEqual: strict ? areObjectsEqualStrict : areArraysEqual, areDataViewsEqual: strict ? areDataViewsEqualStrict : areDataViewsEqual, areDatesEqual: strict ? areDatesEqualStrict : areDatesEqual, // `name` / `message` / `stack` / `cause` / `errors` are not enumerable (unless assigned), which is why // errors need a comparator of their own rather than being treated as plain objects. Each variant also // compares the own properties that `Error` subclasses routinely carry (`status`, `code`, ...): // enumerable ones in loose mode, and all of them (via `areObjectsEqualStrict`) in strict mode. areErrorsEqual: strict ? areErrorsEqualStrict : areErrorsEqual, areFunctionsEqual: strictEqual, areMapsEqual: strict ? areMapsEqualStrict : areMapsEqual, areNumbersEqual: sameValueEqual, areObjectsEqual: strict ? areObjectsEqualStrict : areObjectsEqual, arePrimitiveWrappersEqual: strict ? arePrimitiveWrappersEqualStrict : arePrimitiveWrappersEqual, areRegExpsEqual: strict ? areRegExpsEqualStrict : areRegExpsEqual, areSetsEqual: strict ? areSetsEqualStrict : areSetsEqual, areTypedArraysEqual: strict ? areTypedArraysEqualStrict : areTypedArraysEqual, areUrlSearchParamsEqual: strict ? areUrlSearchParamsEqualStrict : areUrlSearchParamsEqual, areUrlsEqual: strict ? areUrlsEqualStrict : areUrlsEqual, getUnsupportedCustomComparator: undefined, strictNullPrototypeComparison, }; if (createCustomConfig) { config = Object.assign({}, config, createCustomConfig(config)); } if (circular) { // Only containers are wrapped, since they always compare nested values. Types that hold their // value internally only do so for own properties in strict mode, and track those themselves. // Errors are included because comparing `cause` and own properties by value means an error // that references itself would otherwise recurse without bound. config = Object.assign({}, config, { areArraysEqual: createIsCircular(config.areArraysEqual), areErrorsEqual: createIsCircular(config.areErrorsEqual), areMapsEqual: createIsCircular(config.areMapsEqual), areObjectsEqual: createIsCircular(config.areObjectsEqual), areSetsEqual: createIsCircular(config.areSetsEqual), }); } return config; } /** * Default equality comparator pass-through, used as the standard `isEqual` creator for * use inside the built comparator. */ function createInternalEqualityComparator(compare) { return function (a, b, _indexOrKeyA, _indexOrKeyB, _parentA, _parentB, state) { return compare(a, b, state); }; } /** * Create the `isEqual` function used by the consuming application. */ function createIsEqual({ circular, comparator, createState, equals, strict }) { if (createState) { return function isEqual(a, b) { const { cache = circular ? new WeakMap() : undefined, meta } = createState(); return comparator(a, b, { cache, equals, meta, strict, }); }; } if (circular) { return function isEqual(a, b) { return comparator(a, b, { cache: new WeakMap(), equals, meta: undefined, strict, }); }; } const state = { cache: undefined, equals, meta: undefined, strict, }; return function isEqual(a, b) { return comparator(a, b, state); }; } /** * Create a map of tags to their respective handlers for `tag`-based lookups. Each handler is keyed * by both its `Symbol.toStringTag` value (`Map`) and its `toString()` value (`[object Map]`). * * @note * The map has a `null` prototype, so a `Symbol.toStringTag` like `constructor` or `toString` cannot * resolve to an inherited `Object.prototype` method. */ function createSupportedComparatorMap(config) { return [ ['Arguments', config.areObjectsEqual], ['Array', config.areArraysEqual], ['ArrayBuffer', config.areArrayBuffersEqual], ['AsyncGeneratorFunction', config.areFunctionsEqual], ['BigInt', config.arePrimitiveWrappersEqual], ['BigInt64Array', config.areTypedArraysEqual], ['BigUint64Array', config.areTypedArraysEqual], ['Boolean', config.arePrimitiveWrappersEqual], ['DataView', config.areDataViewsEqual], ['Date', config.areDatesEqual], // If an error tag, it should be tested explicitly. Like RegExp, the properties are not // enumerable, and therefore will give false positives if tested like a standard object. ['Error', config.areErrorsEqual], ['Float16Array', config.areTypedArraysEqual], ['Float32Array', config.areTypedArraysEqual], ['Float64Array', config.areTypedArraysEqual], ['Function', config.areFunctionsEqual], ['GeneratorFunction', config.areFunctionsEqual], ['Int8Array', config.areTypedArraysEqual], ['Int16Array', config.areTypedArraysEqual], ['Int32Array', config.areTypedArraysEqual], ['Map', config.areMapsEqual], ['Number', config.arePrimitiveWrappersEqual], [ 'Object', (a, b, state) => // The exception for value comparison is custom `Promise`-like class instances. These should // be treated the same as standard `Promise` objects, which means strict equality, and if // it reaches this point then that strict equality comparison has already failed. typeof a.then !== 'function' && typeof b.then !== 'function' && config.areObjectsEqual(a, b, state), ], // For RegExp, the properties are not enumerable, and therefore will give false positives if // tested like a standard object. ['RegExp', config.areRegExpsEqual], ['Set', config.areSetsEqual], ['String', config.arePrimitiveWrappersEqual], ['URL', config.areUrlsEqual], ['URLSearchParams', config.areUrlSearchParamsEqual], ['Uint8Array', config.areTypedArraysEqual], ['Uint8ClampedArray', config.areTypedArraysEqual], ['Uint16Array', config.areTypedArraysEqual], ['Uint32Array', config.areTypedArraysEqual], ].reduce((comparatorMap, [tag, comparator]) => { comparatorMap[tag] = comparatorMap[`[object ${tag}]`] = comparator; return comparatorMap; }, Object.create(null)); } /** * Whether the items passed are deeply-equal in value. */ const deepEqual = createCustomEqual(); /** * Whether the items passed are deeply-equal in value based on strict comparison. */ const strictDeepEqual = createCustomEqual({ strict: true }); /** * Whether the items passed are deeply-equal in value, including circular references. */ const circularDeepEqual = createCustomEqual({ circular: true }); /** * Whether the items passed are deeply-equal in value, including circular references, * based on strict comparison. */ const strictCircularDeepEqual = createCustomEqual({ circular: true, strict: true, }); /** * Whether the items passed are shallowly-equal in value. */ const shallowEqual = createCustomEqual({ createInternalComparator: () => sameValueEqual, }); /** * Whether the items passed are shallowly-equal in value based on strict comparison */ const strictShallowEqual = createCustomEqual({ strict: true, createInternalComparator: () => sameValueEqual, }); /** * Whether the items passed are shallowly-equal in value, including circular references. */ const circularShallowEqual = createCustomEqual({ circular: true, createInternalComparator: () => sameValueEqual, }); /** * Whether the items passed are shallowly-equal in value, including circular references, * based on strict comparison. */ const strictCircularShallowEqual = createCustomEqual({ circular: true, createInternalComparator: () => sameValueEqual, strict: true, }); /** * Create a custom equality comparison method. * * This can be done to create very targeted comparisons in extreme hot-path scenarios * where the standard methods are not performant enough, but can also be used to provide * support for legacy environments that do not support expected features like * `RegExp.prototype.flags` out of the box. */ function createCustomEqual(options = {}) { const { circular = false, createInternalComparator: createCustomInternalComparator, createState, strict = false, } = options; const config = createEqualityComparatorConfig(options); const comparator = createEqualityComparator(config); const equals = createCustomInternalComparator ? createCustomInternalComparator(comparator) : createInternalEqualityComparator(comparator); return createIsEqual({ circular, comparator, createState, equals, strict }); } exports.circularDeepEqual = circularDeepEqual; exports.circularShallowEqual = circularShallowEqual; exports.createCustomEqual = createCustomEqual; exports.deepEqual = deepEqual; exports.sameValueEqual = sameValueEqual; exports.sameValueZeroEqual = sameValueZeroEqual; exports.shallowEqual = shallowEqual; exports.strictCircularDeepEqual = strictCircularDeepEqual; exports.strictCircularShallowEqual = strictCircularShallowEqual; exports.strictDeepEqual = strictDeepEqual; exports.strictEqual = strictEqual; exports.strictShallowEqual = strictShallowEqual;