Pages

Saturday, June 11, 2016

Rewriting underscore's contain function

We've done so many of these now,  I'm not going to beat around the bush:


_.contains = function(collection, target) {

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


There it is.

If you are experience confusion, please read the rewrite of each post, and the rewrite of reduce post.

Contains is a function that takes a collection, can be an array or an object, and accepts a target value to search for.

Contains calls reduce, passes it the collection, and hard wires a function into reduce that, of course, takes the two parameters usually referred to as accumulator and item, but here we've called it wasFound instead of accumulator.  Remember, names don't matter.

Then, this function returns true, if wasFound equals true, or it returns the value of item === target, which will be either true or false.

Also, notice, that we do set the accumulator to false.  Notice false after the curly brace.  Don't forget, reduce accepts three arguments, a collection, a function, and a value for the accumulator.  If no value is set for the accumulator, then it is just set to be the first item.

If wasFound does equal true, then true will be returned to the function, which if you remember, will set the accumulator to true, and since this function is running inside of each, the next iteration will take place.  At the beginning of the next iteration, wasFound will still equal true, so true will be returned, over and over and over again, until the each cycles have finished running.

Then the function will return the value of wasFound to the reduce function, and the reduce function will return that value, whether true or false, to contains, which will then pass it to what called it.

And that's contains in a nutshell.

P.S.  _.contains searches through each item in an array, and each value in an object, not the objects keys.


No comments:

Post a Comment