Sagiliste
Sagiliste

Reputation: 27

How to refactor a JavaScript function that is used twice

I have these two conditions

if (civility.labelKey === lady) {
  const contactType = this.contactTypes.find((type) => type.label_key === madam)
  this.onSelect({
    $event: { contactType }
  })
  this.contact.greetings = civility
} else {
  const contactType = this.contactTypes.find((type) => type.label_key === civility.labelKey)
  this.onSelect({
    $event: { contactType }
  })
}

I would like to factorize (unify) this code :

this.onSelect({
    $event: { contactType }
  })

Who repeats twice, do you have a solution ?

Upvotes: 0

Views: 64

Answers (1)

Md Hasan Ibrahim
Md Hasan Ibrahim

Reputation: 1898

You can extract a function like this:

function bindOnSelect(component, contactType){
    component.onSelect({
    $event: { contactType }
  })
}

And then call that function:

if (civility.labelKey === lady) {
      const contactType = this.contactTypes.find((type) => type.label_key === madam)
      bindOnSelect(this, contactType);
      this.contact.greetings = civility
    } else {
      const contactType = this.contactTypes.find((type) => type.label_key === civility.labelKey)
      bindOnSelect(this, contactType);
    }

Upvotes: 1

Related Questions