How to use chance

Comprehensive chance code examples:

How to use chance.hour:

7
8
9
10
11
12
13
14
15
16
  alpha: true,
  symbols: true,
  length: 8,
  numeric: true,
});
const hour = chance.hour();
const number = chance.natural({ min: 1, max: 15 });
const shortid = require("shortid");
const email = chance.email({ domain: "example.com" });
const address = chance.address({ short_suffix: true });

How to use chance.cc:

71
72
73
74
75
76
77
78
79
80
    break;
case 'city':
    s += chance.city().toCsv(CSV.delimiter);
    break;
case 'ccnumber':
    s += chance.cc().toCsv(CSV.delimiter);
    break;
case 'char': // one character
    s += chance.character();
    break;

How to use chance.postal:

203
204
205
206
207
208
209
210
211
212
case 'pick':
    fld = hdr[k].arg;
    s += chance.pick(fld.split('|')).toCsv(CSV.delimiter);
    break;
case 'postal':
    s += chance.postal().toCsv(CSV.delimiter);
    break;
case 'province':
    s += chance.province().toCsv(CSV.delimiter);
    break;

How to use chance.color:

144
145
146
147
148
149
150
151
152
153
}

const _createAndSetLabel = (label) => {
  return labelService.create({
    label: label.label,
    color: label.color || chance.color(),
    owner: doc.owner
  })
    .then((l) => {
      // Add new label to the cache and the document

How to use chance.close:

41
42
43
44
45
46
47
48


let [,, action, name1, name2, name3] = process.argv;
if (action === 'add') {
    createEventsForApplication('TestOne', name1, name2, name3);
} else if (action === 'rm') {
    db.connect((c) => clearAllCollections(() => c.close()));
}

How to use chance.js:

206
207
208
209
210
211
212
213
214
215
  "pattern": "yes|no|maybe|i don't know"
}
```
([demo »](http://json-schema-faker.js.org/#gist/8ee282679da5a31cd7edc4cf35f37081))

### Advanced usage of faker.js and Chance.js

In following inline code examples the `faker` and `chance` variables are assumed to be created with, respectively:

```javascript

How to use chance.animal:

44
45
46
47
48
49
50
51
52
53
function generateMovies(moviesCount, listsCount, reviewsCount) {
  const movies = [];
  for (let i = 0; i < moviesCount; i++) {
    let title =
      "The " +
      chance.animal() +
      " in " +
      chance.city() +
      " " +
      chance.integer({ min: 1, max: 100 });

How to use chance.default:

12
13
14
15
16
17
18
19
20
21
};
Object.defineProperty(exports, "__esModule", { value: true });
const client_1 = require("@prisma/client");
const chance_1 = __importDefault(require("chance"));
const prisma = new client_1.PrismaClient();
const chance = new chance_1.default();
function seed() {
    return __awaiter(this, void 0, void 0, function* () {
        const user = {
            id: 1,

How to use chance.capitalize:

14
15
16
17
18
19
20
21
22
23
}
exports.pick = exports.random
exports.firstName = function () { return ch.first() }
exports.lastName = function () { return ch.last() }
exports.gender = function () { return ch.gender() }
exports.company = function () { return ch.capitalize(ch.word({syllables: 3})) }
exports.email = function () { return ch.email() }
exports.phone = function () { return ch.phone() }
exports.address = function () { return ch.address() }
exports.street = function () { return ch.street() }

How to use chance.avatar:

192
193
194
195
196
197
198
199
200
201
/**
 * Return a random avatar.
 * @param {string} fileExtension
 */
avatar(fileExtension = 'jpg') {
  return chance.avatar({protocol: 'https', fileExtension});
},

/**
 * Return a random image.

How to use chance.shuffle:

2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
        list.sort(js_utils.sort_compare_by(item =>
            (['DECOMMISSIONED', 'DECOMMISSIONING'].includes(item.storage_nodes_mode) ? 0 : 1),
            options.order
        ));
    } else if (options.sort === 'shuffle') {
        chance.shuffle(list);
    }
}

_paginate_nodes_list(list, options) {

How to use chance.company:

4
5
6
7
8
9
10
11
12
13
14


module.exports = async({ jobCount = 5, noteCount = 60, resumeCount = 10 } = {}) => {
  const jobsArray = [...Array(jobCount)].map(() => ({
    title: chance.profession(),
    author: chance.phone(),
    company: chance.company(),
    active: chance.bool(),
    jobDescriptionText: chance.word(),
    jobUrl: chance.word(),
    salary: chance.word(),

How to use chance.dollar:

131
132
133
134
135
136
137
138
139
140
            pool: '0123456789'
        });
    }
    break;
case 'dollar':
    s += chance.dollar().toCsv(CSV.delimiter);
    break;
case 'domain':
    s += chance.domain().toCsv(CSV.delimiter);
    break;

How to use chance.radio:

21
22
23
24
25
26
27
28
29
30
const lastNames = ['Doggo', 'Pupster', 'Smith', 'Wolf']
const puppies = longArray(100).map(() => {
  const first = chance.first()
  const last = lastNames[Math.floor(Math.random() * 4)]
  const ssn = chance.ssn()
  const callsign = chance.radio()
  const age = Math.floor(chance.age() / 7)
  const insertQuery = 
    `INSERT INTO Puppy (
      first_name, last_name, ssn, callsign, age

How to use chance.hash:

5
6
7
8
9
10
11
12
13
14
var oids = [ 3200, 3201, 3203, 3300, 3301, 3302, 3303, 3304, 
             3305, 3306, 3308, 3310, 3311, 3312, 3313, 3314,
             3315 ];

function Device() {
    this.clientId = chance.hash({ length: 8 });
    this.lifetime = chance.integer({ min: 600, max: 86400 });
    this.joinTime = chance.timestamp();
    this.ip = chance.ip();
    this.mac = chance.mac_address();

How to use chance.student:

19
20
21
22
23
24
25
26
27
28
* 
* Note the `options = {}` inside each of the function arguments. Those are called "overrides".
* Consider the student generator. It returns an object containing a random id, name, and email.
* So a sample returned object when calling:
* 
* random.student();
* 
* might look like:
* 
* { id: '76638115', name: 'Derek', email: 'lubmo@ninrezgec.vi' }

How to use chance.rpg:

19
20
21
22
23
24
25
26
27
28
//ability score focused on for blurb display
const [abilityOnFocus, setAbilityOnFocus] = useState<string>(!props.pageData.hasRolledScores ? '' : 'str')

const rollAbilityScores = () => {

    const randAbilityScore = () =>  chance.rpg(`3d6`, {sum: true});

    let newScores: AbilityScores = {
        str: randAbilityScore(),
        dex: randAbilityScore(),

How to use chance.profession:

2
3
4
5
6
7
8
9
10
11
12
const Note = require('../../lib/models/Note');
const Asset = require('../../lib/models/Asset');


module.exports = async({ jobCount = 5, noteCount = 60, resumeCount = 10 } = {}) => {
  const jobsArray = [...Array(jobCount)].map(() => ({
    title: chance.profession(),
    author: chance.phone(),
    company: chance.company(),
    active: chance.bool(),
    jobDescriptionText: chance.word(),

How to use chance.timezone:

10
11
12
13
14
15
16
17
18
19
ip: {
  range: [1100616832, 1100616959],
  country: 'US',
  region: chance.state(),
  eu: '0',
  timezone: chance.timezone().utc,
  city: chance.city(),
  ll: [chance.latitude(), chance.longitude()],
  metro: Math.floor(Math.random() * Math.floor(10000000)),
  area: Math.floor(Math.random() * Math.floor(10000))

How to use chance.timestamp:

237
238
239
240
241
242
243
244
245
246
    } else {
        s += chance.string().toCsv(CSV.delimiter);
    }
    break;
case 'timestamp':
    s += chance.timestamp();
    break;
case 'word':
    s += chance.word().toCsv(CSV.delimiter);
    break;

How to use chance.ssn:

21
22
23
24
25
26
27
28
29
    last: chance.last(),
    age: chance.age(),
    birthday: chance.birthday({string: true, american: true}),
    gender: gender,
    zip: chance.zip({plusfour: true}),
    ssnFour: chance.ssn({ ssnFour: true }),
    phone: chance.phone(),
    email: chance.email()
}

How to use chance.coordinates:

5
6
7
8
9
10
11
12
13
14
15


/**
 * $coordinates operator, returns a 2-element array of [longitude, latitude]
 * coordinates.
 *
 * Note: this operator overwrites the chance.coordinates() operator, as it
 * returns a string in "latitude, longitude" format, which is not compatible
 * to MongoDBs geolocation indexes.
 *
 * @example Creates random coordinate pairs

How to use chance.year:

14
15
16
17
18
19
20
21
22
23
24
25


// Generate fake information
let firstname = faker.name.firstName();
let surname = faker.name.lastName();
let gender = 1; // 1: Female, 2: Male
let year = chance.year({ min: 1996, max: 1998 });
let dob = chance.birthday({ year: year });


nightmare
    .useragent(ua)

How to use chance.url:

8
9
10
11
12
13
14
15
16
17
const ofAWebhookObject = ['id', 'url', 'secret', 'labels', 'events', 'active', 'cdate', 'mdate', '_links']

module.exports = function () {
  this.When(/^I create the following webhook:$/, function (attrs, callback) {
    const webhook = {
      url: chance.url()
    }
    attrs.raw().forEach(function (attr) {
      const prop = attr[0]
      const value = attr[1]

How to use chance.province:

50
51
52
53
54
55
56
57
58
59
// address
person.addresses = [{
  preferred: true,
  address1: Chance.address(),
  cityVillage: Chance.city(),
  stateProvince: Chance.province(),
  country: Chance.country({
    full: true,
  }),
  postalCode: Chance.zip(),

How to use chance.street:

173
174
175
176
177
178
179
180
181
182
 */
street(cn = false) {
  if (cn) {
    return chance.pickone(chinese.area) + chance.pickset(chinese.words, rand(2, 3)).join('')+'街';
  }
  return chance.street();
},

/**
 * Return a random address.

How to use chance.n:

58
59
60
61
62
63
64
65
66
67
68
    max: 20
  });
  return Story.build({
    author_id: user.id,
    title: randTitle(),
    paragraphs: chance.n(chance.paragraph, numPars)
  });
}


function generateUsers () {

How to use chance.mac_address:

168
169
170
171
172
173
174
175
176
177
async.series([
  function (cb) {
    test.app.post('/data/ip_data')
      .set('Content-Type', 'application/json')
      .send(data = {
        'macaddr_data': chance.mac_address().toLowerCase(),
        'ip_data': chance.ip() + '/32',
        'host_data': chance.ip()
      })
      .expect(200, [data])

How to use chance.d20:

101
102
103
104
105
106
107
108
109
110
    price: chance.floating({
        fixed: 2,
        max: 1000,
        min: 0
    }),
    downloads: chance.d20(),
    cap: 2000,
    reviews: review,
    url: url
};

How to use chance.unique:

9
10
11
12
13
14
15
16
17
18
const Quote = require('APP/db/models/quote')
const Recording = require('APP/db/models/recording');

const numUsers = 196; // + 4 hardcoded real users = 200 total users
const numRecordings = 500;
const emails = chance.unique(chance.email, numUsers);
const questionsJSON = require('./seedData/questionsSeed');
const quotesJSON = require('./seedData/quotesSeed');
const recordingsJSON = require('./seedData/recordingsSeed');
const realUsers = require('./seedData/usersSeed');