Rory Perro
Rory Perro

Reputation: 451

Underscore contains from scratch?

for practice, I'm studying underscore contains from scratch. There's one part of the code that I cannot articulate or understand. What does this line do:

"return item === target;"

The code:

_.contains = function(collection, target) {

    return _.reduce(collection, function(wasFound, item) { 
      if (wasFound) { 
        return true;
  }
      return item === target;
    }, false); 

};

Upvotes: 0

Views: 149

Answers (2)

Vivin Paliath
Vivin Paliath

Reputation: 95518

It just returns a boolean from the callback to reduce. The result of the expression item === target is a boolean (i.e., either true or false). It's a short-hand and (IMO) more-elegant way of doing the following:

if(item === target) {
    return true;
} else {
    return false;
}

The === is "strict equals", which means it will not perform any type-coercion. This is why "2" == 2 will return true because "2" can be coerced into the number 2 (and vice-versa). But "2" === 2 will return false because it does not perform any type-coercion, and the two arguments are of different types.

The reduce function works by iterating over each element in a collection and calculating some sort of value that is also used within each iteration.

During the initial call to the reduce function, wasFound is set to false (notice the false passed in to the call to reduce after the callback). The first if will not be satisfied and so the function will execute the return statement. This value that is returned will be the new value of wasFound in the next iteration.

This means that as long as wasFound is false, we will try to see if the next element matches the one that was passed in. If it is true, it means that we have found the element we want and so we can just keep returning true.

IMO the function is a little bit inefficient because it doesn't break out early once it has found the element it is looking for, and traverses the entire collection regardless.

Upvotes: 1

dave
dave

Reputation: 64657

if (wasFound) { 
    return true;
}

You are going through the collection, and it the item has already been found, you return true.

return item === target;

Otherwise, you return true if the current item is equal to the target are searching are you, and false if it is not.

Upvotes: 1

Related Questions