_baseIntersection.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. var SetCache = require('./_SetCache'),
  2. arrayIncludes = require('./_arrayIncludes'),
  3. arrayIncludesWith = require('./_arrayIncludesWith'),
  4. arrayMap = require('./_arrayMap'),
  5. baseUnary = require('./_baseUnary'),
  6. cacheHas = require('./_cacheHas');
  7. /* Built-in method references for those with the same name as other `lodash` methods. */
  8. var nativeMin = Math.min;
  9. /**
  10. * The base implementation of methods like `_.intersection`, without support
  11. * for iteratee shorthands, that accepts an array of arrays to inspect.
  12. *
  13. * @private
  14. * @param {Array} arrays The arrays to inspect.
  15. * @param {Function} [iteratee] The iteratee invoked per element.
  16. * @param {Function} [comparator] The comparator invoked per element.
  17. * @returns {Array} Returns the new array of shared values.
  18. */
  19. function baseIntersection(arrays, iteratee, comparator) {
  20. var includes = comparator ? arrayIncludesWith : arrayIncludes,
  21. length = arrays[0].length,
  22. othLength = arrays.length,
  23. othIndex = othLength,
  24. caches = Array(othLength),
  25. maxLength = Infinity,
  26. result = [];
  27. while (othIndex--) {
  28. var array = arrays[othIndex];
  29. if (othIndex && iteratee) {
  30. array = arrayMap(array, baseUnary(iteratee));
  31. }
  32. maxLength = nativeMin(array.length, maxLength);
  33. caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
  34. ? new SetCache(othIndex && array)
  35. : undefined;
  36. }
  37. array = arrays[0];
  38. var index = -1,
  39. seen = caches[0];
  40. outer:
  41. while (++index < length && result.length < maxLength) {
  42. var value = array[index],
  43. computed = iteratee ? iteratee(value) : value;
  44. value = (comparator || value !== 0) ? value : 0;
  45. if (!(seen
  46. ? cacheHas(seen, computed)
  47. : includes(result, computed, comparator)
  48. )) {
  49. othIndex = othLength;
  50. while (--othIndex) {
  51. var cache = caches[othIndex];
  52. if (!(cache
  53. ? cacheHas(cache, computed)
  54. : includes(arrays[othIndex], computed, comparator))
  55. ) {
  56. continue outer;
  57. }
  58. }
  59. if (seen) {
  60. seen.push(computed);
  61. }
  62. result.push(value);
  63. }
  64. }
  65. return result;
  66. }
  67. module.exports = baseIntersection;