My objective in software development is to express my intents in a way that is clear and unambiguous.
For this kind of "problems", I will always reach out for the humble map. There's no extra ceremonies (i.e. if/else, switch/case, etc.). It just says "if you give me an X, I'll give you a Y".
const risk_map =
{ PUB: "com.generali.gip.local.hk.domain.RiskPublicLiability"
, SPPI: "com.generali.gip.local.hk.domain.RiskPublicLiability"
, PROD: "com.generali.gip.local.hk.domain.RiskPublicLiability"
, PR: "com.generali.gip.local.hk.domain.RiskPublicLiability"
, DO: "com.generali.gip.local.hk.domain.RiskPublicLiability"
, PD: "com.generali.gip.local.hk.domain.RiskMaterialDamage";
, BI: "com.generali.gip.local.hk.domain.RiskBusinessInterruption"
};
Regardless of your programming background, the "time to get it" is low.
It can indeed lead to duplication but I don't think it comes at the expense of readability or maintenance. (How hard would it be to replace these duplicated strings with a constant for example?)
Now how can we "query" this map? Let's build a high-order function for that:
We say "Give me a map, then give me a key, I'll get you a value":
const get_value = map => key => map[key];
get_value(risk_map)("PUB");
//=> "com.generali.gip.local.hk.domain.RiskPublicLiability"
The get_value
is a high-order function. We're meant to build specialised functions out of it. Let's just do that:
const get_risk = get_value(risk_map);
get_risk("PUB");
//=> "com.generali.gip.local.hk.domain.RiskPublicLiability"
With this we can solve your "problem" quite simply:
const content_risks =
content.risks
? content.risks.map(risk => get_risk(risk.coverageCode))
: null;
I'll leave it as an exercise to combine and adapt this to fit your exact needs.
Hope this helps though.