Last active
October 14, 2019 07:45
-
-
Save fergiemcdowall/66c93a2edc994070a14564e36014d5a9 to your computer and use it in GitHub Desktop.
Generate a randomised JSON array of cars
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
// randomise function | |
const random = (...list) => list[Math.floor(Math.random() * list.length)] | |
// create random numbers within a range | |
const getRandomInt = (min, max) => { | |
min = Math.ceil(min); | |
max = Math.floor(max); | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
// display function | |
const generate = (length, template) => console.log( | |
JSON.stringify( | |
[...Array(length)].map(template) | |
, null, 2) | |
) | |
// Iteration function that generates every item | |
const template = (item, i) => ({ | |
_id: i, | |
make: random('Volvo', 'BMW', 'Tesla'), | |
colour: random('Red', 'Blue', 'Black', 'White', 'Silver'), | |
year: getRandomInt(2000, 2019), | |
price: getRandomInt(30000, 100000), | |
// We can choose the model based on the make | |
get model() { | |
switch (this.make) { | |
case 'BMW': return random('3-series', '5-series') | |
case 'Tesla': return random('3', 'S', 'X') | |
case 'Volvo': return random('XC60', 'XC90') | |
} | |
}, | |
// We can choose the drivetrain based on the make | |
get drivetrain() { | |
switch (this.make) { | |
case 'Tesla': return 'Electric' | |
default: return random('Hybrid', 'Diesel', 'Petrol') | |
} | |
} | |
}) | |
// make 10 random cars | |
generate(10, template) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment