Rory Perro
Rory Perro

Reputation: 451

Underscore every from scratch

I'm practicing _.every from scratch to learn Javascript, and there are just two lines that I don't understand. Could you articulate what these lines are doing:

if(iterator == undefined) { 
  iterator = _.identity; 

_.every = function(collection, iterator) {
  if(iterator == undefined) { 
    iterator = _.identity; 
  }

  return _.reduce(collection, function(accumulator, item) {
    if (iterator(item)) {
      return accumulator;
    }
    else {
      return false;
    }
  }, true); 
};

I know that _.identity returns the same value that is used as the passed parameter, but I'm not quite seeing how it's applicable here?

Upvotes: 0

Views: 260

Answers (2)

chilleren
chilleren

Reputation: 81

_.identity is a function that returns what ever you pass in. f(x) = x

If you call _.every without an iterator, then the iterator is set to _.identity as a default. This allows you to call _.every without passing in your own iterator. It's basically just a convenience, since you could pass in _.identity yourself if you wanted.

Upvotes: 1

Pointy
Pointy

Reputation: 413720

If the iterator parameter is undefined, that statement makes _.every use _.identity as the default iterator.

Why would that be useful? Because it makes _.every(someArray) be a test to see whether all of the entries in the array are "truthy". For example, if you've got an array that you know contains numbers, and you want to see whether they're all non-zero, you can use _.every() with only one parameter (the array) to make that test.

Upvotes: 1

Related Questions