No Description

uniq.js 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. var isBoolean = require('./isBoolean.js');
  2. var _cb = require('./_cb.js');
  3. var _getLength = require('./_getLength.js');
  4. var contains = require('./contains.js');
  5. // Produce a duplicate-free version of the array. If the array has already
  6. // been sorted, you have the option of using a faster algorithm.
  7. // The faster algorithm will not work with an iteratee if the iteratee
  8. // is not a one-to-one function, so providing an iteratee will disable
  9. // the faster algorithm.
  10. function uniq(array, isSorted, iteratee, context) {
  11. if (!isBoolean(isSorted)) {
  12. context = iteratee;
  13. iteratee = isSorted;
  14. isSorted = false;
  15. }
  16. if (iteratee != null) iteratee = _cb(iteratee, context);
  17. var result = [];
  18. var seen = [];
  19. for (var i = 0, length = _getLength(array); i < length; i++) {
  20. var value = array[i],
  21. computed = iteratee ? iteratee(value, i, array) : value;
  22. if (isSorted && !iteratee) {
  23. if (!i || seen !== computed) result.push(value);
  24. seen = computed;
  25. } else if (iteratee) {
  26. if (!contains(seen, computed)) {
  27. seen.push(computed);
  28. result.push(value);
  29. }
  30. } else if (!contains(result, value)) {
  31. result.push(value);
  32. }
  33. }
  34. return result;
  35. }
  36. module.exports = uniq;