index.js 930 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. var filter = require('through2-filter').obj;
  3. var stringify = require("json-stable-stringify-without-jsonify");
  4. var ES6Set;
  5. if (typeof global.Set === 'function') {
  6. ES6Set = global.Set;
  7. } else {
  8. ES6Set = function() {
  9. this.keys = [];
  10. this.has = function(val) {
  11. return this.keys.indexOf(val) !== -1;
  12. },
  13. this.add = function(val) {
  14. this.keys.push(val);
  15. }
  16. }
  17. }
  18. function prop(propName) {
  19. return function (data) {
  20. return data[propName];
  21. };
  22. }
  23. module.exports = unique;
  24. function unique(propName, keyStore) {
  25. keyStore = keyStore || new ES6Set();
  26. var keyfn = stringify;
  27. if (typeof propName === 'string') {
  28. keyfn = prop(propName);
  29. } else if (typeof propName === 'function') {
  30. keyfn = propName;
  31. }
  32. return filter(function (data) {
  33. var key = keyfn(data);
  34. if (keyStore.has(key)) {
  35. return false;
  36. }
  37. keyStore.add(key);
  38. return true;
  39. });
  40. }