Last active
August 23, 2023 05:57
-
-
Save its-tayo/471b6608f651aeede79b4052e4a4e259 to your computer and use it in GitHub Desktop.
Faker.js: Generate array of N items
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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}', | |
}, | |
}, | |
... | |
]; |
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
@brunoandradebr is this a different solution to the same problem or a refinement or something else?
Different solution with less code.
Thanks man!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is brilliant!
Couple of things:
faker.datatype.number