0
\$\begingroup\$

I have a method that takes as parameter an array of several depth (group) and a name as a string (currentFilterName)

checkFilterValue(group, currentFilterName) {
  group.forEach((element, index) => {
    if (element.children) {
      if (element.name === currentFilterName) {
        this.returnedValue = element.value
      } else {
        this.checkFilterValue(element.children || this.filtersConfig[index + 1], currentFilterName)
      }
    } else {
      if (element.name === currentFilterName) {
        this.returnedValue = element.value
      }
    }
  })
}

The depth levels are the element.children , being the goal is to return the element.value, at each turn if the element has a depth level I first check if element.name === currentFilterName if it is the case I would like returned the element.value if it is not the case I return the method evening with the next element.children if there is otherwise the original tables with the next index this.filtersConfig [index + 1], if the element has no depth I simply check if element.name === currentFilterName and I return to element.value

The problem I have is that the method is a little verbose, how can we simplify it with an elegant writing?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ What other code is in this object's definition? Is it in strict mode? Why do you want to set returnedValue this way? \$\endgroup\$ Dec 11, 2018 at 9:41

1 Answer 1

2
\$\begingroup\$

I think your code has an issue:

this.checkFilterValue(element.children || this.filtersConfig[index + 1], currentFilterName)

The this.filtersConfig[index + 1] is never called as you check element.children first:

if (element.children) {
   ...
}

Your code doesn't need a forEach as a for loop will be better:

checkFilterValue(group, currentFilterName) {
  for (let key in group) {
    const { name, value, children } = group[key]
    if (name === currentFilterName) {
      return value
    }

    if (children) {
        let found = this.checkFilterValue(children, currentFilterName)
        if (found) return found
    }
  }

  return null
}

By using a for loop you are able to directly return the value if found.

Another issue of your code is you missed to reset this.returnedValue doing so you have a bug if you call 2 different searches and the second one doesn't find anything.

Although you didn't share other code, maybe you should do this in another method.

You can see I use the spread operator to make the code much more concise:

const { name, value, children } = group[key]

and get rid of element.something.

Not sure how to handle the part where you call the function with a different set of data, but maybe inside this method is not the right place of doing it.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.