Reputation:
I am new to javascript so sorry I don't know very much. I have the following and I would like to make it simpler. Any suggestion would be appreciated.
if (entity == "house") {
primaryKey = store.getItem('accountID') + "02" + "00";
table = "Content";
}
if (entity == "street") {
primaryKey = store.getItem('accountID') + "0000";
table = "Content";
}
if (entity == "city") {
var primaryKey = store.getItem('categoryID');
table = "Reference";
}
if (entity == "location") {
primaryKey = "0001" + store.getItem('examID');
table = "Content";
}
Upvotes: 0
Views: 93
Reputation: 707168
You could do it with a table driven approach and no repeated code (DRY) like this:
var lookupInfo = {
house: {id: "accountID", prefix, "", suffix: "0200", table: "Content"},
street: {id: "accountID", prefix: "", suffix: "0000", table: "Content"},
city: {id: "categoryID", prefix: "", suffix: "", table: "Reference"},
location: {id: "examID", prefix: "0001", suffix: "", table: "Content"}
};
var primaryKey, data = lookupInfo[entity];
if (data) {
primaryKey = data.prefix + store.getItem(data.id) + data.suffix;
table = data.table;
}
Besides minimizing the code and not repeating any code, it's also easy to add more options to the table without writing any additional code.
Or, the data table can be made a little more compact, though not quite as elegant (from a pure programming point of view because of the hard coded constants) this way:
var lookupInfo = {
house: ["accountID", "", "0200", "Content"],
street: ["accountID", "", "0000", "Content"],
city: ["categoryID", "", "", "Reference"],
location: ["examID", "0001", "", "Content"]
};
var primaryKey, data = lookupInfo[entity];
if (data) {
primaryKey = data[1] + store.getItem(data[0]) + data[2];
table = data[3];
}
Either way, you get the idea of using a lookup table for the entity and then a table driven approach for the different values for each entity.
Upvotes: 6
Reputation: 4467
You can use a switch statement. https://developer.mozilla.org/en/JavaScript/Reference/Statements/switch
var primaryKey;
var table = "Content";
switch (entity) {
case "house":
primaryKey = store.getItem('accountID') + "0200";
break;
case "street":
primaryKey = store.getItem('accountID') + "0000";
break;
case "city":
primaryKey = store.getItem('categoryID');
table = "Reference";
break;
case "location":
primaryKey = "0001" + store.getItem('examID');
break;
default:
// do nothing
}
This is still verbose, but easier to read.
Upvotes: 2