_equalArrays.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. // Assume cyclic values are equal.
  28. var stacked = stack.get(array);
  29. if (stacked && stack.get(other)) {
  30. return stacked == other;
  31. }
  32. var index = -1,
  33. result = true,
  34. seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
  35. stack.set(array, other);
  36. stack.set(other, array);
  37. // Ignore non-index properties.
  38. while (++index < arrLength) {
  39. var arrValue = array[index],
  40. othValue = other[index];
  41. if (customizer) {
  42. var compared = isPartial
  43. ? customizer(othValue, arrValue, index, other, array, stack)
  44. : customizer(arrValue, othValue, index, array, other, stack);
  45. }
  46. if (compared !== undefined) {
  47. if (compared) {
  48. continue;
  49. }
  50. result = false;
  51. break;
  52. }
  53. // Recursively compare arrays (susceptible to call stack limits).
  54. if (seen) {
  55. if (!arraySome(other, function(othValue, othIndex) {
  56. if (!cacheHas(seen, othIndex) &&
  57. (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  58. return seen.push(othIndex);
  59. }
  60. })) {
  61. result = false;
  62. break;
  63. }
  64. } else if (!(
  65. arrValue === othValue ||
  66. equalFunc(arrValue, othValue, bitmask, customizer, stack)
  67. )) {
  68. result = false;
  69. break;
  70. }
  71. }
  72. stack['delete'](array);
  73. stack['delete'](other);
  74. return result;
  75. }
  76. module.exports = equalArrays;