Ab_c
Ab_c

Reputation: 408

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?

Upvotes: 23

Views: 25126

Answers (2)

Rex
Rex

Reputation: 454

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;
};

Upvotes: 4

Halcyon
Halcyon

Reputation: 57719

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.

Upvotes: 42

Related Questions