1

I have a functions which accepts browser types as arrays in an object as argument. I want to return an error message for whether user wanted any browser or not. For this I used a variable named allTypeNumber. I used for returning error in the code below.

I want to check the length of every array and if they're all 0, I know that no browser has been requested, but confused how to do that without using a variable.

async retrievePartners (capabilities) {
    const appropriatePartners = { chrome: [], firefox: [], safari: [], ie: [] }
    const partners = await this.getAllPartners()
    let allTypeNumber = 0
    // first check if there is available appropriate Partners
    Object.keys(capabilities.type).forEach(key => {
      let typeNumber = parseInt(capabilities.type[key])
      allTypeNumber = allTypeNumber + typeNumber
      for (let i = 0; i < typeNumber; i++) {
        partners.forEach((partner, i) => {
          if (
            key === partner.value.type &&
            partner.value.isAvailable &&
            appropriatePartners[key].length < typeNumber
          ) {
            appropriatePartners[key].push(partner)
          }
        })

        if (appropriatePartners[key].length < typeNumber) {
          throw new Error(
            'Sorry there are no appropriate Partners for this session'
          )
        }
      }
    })

    if (allTypeNumber === 0) {
      throw new Error('Please mention at least 1 type of browser !')

and I call it like with this parameter

const capabilities = { type: { chrome: 1 } }
2
  • 1
    To be sure about what you are asking for; you want to check if chrome/firefox/safari/ie arrays in appropriatePartners are all empty? Commented Apr 18, 2018 at 13:45
  • Please avoid phrases like "More elegant solution needed". Rather point out what you need as hard requirements. Do you want concise code? Super performant code? What is irking you about your current approach? I have rm the phrase out of your question. Commented Apr 18, 2018 at 14:01

1 Answer 1

2

A clean way to check if every value of an array is something, is to use every() (or its inverse, some()). every() will loop through each element in an array and continue as long as it keeps getting a truthy value returned. some() will keep going as long as it keeps getting a falsey. They both return either true or false based on their last return value.

Or, if you need a count (versus just knowing if there is at least one) you can use reduce() to create a sum. reduce() loops through an array with an accumulator and is good for creating singular values from an array of data.

Also, if you need to get the values from an object, using either Object.entries() or Object.values() can be cleaner than using keys. Object.entries() gives you an array of arrays, where each array is [key, value]. Object.values() just gives you an array of values.

Finally, for making sure the partner is appropriate, you can use partner.filter() to filter only the good partners and the bad partners.

Putting some of those together, you can easily do something like:

const total = Object.entries(capabilties.type).reduce(([key, type]) => {
  typeNumber = parseInt(type);
  const good = partners.filter(partner => key === partner.value.type && partner.value.isAvailable && appropriatePartners[key] < typeNumber);

  appropriatePartners[key].concat(good);

  if (appropriatePartners[key].length < typeNumber) {
    throw new Error('No appropriate partners');
  }

  return typeNumber;
}, 0);

if (total === 0) {
  throw new Error('Please mention at least 1 type of browser');
}

Of course, this isn't the only appropriate. I don't know which bits of your logic are simply so you can keep track and which have business logic behind them. Using some of the functions I mentioned, you can probably reduce it even further if you don't need to keep track of certain things.

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks but I couldnt understand something here, is that all code or just the part I am asking for.. What happened the code for constructing appropriatePartners, and what is good there ?couldnt get it
Basically, there isn't one single solution. The code I gave you is roughly equivalent to what you have above. The filter() and concat() bit will do the same as your for loop, which is one possible approach. I also gave you a number of functions you could use to make it more elegant as you had original asked.
I couldnt do it because I dont have array in the beginning. My manager told me to do it in the beginning. this is an example I send as capabilities... const capabilities = { type: { chrome: 1 } }
If one isn't an array, you can turn it into an array with one of the Object functions I mentioned above.
I did it, and I prepared a predicate function which returns true if input > 0 and used every method but didnt worked for me. I tried convertedArray.every(predicate). someshow I need to send lenghts to every, but I have an array of array actually, confused on that
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.