uniq.js 910 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "use strict"
  2. function unique_pred(list, compare) {
  3. var ptr = 1
  4. , len = list.length
  5. , a=list[0], b=list[0]
  6. for(var i=1; i<len; ++i) {
  7. b = a
  8. a = list[i]
  9. if(compare(a, b)) {
  10. if(i === ptr) {
  11. ptr++
  12. continue
  13. }
  14. list[ptr++] = a
  15. }
  16. }
  17. list.length = ptr
  18. return list
  19. }
  20. function unique_eq(list) {
  21. var ptr = 1
  22. , len = list.length
  23. , a=list[0], b = list[0]
  24. for(var i=1; i<len; ++i, b=a) {
  25. b = a
  26. a = list[i]
  27. if(a !== b) {
  28. if(i === ptr) {
  29. ptr++
  30. continue
  31. }
  32. list[ptr++] = a
  33. }
  34. }
  35. list.length = ptr
  36. return list
  37. }
  38. function unique(list, compare, sorted) {
  39. if(list.length === 0) {
  40. return list
  41. }
  42. if(compare) {
  43. if(!sorted) {
  44. list.sort(compare)
  45. }
  46. return unique_pred(list, compare)
  47. }
  48. if(!sorted) {
  49. list.sort()
  50. }
  51. return unique_eq(list)
  52. }
  53. module.exports = unique