No Description

index.js 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. // there's 3 implementations written in increasing order of efficiency
  3. // 1 - no Set type is defined
  4. function uniqNoSet(arr) {
  5. var ret = [];
  6. for (var i = 0; i < arr.length; i++) {
  7. if (ret.indexOf(arr[i]) === -1) {
  8. ret.push(arr[i]);
  9. }
  10. }
  11. return ret;
  12. }
  13. // 2 - a simple Set type is defined
  14. function uniqSet(arr) {
  15. var seen = new Set();
  16. return arr.filter(function (el) {
  17. if (!seen.has(el)) {
  18. seen.add(el);
  19. return true;
  20. }
  21. return false;
  22. });
  23. }
  24. // 3 - a standard Set type is defined and it has a forEach method
  25. function uniqSetWithForEach(arr) {
  26. var ret = [];
  27. (new Set(arr)).forEach(function (el) {
  28. ret.push(el);
  29. });
  30. return ret;
  31. }
  32. // V8 currently has a broken implementation
  33. // https://github.com/joyent/node/issues/8449
  34. function doesForEachActuallyWork() {
  35. var ret = false;
  36. (new Set([true])).forEach(function (el) {
  37. ret = el;
  38. });
  39. return ret === true;
  40. }
  41. if ('Set' in global) {
  42. if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) {
  43. module.exports = uniqSetWithForEach;
  44. } else {
  45. module.exports = uniqSet;
  46. }
  47. } else {
  48. module.exports = uniqNoSet;
  49. }