1
\$\begingroup\$

Take this:

has_competitors:function(){
  var c = false;
  _.each(this.competitors, function(obj, index){ // lodash here
    if(obj.name && obj.name.trim() !== ''){
      c = true;
      return false; // to break the loop
    }
  });
  return c;
}

I don't like the form of this, but till now I didn't find a more concise way. Could you suggest a better way? :) I mean, less lines.

| improve this question | | | | |
\$\endgroup\$
  • 2
    \$\begingroup\$ What does this function do? Please tell us, and make that the title of the question — see How to Ask. Also tell us what _ is — use the lodash.js or underscore.js tag as appropriate. \$\endgroup\$ – 200_success Jul 25 '18 at 14:03
  • \$\begingroup\$ There were already enough informations to have 2 answers and one accepted, so I don't really see the point. Anyway, added the informations you're asking for. \$\endgroup\$ – Luca Reghellin Jul 26 '18 at 21:50
1
\$\begingroup\$

I assume you are using lodash library.

You may use _.some function.

Checks if predicate returns truthy for any element of collection. Iteration is stopped once predicate returns truthy. The predicate is invoked with three arguments: (value, index|key, collection).

has_competitors: function(){
    return _.some(this.competitors, function(obj){
        return obj.name && obj.name.trim() !== '';
    };
}
| improve this answer | | | | |
\$\endgroup\$
4
\$\begingroup\$
  • Since ES5 (which all browsers support nowadays) is array.some(). It works in the same way as Lodash's/Underscore's _.some() but without the library.
  • If you target ES6, you can further trim your code using shorthand object methods and arrow functions.
  • Your object.trim() can blow up if object.name is truthy but not a string. Do a typeof obj.name === 'string' instead of a truthy check. If it is always guaranteed to be a string, the truthy check is redundant since a trimmed empty string will always be empty.

So your code could be as simple as:

has_competitors(){
  return this.competitors.some(obj => obj.name.trim() !== '') 
}
| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ Good suggestions. Anyway in my case competitors is a collection (obj) not an array, so I'll go for lodash. \$\endgroup\$ – Luca Reghellin Jul 26 '18 at 7:50

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