Ok, the title should be your warning. I'm only posting this because it is Sunday night and I'm bored. I'm working on a demo for my jQuery video (did I mention I'm working on a jQuery video?) that mimics a typical car dealership inventory search. As we just upgraded our car I'm pretty familiar with these. The demo will focus on building the UI to create a search engine that can filter cars by model, trim, color, price, and features. In order to actually have something to search against, I wrote a script that creates an inventory of cars. Here is that script. Enjoy.
/**
* Returns a random integer between min and max
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/*
A utility to create my car data.
We have models
Models have trims (which they all share)
cars have a color
and an array of features from a list of possible ones
*/
var models = ["Alpha", "Beta", "Gamma", "Delta", "Epsilon"];
var trims = ["XT", "XTE", "Super", "Ultimate"];
var colors = ["Red", "Blue", "Silver", "Gold", "Black", "White"];
var features = ["Air Conditioning", "Cruise Control", "Backup Camera", "Power Steering", "Internet", "Sat Radio", "4WD", "Moon Roof"];
var inventory = [];
/*
Ok, loop over each model. Each model will have 5-20 (rnd) of each trim.
Each car will have a random color.
Each car will have a random chance of having a feature with higher trims having a better chance of having it.
Each car will have a price btn 20K-40K with each level of trim adding +10k to make them, normally, higher
*/
for(var i=0; i < models.length; i++) {
var model = models[i];
for(var k=0; k < trims.length; k++) {
var trim = trims[k];
var numberToAdd = getRandomInt(8, 23);
console.log("Going to make "+numberToAdd+" "+model+" "+trim);
for(var j=0; j<numberToAdd; j++) {
var car = {
model:model,
trim:trim
};
car.color = colors[getRandomInt(0, colors.length-1)];
car.price = getRandomInt(20000, 40000) + (k*10000);
car.features = [];
for(var z=0; z<features.length; z++) {
if(getRandomInt(1,10) + k > 6) {
car.features.push(features[z]);
car.price += (car.features.length+1)*1000;
}
}
inventory.push(car);
}
}
}
//so i can see it
console.table(inventory);
//so i can copy it
console.log(JSON.stringify(inventory));
In case you're curious, I'm going to write a simple module that wraps calls to this data so that I don't have to use an application server to serve it up.