When i rewriting my old code, i had a problem i don’t know to to optimize this code in past i use switch,but now i know about Object literals, my code:
switch(true) {
case data.rep <= -30:
reputation_text = this.language.pf.reputation.satan;
break;
case data.rep >= -10 && data.rep <= -5:
reputation_text = this.language.pf.reputation.devil;
break;
//other....
case data.rep >= 30:
reputation_text = this.language.pf.reputation.angel;
break;
}
How i can replace him with object literals?
Advertisement
Answer
You can write the cases as object literals and iterate over them:
const { reputations } = this.language.pf;
type MapEntry = { min: number; max: number; value: keyof typeof reputations };
const mapTable: MapEntry[] = [
{ min: Number.MIN_VALUE, max: -30,
value: "satan" },
{ min: -10, max: -5,
value: "devil" },
// ...
{ min: 30, max: Number.MAX_VALUE,
value: "angel" },
];
for (const entry of mapTable) {
if (Data.rep >= entry.min && Data.rep <= entry.max) {
reputation_text = reputations[entry.value];
break;
}
}