_equalArrays.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. var SetCache = require('./_SetCache'),
  2. arraySome = require('./_arraySome'),
  3. cacheHas = require('./_cacheHas');
  4. /** Used to compose bitmasks for value comparisons. */
  5. var COMPARE_PARTIAL_FLAG = 1,
  6. COMPARE_UNORDERED_FLAG = 2;
  7. /**
  8. * A specialized version of `baseIsEqualDeep` for arrays with support for
  9. * partial deep comparisons.
  10. *
  11. * @private
  12. * @param {Array} array The array to compare.
  13. * @param {Array} other The other array to compare.
  14. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  15. * @param {Function} customizer The function to customize comparisons.
  16. * @param {Function} equalFunc The function to determine equivalents of values.
  17. * @param {Object} stack Tracks traversed `array` and `other` objects.
  18. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  19. */
  20. function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  21. var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
  22. arrLength = array.length,
  23. othLength = other.length;
  24. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  25. return false;
  26. }
  27. // Check that cyclic values are equal.
  28. var arrStacked = stack.get(array);
  29. var othStacked = stack.get(other);
  30. if (arrStacked && othStacked) {
  31. return arrStacked == other && othStacked == array;
  32. }
  33. var index = -1,
  34. result = true,
  35. seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
  36. stack.set(array, other);
  37. stack.set(other, array);
  38. // Ignore non-index properties.
  39. while (++index < arrLength) {
  40. var arrValue = array[index],
  41. othValue = other[index];
  42. if (customizer) {
  43. var compared = isPartial
  44. ? customizer(othValue, arrValue, index, other, array, stack)
  45. : customizer(arrValue, othValue, index, array, other, stack);
  46. }
  47. if (compared !== undefined) {
  48. if (compared) {
  49. continue;
  50. }
  51. result = false;
  52. break;
  53. }
  54. // Recursively compare arrays (susceptible to call stack limits).
  55. if (seen) {
  56. if (!arraySome(other, function(othValue, othIndex) {
  57. if (!cacheHas(seen, othIndex) &&
  58. (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  59. return seen.push(othIndex);
  60. }
  61. })) {
  62. result = false;
  63. break;
  64. }
  65. } else if (!(
  66. arrValue === othValue ||
  67. equalFunc(arrValue, othValue, bitmask, customizer, stack)
  68. )) {
  69. result = false;
  70. break;
  71. }
  72. }
  73. stack['delete'](array);
  74. stack['delete'](other);
  75. return result;
  76. }
  77. module.exports = equalArrays;