alex alex - 6 months ago 9
Javascript Question

How to do it so the code executes down the function after not passing a condition?

The following function does the following:

1) Check if the object has non-empty categories (keys with a certain name).

2) Check each of the objects inside those categories. If the object has the property

web
and the property is not empty or undefined return
false
.

3) The last bit does the same, but when the property
web
is in the object not in the categories.

hasNoCategories (object) {
for (let key in object) {
const value = object[key]
const isCategory = this.categories.indexOf(key) > -1
if (value.constructor === Array && isCategory && value.length > 0) {
let result
value.map(pano => {
if (pano.web !== undefined && pano.web !== '') {
result = false
}
})
// STUCK HERE
return result
}
if (key === 'web' && value !== '') {
return false
}
}
return true
},


However, when the code sometimes stops in
// STUCK HERE
and never makes it to return
true
at the end.

One workaround is this:

if (pano.web !== undefined && pano.web !== '') {
result = false
} else {
result = true
}


But I'm against having two
return true
, I feel it kinds of muddle the logic (I just want to have one
return true
, the one at the end.)

How to modify the code so the code doesn't get stuck in
// STUCK HERE
and continues until reaching
return true
?

EDIT:

Sample input:

{
"livingroom": [],
"diningroom": [],
"kitchen": [],
"bedroom": [],
"study": [],
"bathroom": [],
"toilet": [],
"garden": [],
"garage": [],
"outdoors": [],
"other": [],
"id": "ZI4hteKxgr",
"name": "Cuiti",
"description": "",
"visible": true,
"user": "",
"floorplan": "",
"shareCode": "http://vrviewer.istaging.co#!/854703",
"date": "2016/5/13",
"isDirty": false
}

Answer

This is example of doing this using a for loop instead of map for the first if statement.

hasNoCategories (object) {
  for (let key in object) {
    const value = object[key]
    const isCategory = this.categories.indexOf(key) > -1
    if (value.constructor === Array && isCategory && value.length > 0) {
      for (let i = 0, len = value.length; i < len; i++) {
        let pano = value[i]
        if (pano.web !== undefined && pano.web !== '') {
          return false
        }
      }
    }
    if (key === 'web' && value !== '') {
      return false
    }
  }
  return true
}

This could probably be done in a cleaner way, though. I think for loops tend to make code look less clean.

Comments