Pages

Monday, June 6, 2016

Rebuild Underscore's each function

Each basically replaces a for loop.  It returns nothing, it simply iterates through either an array or an object.  This first step is to determine whether we are dealing with an object or an array:


I'll show you a couple of ways this can be done:

var _ = {};


_.each =  function(collection, iterator){

  if(Array.isArray(collection)){
    for(var i = 0; i < collection.length; i ++){
      iterator(collection[i], i, collection);
    }
  }
  else{
    for(var key in collection){
      iterator(collection[key], key, collection);
    }
  }
}


And probably the better way:

 _.each = function(collection, iterator) {
    if (collection.constructor === Array) {
      for (var i = 0; i < collection.length; i++) {
        var index = i;
        iterator(collection[i], index, collection);
      }
    }
    if (collection.constructor === Object) {
      for (var key in collection) {
        iterator(collection[key], key, collection);
      }
    }
  };

Not much of a difference here.  I'll walk step through step through the first example.

First we determine if we are dealing with an array or an object.  Obviously this is because an array will use a for loop to iterate through itself and on object will use a for in loop to iterate through itself.

Array.isArray(collection) will either return true or false.  If true, the for loop is run, else the for in loop is run.

The important thing here is that the loop is run on each item in the array, the index of the array, and the array itself.  This gives us the choice of iterating through all three of these or just one, or two.

Notice that each calls for a function as a parameter, or in the example above it is called iterator.

So, let's say I want console.log each item added to its index number.  I would call it like this:

_.each(collection, function(item, index){
  console.log(item + index);
});


if the collection were this array = [1,2,3]

Then 1
         3
         5
would print out to the console.  This is because the first item is 1 + its index of 0 = 1, the second item is 2 + its index of 1 = 3, and the last item is 3 + its index of 2 = 5.

Remember, _.each is basically just a for loop, it can produce a side effect, but it does not return anything.  _.each is very useful to call inside other Underscore functions instead of creating for loops inside of them.



No comments:

Post a Comment