UNPKG

@a11d/equals

Version:

A value equality utility library.

36 lines (35 loc) 1.22 kB
import { equals } from './symbol.js'; Object.prototype[equals] = function (other) { if (this === other) { return true; } if (!(other instanceof Object)) { if (typeof other === 'object' && other !== null) { return this[equals](Object.assign({}, other)); } return false; } if (this.constructor !== other.constructor) { return false; } if ('valueOf' in this && 'valueOf' in other && this.valueOf !== Object.prototype.valueOf && this.valueOf !== Object.prototype.valueOf) { return this.valueOf() === other.valueOf(); } const nonUndefinedKeys = Object.keys(this).filter(key => this[key] !== undefined); const otherNonUndefinedKeys = Object.keys(other).filter(key => other[key] !== undefined); if (nonUndefinedKeys.length !== otherNonUndefinedKeys.length) { return false; } for (const [key, value] of Object.entries(this)) { if (value === undefined) { continue; } if (!Object.prototype.hasOwnProperty.call(other, key)) { return false; } if (!Object[equals](value, other[key])) { return false; } } return true; };