UNPKG

ts-prime

Version:

A utility library for JavaScript and Typescript.

72 lines (71 loc) 2.38 kB
import { type } from './type'; import { isFunction, isPromise, isArray, isObject } from './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 */ export function deepEqual(valueA, valueB, mode) { if (mode === void 0) { mode = 'hard'; } var compare = function (a, b) { if (a === b) return true; if (type(a) !== type(b)) return false; if (isFunction(a) && isFunction(b)) a.toString() === b.toString(); if (isPromise(a) && isPromise(b)) return a === b; if (isArray(a) && 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 (isObject(a) && 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); }