Generate an array of random data
•
Faker is a useful JavaScript library for generating dummy data.
For example, faker.random.words(3)
generates a string containing three random words. But what if you want to generate an array of random words?
Helper function to the rescue.
function makeArray<T>(length: number, generator: () => T): T[] {
return Array.from({ length }, generator)
}
Usage:
// Array containing 20 single word strings
const simple: string[] = makeArray(20, faker.random.word)
// Array containing up to 20 3-word strings
const fancy: string[] = makeArray(faker.random.number(20), () =>
faker.random.words(3),
)
Sign up for my newsletter
A monthly round-up of blog posts, projects, and internet oddments.