Skip to content

Instantly share code, notes, and snippets.

@its-tayo
Last active August 23, 2023 05:57
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save its-tayo/471b6608f651aeede79b4052e4a4e259 to your computer and use it in GitHub Desktop.
Save its-tayo/471b6608f651aeede79b4052e4a4e259 to your computer and use it in GitHub Desktop.
Faker.js: Generate array of N items
// generator
const generator = (schema, min = 1, max) => {
max = max || min;
return Array.from({
length: faker.random.number({
min,
max,
}),
}).map(() => {
const innerGen = (anySchema) => Object.keys(anySchema).reduce((entity, key) => {
if (
Object.prototype.toString.call(anySchema[key]) === '[object Object]'
) {
entity[key] = innerGen(anySchema[key]);
return entity;
}
entity[key] = faker.fake(anySchema[key]);
return entity;
}, {});
return innerGen(schema);
});
};
// your schema
const clientsSchema = {
id: '{{random.number}}',
name: '{{company.companyName}} {{company.companySuffix}}',
contact: {
address: '{{address.streetAddress}}',
phone: '{{phone.phoneNumber}}',
email: '{{internet.email}}',
},
};
// generate random clients between 2 and 5 units, based on client schema defined above
const data = generator(clientsSchema, 2, 5);
// data looks like this:
[
{
id: '92447',
name: 'Wintheiser Group Group',
contact: {
address: '566 Leonardo Loop',
phone: '025.415.9443 x5894',
email: 'Esta36@gmail.com',
},
},
{
id: '42354',
name: 'Larson Inc and Sons',
contact: {
address: '3089 Waelchi Keys',
phone: '711.874.8437 x58199',
email: 'Lloyd_Shanahan73@hotmail.com}',
},
},
...
];
@kris-luminar
Copy link

This is brilliant!

Couple of things:

  1. faker.random.number is deprecated in favor of faker.datatype.number
  • this matters on line 5 and line 27
  1. How can return integers instead of a string containing them?
  • I'd like 500 instead of '500', for example

@brunoandradebr
Copy link

foo() {
   
   return faker.random.word().split('').map(() => ({
      id: faker.datatype.uuid(),
      type: faker.helpers.arrayElement(['bla', 'ble', 'bli']),
      name: faker.random.word(),
      position: {
         x: faker.random.numeric(3),
         y: faker.random.numeric(3)
      }
   }))
	
}

this way I'm faking an random array of object that I define inside map return. faker.random.word().split('') generates a random array :D

@kris-luminar
Copy link

@brunoandradebr is this a different solution to the same problem or a refinement or something else?

@brunoandradebr
Copy link

Different solution with less code.

@SalahAdDin
Copy link

Thanks man!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment