MeSa
MeSa

Reputation: 11

Want to shorten my if statement using Lodash

I am looking to optimize the below piece of code using Lodash. I have looked for solutions online, but could not find anything relevant. Can someone please help?

if (isPage && isPageType === constants.keys.isDisclosureSubmitted) {
    if (form && form.application && typeof form.application.disclosureAccepted !== 'undefined' && form.application.disclosureAccepted !== null && !form.application.disclosureAccepted) {
        return $q.when(response.data.content);
    }
}

Upvotes: 1

Views: 55

Answers (1)

Devin Fields
Devin Fields

Reputation: 2544

if (isPage && isPageType === constants.keys.isDisclosureSubmitted) {
  const discAcc = _.get(form, ['application', 'disclosureAccepted'], true);
  if (!_.isNil(discAcc) && !disAcc) {
     return $q.when(response.data.content);
  }
}

Basically, with _.get, you don't have to worry about checking a property of undefined, since it will just return undefined in that scenario rather than throw an error. _.isNil check is the value is both null or undefined, and then you want to make sure the value is still falsey.

I mean, I'm not sure if lodash "optimizes" in this case, since these function calls will actually slow it down, but it is slightly more readable. Like the comments, I'm not sure exactly why you need to be so specific; you could just use _.get(form, ['application', 'disclosureAccepted']) == false, thought I sway against using unstrict equivalence.

Upvotes: 1

Related Questions