Given an object that may be null and may have the following properties:
{
templateId: "template1",
templates: {
template1: "hello"
}
}
How would you get the template in a failsafe way? (templateId might not be defined, or the template it reffers might be undefined)
I use ramda and was trying to adapt my naive version of the code to use something like a Maybe adt to avoid explicit null/undefined checks.
I'm failing to come up with an elegant and clean solution.
naive ramda version:
const getTemplate = obj => {
const templateId = obj && prop("templateId", obj);
const template = templateId != null && path(["template", templateId], obj);
return template;
}
this does work but I would like to avoid null checks, as my code has a lot more going on and it would be really nice to become cleaner
Edit I get from severall answers that the best is to ensure clean data first. That's not allways possible though. I also came up with this, which I do like.
const Empty=Symbol("Empty");
const p = R.propOr(Empty);
const getTemplate = R.converge(p,[p("templateId"), p("templates")]);
Would like to get feedback regarding how clean and how readable it is (and if there are edge cases that would wreck it)