timmyLtus
timmyLtus

Reputation: 274

Vue: Refactoring a computed property

I have the following computed property that works as expected. I want it to return true if any of the 3 data properties are empty strings and want it return true if any of the strings are "n/a":

             appNamesInvalid() {
                if (!this.preferredAppName1 || !this.preferredAppName2 || !this.preferredAppName3) {
                    return true;
                }
                if (this.preferredAppName1.toLowerCase().includes('n/a') || this.preferredAppName2.toLowerCase().includes('n/a') || this.preferredAppName3.toLowerCase().includes('n/a')) {
                    return true;
                }
                return false;
            },

I had originally tried to do this but this wasn't working as expected and I can't tell why:

   appNamesInvalid() {
        let appNames = [this.preferredAppName1, this.preferredAppName2, this.preferredAppName3];
        appNames.forEach(appName => {
            if (appName == "" || appName.toLowerCase().includes("n/a")) { 
               return true;
            }
        }
        return false;
    },

Is there a cleaner way of refactoring the working code in the first block?

Upvotes: 1

Views: 165

Answers (1)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38847

Try using Array.prototype.some to return a boolean based on your specific criteria:

appNamesInvalid() {
  let appNames = [this.preferredAppName1, this.preferredAppName2, this.preferredAppName3];
  return appNames.some(appName => {
      return appName === "" || appName.toLowerCase().includes("n/a");
  }
},

That would return true if for any aoo either appName === "" or appName.toLowerCase().includes("n/a") is true.

Hopefully that helps!

Upvotes: 3

Related Questions