_baseDifference.js 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. /** Used as the size to enable large array optimizations. */
  8. var LARGE_ARRAY_SIZE = 200;
  9. /**
  10. * The base implementation of methods like `_.difference` without support
  11. * for excluding multiple arrays or iteratee shorthands.
  12. *
  13. * @private
  14. * @param {Array} array The array to inspect.
  15. * @param {Array} values The values to exclude.
  16. * @param {Function} [iteratee] The iteratee invoked per element.
  17. * @param {Function} [comparator] The comparator invoked per element.
  18. * @returns {Array} Returns the new array of filtered values.
  19. */
  20. function baseDifference(array, values, iteratee, comparator) {
  21. var index = -1,
  22. includes = arrayIncludes,
  23. isCommon = true,
  24. length = array.length,
  25. result = [],
  26. valuesLength = values.length;
  27. if (!length) {
  28. return result;
  29. }
  30. if (iteratee) {
  31. values = arrayMap(values, baseUnary(iteratee));
  32. }
  33. if (comparator) {
  34. includes = arrayIncludesWith;
  35. isCommon = false;
  36. }
  37. else if (values.length >= LARGE_ARRAY_SIZE) {
  38. includes = cacheHas;
  39. isCommon = false;
  40. values = new SetCache(values);
  41. }
  42. outer:
  43. while (++index < length) {
  44. var value = array[index],
  45. computed = iteratee == null ? value : iteratee(value);
  46. value = (comparator || value !== 0) ? value : 0;
  47. if (isCommon && computed === computed) {
  48. var valuesIndex = valuesLength;
  49. while (valuesIndex--) {
  50. if (values[valuesIndex] === computed) {
  51. continue outer;
  52. }
  53. }
  54. result.push(value);
  55. }
  56. else if (!includes(values, computed, comparator)) {
  57. result.push(value);
  58. }
  59. }
  60. return result;
  61. }
  62. module.exports = baseDifference;