UNPKG

2.27 kBMarkdownView Raw
1# unique
2
3```js
4// usage
5chance.unique(chance.state, 5)
6chance.unique(chance.state, 5, { comparator: func })
7```
8
9Provide any function that generates random stuff (usually another **Chance** function) and a number and `unique()` will generate a random array of unique (not repeating) items with a length matching the one you specified.
10
11```js
12chance.unique(chance.state, 5);
13=> ["SC", "WA", "CO", "TX", "ND"]
14```
15
16This is helpful when there are a limited number of options and you want a bunch but want to ensure each is different.
17
18Optionally specify the comparator used to determine whether a generated item is in the list of already generated items. By default the comparator just checks to see if the newly generated item is in the array of already generated items. This works for most simple cases (such as `chance.state()`) but will not work if the generated item is an object (because the `Array.prototype.indexOf()` method will not work on an object since 2 objects will not be strictly equal, `===`, unless they are references to the same object).
19
20```js
21chance.unique(chance.currency, 2, {
22comparator: function(arr, val) {
23return arr.reduce(function(acc, item) {
24return acc || (item.code === val.code);
25}, false);
26}
27});
28=> [{ code: "KYF", name: "Cayman Islands Dollar" }, { code: "CDF", name: "Congo/Kinshasa Franc" }]
29```
30
31You can also specify any arbitrary options in this third argument and they'll be passed along to the method you specify as the first.
32
33For example, let's say you want to retrieve 10 unique integers between 0 and 100. This is easily achievable by specifying `chance.integer` as hte function, 10 as the number to retrieve, and a min/max in the options.
34
35```js
36chance.unique(chance.integer, 10, {min: 0, max: 100});
37=> [78, 49, 7, 87, 59, 89, 84, 62, 60, 63]
38```
39
40Note, there could be cases where it is impossible to generate the unique number. For example, if you choose `chance.state` as shown above as the random function and want say, 55 uniques, **Chance** will throw a RangeError because it is impossible to generate 55 uniques because there are only 51 states in the available pool (50 states plus the District of Columbia).
41
42```js
43chance.unique(chance.state, 55);
44=> RangeError: Chance: num is likely too large for sample set
45```
46
47