Implementing _.some by using _.every

January 14, 2019

I was working on re-implementation of some functionalites of underscore.js. I found it’s actually interesting to discuss how to use _.every to implement _.some.

First of all, let’s quickly look up what _.every and _.some are from the official document of underscore.js.

every _.every(list, [predicate], [context]) Alias: all
Returns true if all of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a false element is found.

every is actually the same as logical AND.

some _.some(list, [predicate], [context]) Alias: any
Returns true if any of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a true element is found.

some is actually the same as logical OR.

Now, let’s come to the question, how to use _.every to implement _.some?

If _.every returns true, then _.some returns true. However, if _.some returns true, we still can’t conclude the result of _.every.

So, what might happen when _.some returns true? It means, at least one of the values in the list pass the predicate truth test. In other words, at least one of them does NOT pass the predicate FALSE test.

How about when _.some returns false? It means none of the values in the list pass the predicate truth test. In other words, ALL of them pass the predicate FALSE test.

If we use the predicate FALSE test to replace the predicate TRUTH test in the function of _.every, it will look like this

_.every(list, ![predicate], [context])

It returns true if All of the values in the list pass the predicate FALSE test. However, _.some should return FALSE in this situation. Thus, we can use “!” to toggle this entire statement like this

!_.every(list, ![predicate], [context])

Does it also work when _.some returns true? When this statement returns true, it means NOT ALL of the values in the list pass the predicate FALSE test. In other words, it also means at least one of them does NOT pass the predicate FALSE test. So, yes! It also works when _.some return true.

Now, let’s re-organize this statement.

_.some = !_.every(list, ![predicate], [context])

It also can be written as below.

_.some = function(list, [predicate]){
  return !(_.every(list, function(value) {
    return ![predicate];
  }));
}

Hope my explanation is helpful to you.