baseUniq.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var baseIndexOf = require('./baseIndexOf'),
  2. cacheIndexOf = require('./cacheIndexOf'),
  3. createCache = require('./createCache');
  4. /** Used as the size to enable large array optimizations. */
  5. var LARGE_ARRAY_SIZE = 200;
  6. /**
  7. * The base implementation of `_.uniq` without support for callback shorthands
  8. * and `this` binding.
  9. *
  10. * @private
  11. * @param {Array} array The array to inspect.
  12. * @param {Function} [iteratee] The function invoked per iteration.
  13. * @returns {Array} Returns the new duplicate free array.
  14. */
  15. function baseUniq(array, iteratee) {
  16. var index = -1,
  17. indexOf = baseIndexOf,
  18. length = array.length,
  19. isCommon = true,
  20. isLarge = isCommon && length >= LARGE_ARRAY_SIZE,
  21. seen = isLarge ? createCache() : null,
  22. result = [];
  23. if (seen) {
  24. indexOf = cacheIndexOf;
  25. isCommon = false;
  26. } else {
  27. isLarge = false;
  28. seen = iteratee ? [] : result;
  29. }
  30. outer:
  31. while (++index < length) {
  32. var value = array[index],
  33. computed = iteratee ? iteratee(value, index, array) : value;
  34. if (isCommon && value === value) {
  35. var seenIndex = seen.length;
  36. while (seenIndex--) {
  37. if (seen[seenIndex] === computed) {
  38. continue outer;
  39. }
  40. }
  41. if (iteratee) {
  42. seen.push(computed);
  43. }
  44. result.push(value);
  45. }
  46. else if (indexOf(seen, computed, 0) < 0) {
  47. if (iteratee || isLarge) {
  48. seen.push(computed);
  49. }
  50. result.push(value);
  51. }
  52. }
  53. return result;
  54. }
  55. module.exports = baseUniq;