1 |
|
2 | var unique = {};
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | var found = {};
|
9 |
|
10 |
|
11 |
|
12 | var exclude = [];
|
13 |
|
14 |
|
15 | var currentIterations = 0;
|
16 |
|
17 |
|
18 |
|
19 | var defaultCompare = function(obj, key) {
|
20 | if (typeof obj[key] === 'undefined') {
|
21 | return -1;
|
22 | }
|
23 | return 0;
|
24 | };
|
25 |
|
26 |
|
27 | unique.errorMessage = function (now, code, opts) {
|
28 | console.error('error', code);
|
29 | console.log('found', Object.keys(found).length, 'unique entries before throwing error. \nretried:', currentIterations, '\ntotal time:', now - opts.startTime, 'ms');
|
30 | throw new Error(code + ' for uniqueness check \n\nMay not be able to generate any more unique values with current settings. \nTry adjusting maxTime or maxRetries parameters for faker.unique()')
|
31 | };
|
32 |
|
33 | unique.exec = function (method, args, opts) {
|
34 |
|
35 |
|
36 | var now = new Date().getTime();
|
37 |
|
38 | opts = opts || {};
|
39 | opts.maxTime = opts.maxTime || 3;
|
40 | opts.maxRetries = opts.maxRetries || 50;
|
41 | opts.exclude = opts.exclude || exclude;
|
42 | opts.compare = opts.compare || defaultCompare;
|
43 |
|
44 | if (typeof opts.currentIterations !== 'number') {
|
45 | opts.currentIterations = 0;
|
46 | }
|
47 |
|
48 | if (typeof opts.startTime === 'undefined') {
|
49 | opts.startTime = new Date().getTime();
|
50 | }
|
51 |
|
52 | var startTime = opts.startTime;
|
53 |
|
54 |
|
55 | if (typeof opts.exclude === 'string') {
|
56 | opts.exclude = [opts.exclude];
|
57 | }
|
58 |
|
59 | if (opts.currentIterations > 0) {
|
60 |
|
61 | }
|
62 |
|
63 |
|
64 | if (now - startTime >= opts.maxTime) {
|
65 | return unique.errorMessage(now, 'Exceeded maxTime:' + opts.maxTime, opts);
|
66 | }
|
67 |
|
68 | if (opts.currentIterations >= opts.maxRetries) {
|
69 | return unique.errorMessage(now, 'Exceeded maxRetries:' + opts.maxRetries, opts);
|
70 | }
|
71 |
|
72 |
|
73 | var result = method.apply(this, args);
|
74 |
|
75 |
|
76 | if (opts.compare(found, result) === -1 && opts.exclude.indexOf(result) === -1) {
|
77 | found[result] = result;
|
78 | opts.currentIterations = 0;
|
79 | return result;
|
80 | } else {
|
81 |
|
82 | opts.currentIterations++;
|
83 | return unique.exec(method, args, opts);
|
84 | }
|
85 | };
|
86 |
|
87 | module.exports = unique;
|