ts-prime
Version:
A utility library for JavaScript and Typescript.
75 lines (74 loc) • 2.52 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var type_1 = require("./type");
var index_1 = require("./index");
/**
* Compares two values recursively.
* @warning Soft mode is relative expensive operation.
* @description
* The function has two modes `soft` and `hard` soft mode ignores array order hard mode preserves array order
* - `Soft mode` ignore array order.
* @param valueA - anything
* @param valueB - anything
* @example
* P.deepEquals({
* data: 1,
* super: [{ id: 1, name: "Tom" }, { id: 2, name: "Martin" }]
* }, {
* data: 1,
* super: [{ id: 2, name: "Martin" }, { id: 1, name: "Tom" }]
* }) // false super property is not equal
*
* P.deepEquals({
* data: 1,
* super: [{ id: 1, name: "Tom" }, { id: 2, name: "Martin" }]
* }, {
* data: 1,
* super: [{ id: 2, name: "Martin" }, { id: 1, name: "Tom" }]
* }, 'soft') // true Ignores array order
*
*
* @param mode - array comparison mode
* @category Utility
*/
function deepEqual(valueA, valueB, mode) {
if (mode === void 0) { mode = 'hard'; }
var compare = function (a, b) {
if (a === b)
return true;
if (type_1.type(a) !== type_1.type(b))
return false;
if (index_1.isFunction(a) && index_1.isFunction(b))
a.toString() === b.toString();
if (index_1.isPromise(a) && index_1.isPromise(b))
return a === b;
if (index_1.isArray(a) && index_1.isArray(b)) {
if (a.length !== b.length)
return false;
var aArray = mode === 'hard' ? a : a;
var bArray = mode === 'hard' ? b : b;
for (var index in aArray) {
if (!deepEqual(aArray[index], bArray[index]))
return false;
}
return true;
}
if (index_1.isObject(a) && index_1.isObject(b)) {
var aKeys = Object.keys(a);
var bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length)
return false;
if (!deepEqual(aKeys, bKeys))
return false;
for (var _i = 0, aKeys_1 = aKeys; _i < aKeys_1.length; _i++) {
var aKey = aKeys_1[_i];
if (!deepEqual(a[aKey], b[aKey]))
return false;
}
return true;
}
return false;
};
return compare(valueA, valueB);
}
exports.deepEqual = deepEqual;