intersection.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. var baseIndexOf = require('../internal/baseIndexOf'),
  2. cacheIndexOf = require('../internal/cacheIndexOf'),
  3. createCache = require('../internal/createCache'),
  4. isArrayLike = require('../internal/isArrayLike'),
  5. restParam = require('../function/restParam');
  6. /**
  7. * Creates an array of unique values that are included in all of the provided
  8. * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
  9. * for equality comparisons.
  10. *
  11. * @static
  12. * @memberOf _
  13. * @category Array
  14. * @param {...Array} [arrays] The arrays to inspect.
  15. * @returns {Array} Returns the new array of shared values.
  16. * @example
  17. * _.intersection([1, 2], [4, 2], [2, 1]);
  18. * // => [2]
  19. */
  20. var intersection = restParam(function(arrays) {
  21. var othLength = arrays.length,
  22. othIndex = othLength,
  23. caches = Array(length),
  24. indexOf = baseIndexOf,
  25. isCommon = true,
  26. result = [];
  27. while (othIndex--) {
  28. var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : [];
  29. caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null;
  30. }
  31. var array = arrays[0],
  32. index = -1,
  33. length = array ? array.length : 0,
  34. seen = caches[0];
  35. outer:
  36. while (++index < length) {
  37. value = array[index];
  38. if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) {
  39. var othIndex = othLength;
  40. while (--othIndex) {
  41. var cache = caches[othIndex];
  42. if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) {
  43. continue outer;
  44. }
  45. }
  46. if (seen) {
  47. seen.push(value);
  48. }
  49. result.push(value);
  50. }
  51. }
  52. return result;
  53. });
  54. module.exports = intersection;