tiny-types
Version:
A tiny library that brings Tiny Types to JavaScript and TypeScript
46 lines • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.equal = equal;
const significantFields_1 = require("./significantFields");
/**
* @access private
*/
function equal(v1, v2) {
switch (true) {
case !sameType(v1, v2):
return false;
case both(arePrimitives, v1, v2):
return checkIdentityOf(v1, v2);
case both(areObjects, v1, v2) && sameClass(v1, v2) && both(areDates, v1, v2):
return checkTimestamps(v1, v2);
case both(areObjects, v1, v2) && sameClass(v1, v2):
return checkSignificantFieldsOf(v1, v2);
}
return false;
}
const areObjects = (_) => new Object(_) === _;
const areDates = (_) => _ instanceof Date;
const arePrimitives = (_) => !areObjects(_); // arrays are objects
function both(condition, v1, v2) {
return condition(v1) && condition(v2);
}
const sameType = (v1, v2) => typeof v1 === typeof v2;
const sameClass = (v1, v2) => (v1.constructor && v2 instanceof v1.constructor) || (v2.constructor && v1 instanceof v2.constructor);
const sameLength = (v1, v2) => v1.length === v2.length;
function checkIdentityOf(v1, v2) {
return v1 === v2;
}
function checkTimestamps(v1, v2) {
return v1.getTime() === v2.getTime();
}
function checkSignificantFieldsOf(o1, o2) {
const fieldsOfObject1 = (0, significantFields_1.significantFieldsOf)(o1), fieldsOfObject2 = (0, significantFields_1.significantFieldsOf)(o2);
if (!sameLength(fieldsOfObject1, fieldsOfObject2)) {
return false;
}
return fieldsOfObject1.reduce((previousFieldsAreEqual, field) => {
const currentFieldIsEqual = equal(o1[field], o2[field]);
return previousFieldsAreEqual && currentFieldIsEqual;
}, true);
}
//# sourceMappingURL=equal.js.map