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