Currently I'm doing the optional addition using something like this
...(!!providerId && { providerId }),
...(!!practiceId && { practiceId }),
Is there some shorthand logic to replace this logic in a graceful manner like
yield createRemarkRequest.post(PATIENT_REMARK, {
patientId,
?providerId,
?practiceId,
noteTypeCode,
note,
})
CodePudding user response:
What you're doing is fine (assuming you don't need to include 0 or "", etc.; if you do, you'll want something other than a !! check). It relies on the fact there aren't any own, enumerable properties on Boolean objects, but that's okay, there aren't. :-) I've definitely done that in some code, though not frequently.
But it might be clearer just to make it explicit:
const appropriateNameHere = {
patientId,
noteTypeCode,
note,
};
if (providerId) {
appropriateNameHere.providerId = providerId;
}
if (practiceId) {
appropriateNameHere.practiceId = practiceId;
}
yield createRemarkRequest.post(PATIENT_REMARK, appropriateNameHere);
(That also makes debugging a bit easier.)
Or if createRemarkRequest.post ignores undefined property values, you could do:
yield createRemarkRequest.post(PATIENT_REMARK, {
patientId,
providerId: providerId ? providerId : undefined,
practiceId: practiceId ? practiceId : undefined,
noteTypeCode,
note,
});
CodePudding user response:
There is Nullish coalescing operator in JavaScript.
You can call your function like below
yield createRemarkRequest.post(PATIENT_REMARK, {
patientId,
providerId??null, //null or whatever value you want to pass
practiceId??null,
noteTypeCode,
note,
})
