Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnderscoreJS -- _.some() vs _.find()

From what I've read in the documentation, _.find() functions very similarly to _.some()

Does anyone know whether there are (performance) advantages between the two?

like image 696
Ab_c Avatar asked Mar 27 '13 17:03

Ab_c


2 Answers

Their performance characteristics are probably the same, assuming you want to know wether to use find or some in a specific case. They are both lazy in the same way.

The difference is in the output. find will return the value, some will return a boolean.


I checked the source (1.4.4). some and find both use some (=== any) internally. So even if a native implementation of some is used it benefits both find and some.

like image 84
Halcyon Avatar answered Nov 10 '22 07:11

Halcyon


If you look into it's source, you will find that those two are identical, _.find actually calls _.some.

_.find = _.detect = function(obj, iterator, context) {
  var result;
  any(obj, function(value, index, list) {
    if (iterator.call(context, value, index, list)) {
      result = value;
      return true;
    }
  });
  return result;
};

var any = _.some = _.any = function(obj, iterator, context) {
  iterator || (iterator = _.identity);
  var result = false;
  if (obj == null) return result;
  if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
  each(obj, function(value, index, list) {
    if (result || (result = iterator.call(context, value, index, list))) return breaker;
  });
  return !!result;
};
like image 26
Rex Avatar answered Nov 10 '22 08:11

Rex