Pages

Tuesday, June 28, 2016

Coding challenge : Equidistant letter sequence

So, you're a very low tech spy and you want to encrypt a message before sending it.

You want to insert a certain number of random letters and place them between each letter in your message.  For example,

hello

would become

hwoexolehlzhowe

After each letter in the message, two random letters are inserted.

Your mission, should you choose to accept it, is to create this Equidistant encoder, and also an Equidistant decoder which will return the encoded message back to its original code.

Your function should accept two parameters.  1, the message to be encoded, and 2, a number.  This number argument determines how many random letters are place between each letter.

Good luck,

Solution is in the comments.


Saturday, June 25, 2016

CSS colors in words chart

Handy site:



http://www.colors.commutercreative.com/grid/

Coding challenge to be solved with Underscore functions....

Given a list of arrays, return the total length of all arrays added up.

For example, if the length of the first array was 5, and the second was 10, the total length of all arrays would be 15.

You can use the below arrays for testing:


var array1 = [[1],[2],[3],[4].[5]];
var array2 = ["a", "b"];
var array3 = [{name : "John"}, {age : 21}];
var array4 = [1,2,3,4,5,6,7,8,9,0];


19 should be returned.


Solution is in the comments.

Wednesday, June 22, 2016

JQuery cheat sheet

https://oscarotero.com/jquery/

Terminal commands

cd = to move into a folder


ls =  to list all folders and files in current location


open = type open, then space, then file name to open a file


open -a "Sublime Text" index.html = to open a file with a specific program, type open, then space, then -a, then space, then the name of the program in quotation marks, then space, then the file name.  

touch = create a new file


mkdir = create a new folder


rm = delete a file


rm -r = delete a folder and its contents






Tuesday, June 21, 2016

Coding challenge that can be solved with Underscore functions

Take a bunch of objects, with a bunch of products as properties and dollar amounts as values, and build one brand new object that contains all products over 5 dollars from each object.


You can use the below objects as examples:


var objCandy = {
"candy bar" : 1.5,
"bag of chocolate" : 3,
"big bag of marshmallows" : 6,
"Ferrorro Rocher - 20 pk " : 9,
chocolate_syrup : 3
};

var objProduce = {
"head of lettuce - organic" : 3,
"bag of organic apples" : 10,
lemon : 1,
"10 pound bag of potatoes": 7,
Broccoli : 4,
cherries : 12,
};

var objMeat = {
beef : 8,
chicken : 5,
pork : 6,
hotdogs : 4,
salmon : 16
};

var objDry = {
bread : 3,
peanutButter : 6,
jelly : 3,
coffee : 10,
tea : 4,
jalapenos : 4
};

var objFrozen = {
"ice cream" : 4,
vegetables : 6,
pizza : 12,
waffles : 6,
juice : 3,
"fish sticks" : 8
};

var dairy = {
cheese : 13,
creamCheese : 4,
butter : 7,
eggs: 5,
milk : 6
};

var toys = {
PS4 : 350,
"Xbox One" : 320,
videoGame : 40,
bike : 90,
lego : 180
};












Sunday, June 19, 2016

Coding challenge to be solved with Underscore functions...

Time to do some secret encoding!  You never now, one day you might be a spy.

I won't bore you with a long story, but a famous encoding method is to swap the first 13 characters of the alphabet with their opposites.

For example, A would become N. A is the first of the first 13 letters, and n is the first of next set of 13 letters.

So, A would become N and N would beome A.  B would be o and o would be b.  C would be p, and p would be c.

M would be z and z would be m.

So, you can take a secret message like this:  "  The money is hidden in the blue pillow"
and output this :

    gurzbarlvfuvqqravaguroyhrcvyybj

Thus, you can send your secret message without fear of someone figuring it out.  I understand that emails are encrypted, but what if you send it by mail?  What if you leave a note?


The same function will also decode the message when fed back to it.

The solution is in the comments.


Coding challenge for Underscore functions

Take an array of names, and return a new array with no names repeated.

For example :

var arrayNames = ["Abagail", "Andrew", "Andrew", "Betsy", "Bobby", "Carl", "Cliff", "Carl"];

should return = ["Abagail", "Andrew", "Betsy", "Bobby", "Carl", "Cliff"];


Solution is in the comments.



Extra credit : Build a function that will count how many times the same names appears in the array.

The function fed arrayNames should return 2, because 2 times a name appears that is already in the array.

Solution is also in the comments.

Coding challenge

Hint : Use an underscore function.

Make all of the even numbers in an array odd, and then return the array with all odd numbers. Make each even number odd by adding 1.


For example,

var array1 = [2,5,7,6,5,8,9]

output should be : [3,5,7,7,5,9,9]
Solution in the comments.  



Coding challenge that can be solved using Underscore's functions.

Check the array below to see if any of the words in it are less than 8 characters:

var array1 =["beautiful", "longing", "trepidation", "anxiety", "happiness", "excitement"];

I almost feel as though I wrote a poem there.  LOL.

The output should equal true if all words are 8 characters or more, and false any word is less than 8 characters.

Solution in the comments.

Saturday, June 18, 2016

Coding challenge using Underscore functions

Take 4 arrays of 4 objects each, and return a new array with just "ages".  Then make sure that every age is over 21, if not, return false, is so, return true.


arrob1 = [{name : " Aaron " , age : 20}, {name : "Adam", age: 30} {name : "Bill", age : 40}, {name : "Bob", age : 30}];

arrob2 = [{name : " Charles " , age : 20}, {name : "Chad", age: 30} {name : "David", age : 40}, {name : "Donald", age : 30}];

arrob3 = [{name : " Evan " , age : 20}, {name : "Eugene", age: 30} {name : "Frank", age : 40}, {name : "Fred", age : 30}];

arrob4 = [{name : " Gerald " , age : 20}, {name : "Gene", age: 30} {name : "Harold", age : 40}, {name : "Henry", age : 30}];



 Solution is in the comments.

Friday, June 17, 2016

Coding challenge using Underscore functions.

Build a function that will filter through any number of arrays, and return all the numbers that pass a truth test.

The function should have one parameter, which is the truth test callback function, but any numbers of arrays can be fed as arguments, because the function will access the arguments object.


You can use the arrays below if you like for testing purposes.  


var array1 = [3,5,4,3,4,5,6,35,34,56,78,345];

var array2 = [4,6,2,8,77,66,55,44,5,7,2,4];

var array3 = [3,6,9,15];

var array4 = [9,7,5,3,1];

var array5 = [44,6,5,78,234,456,678];

var array6 = [77,88,99,0,234];

var array7 = [14,65,45,87,65,45,44];

var array8 = [55,44,33,22,11];

var array9 = [3,33,333];

var array10 = [999, 871, 751];


For example, if my function was fed a callback function that tested if numbers were divisible by 4, then it would return this after feeding it all the above arrays at once: 

[ 4, 4, 56, 4, 8, 44, 4, 44, 456, 88, 0, 44, 44 ]


The solution in the comments.











Some coding problems to practice using Underscore functions

1.  Take this array of objects and extract out the values of a particular property from each of them.

Use can use this array:

var arrayObj = [{name: "Johen", age: 7}, {name : "Brian", age : 8}, {name: "Sam", age: 98}, {name : "Jules", age : 89}];


2. Build a function that will take an array of objects, and return the number of times a particular value in each object passes a truth test.

  For example, let's say, in the above array named arrayObj, that I wanted to count how many people are over 18.

  My function has three parameters, collection, key, age .  So, I can put enter in any age I like, and get the number of people over that age returned to me, as a number.  The above array returns 2 in my function if I use 18 as age.


Solution in the comments.




Thursday, June 16, 2016

Coding challenge

Take a number cubed like 2, for example(2 * 2 *2) and add it to another number cubed like (3 * 3 *3) = 35.

We want to write a function that will return true if there is more than one pair of numbers, say, at least 2 pair, that when each is cubed add up to the number.

Let's take for example, 1,729.  9 cubed + 10 cubed will equal 1, 729 and 1 cubed and 12 cubed equal 1,729.  Thus more than one pair of cubed numbers add up to 1, 729 so the function would return true.

9 would return false, because only one pair of cubed numbers can add up to be 9.  2 cubed + 1 cubed = 9.

Good luck.

The solution is in the comments.



Coding challenge using an Underscore function

Combine 10 objects into one new object.  This new object should share no reference with any other object, in other words, adding a new property to this new object later on, will not also add that property to any other object.


Here's ten objects below to save you testing time:



var obj1 = {
name: "Joanna"
}

var obj2 = {
activities : "shopping"
}

var obj3 = {
age : 30
}

var obj4 = {
"hair color" : "brown"
}

var obj5 = {
"name real" : false
}

var obj6 = {
job : saleswoman
}

var obj7 = {
car : "Prius"
}

var obj8 = {
"car color" : "Purple"
}

var obj9 = {
height : "5 feet 11 inches"
}

var obj10 = {
weight : 180
}


This is very easily accomplished with extend.

Monday, June 13, 2016

Flatten an array using an Underscore function

This Underscore function also has a native version, you can use either.

Take an array such as this one:

var arrays = [[1, 2, 3], 8,[4, 5], [6]];

and flatten it so that it looks like this:

[1, 2, 3, 8, 4, 5, 6];


Hint in the comments.

Another Underscore coding challenge

Given an array that has numbers, and arrays of numbers, leave the single number values alone, but do the following to arrays within the array with more than one number, multiply them by the number of values in the inner array.

For example, let's use this array here:


var array1 = [2, [3, 5, 4], 4, 6, 4, [3, 3, 1, 6, 4], 5, [5, 6]];

The returned array would be = [2, [9, 15, 12], 4, 6, 4, [15, 15, 5, 30, 20], 5, [10, 12]];


The first two is a single value, not in a subarray, so we do nothing to it.  The following 3, 5 and 4 are in a subarray, and there are three values in that subarray, so we multiply each number in the subarray by 3, and so on.


Tip : I used map for this.

I'll post my solution in the comments.




Write a function that runs a deep comparison on two objects


Just like the title says, we need a function that can run a deep comparison on two objects to see if they equal each other.

In case you don't know this:

var obj1 = {

name : "Sam"

}

var obj2 = {

name : "Sam"

}


obj1 === obj2
// false

That's right, obj2 does not equal obj2 even though they are identical.  This is because objects are passed by reference, not as values.  Variables are the opposite.

var banana = 5;

var apple = 5;

apple === banana;
// true

The variable banana holds the value 5, as does apple, so when you compare the two the question is does 5 equal 5, and that is true.

However, the object does not hold a value.  It holds an address to a location in memory where the value/ values are stored.  If memory addresses were the same as home addresses, then the object might hold something like 832 West Maple St., APT 9.

The address where the values for obj1 are stored might be 99283746, for example.
The address where the values for obj2 are stored might be 23827342834, for example.

So, when we compare obj1 === obj2, what we are comparing is 99283746 === 23827342834 which is false.

This is what is meant by objects are passed by reference.  Take this example :

var obj1 = {

name : "Sam"

}

var obj2 = {

name : "Sam"

}

var obj3 = obj1;

obj1 === obj3;
// true;

When I assign the var obj3 to be equal to obj1, the address to the memory which holds the values for obj1 is passed to obj3, so obj3 now equals 99283746.

Just imagine that the browser knocks on the door of obj1, because it wants to see inside it:

Knock, knock.  Who's there?  The browser?  The browser who?  The web browser, I want to see inside you.  Okay, go to 99283746.


So, let's create a function that will compare not the addresses of two objects, but there actual properties and values.

Tip, arrays are also objects.  A for in loop can be used on arrays too.

A little recursion will help.


All of these should return true, except for the second one :

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));

console.log(deepEqual(obj, {here: 1, object: 2}));

console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));

console.log(deepEqual([5, {names : [{d :"sam"},{s : "mike"},{da : "joen"}]}], [5, {names : [{d :"sam"},{s : "mike"},{da : "joen"}]}]));


I'll put the solution in the comments.


Sunday, June 12, 2016

A bunch of Underscore's functions rewrites in one place:

var _ = {};

 _.identity = function(val){
    return val;
};



 _.first = function(array, n){
    return n === undefined ? array[0] : array.slice(0, n);
 }

 _.last = function(array, n){
    if(n === 0){
      return [];
    }

   return n === undefined ? array[array.length -1] : array.slice(-n);
}


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



 _.indexOf = function(array, target){
    var result = -1;
    var initial = 0;
    _.each(array, function(item, index){
      if(item === target && initial === 0){
        result = index;
        initial ++;
      }
});
    return result;
}



 _.filter = function(array, callback){
    var filterArray = [];
    _.each(array, function(item){
      if(callback(item)){
        filterArray.push(item);
      }
    })
    return filterArray;
}



 _.map = function(array, callback){
    var mapArray = [];

    _.each(array, function(item){
      mapArray.push(callback(item));
    });
return mapArray;
}




 _.uniq = function(array){
    var uniqArray = [];
   
    _.each(array, function(item){
      if(_.indexOf(uniqArray, item) === -1){
        uniqArray.push(item);
      }
    });
    return uniqArray;
}

 _.contains = function(collection, target){
    var result = false;

    _.each(collection, function(item){
      if(item === target){
        result = true;
      }
    });
    return result;
}


 _.pluck = function(array, prop){
    var pluckArray = [];

    _.each(array, function(item){
      pluckArray.push(item[prop]);
    })
    return pluckArray;
}



 _.reduce = function(collection, callback, accumulator){
    var initial = 0;

    _.each(collection, function(item){
      if(accumulator === undefined && initial === 0){
        accumulator = item;
      }
      else{
        accumulator = callback(accumulator, item);
      }
    });
    return accumulator;
}




 _.reject = function(array, callback){
    return _.filter(array, function(item){
      return !callback(item);
    });
}



 _.every = function(array, callback){
    callback = callback || _.identity;
    return !! _.reduce(array, function(a, b){
      return a && callback(b);
    }, true);
}




 _.some = function(array, callback){
    callback = callback || _.identity;
    return !! _.reduce(array, function(a, b){
      return a || callback(b);
    }, false);
}



 _.extend = function(obj){
    _.each(arguments, function(item){
      _.each(item, function(value, prop){
        obj[prop] = value;
      })
    });
    return obj;
}










  

Saturday, June 11, 2016

Coding problem to solve using recursion

Decide if a number can be reached starting with 1 by either adding five or multiplying by three in any number or combination of steps.  For example, 15 can't be reached, but 13 can be reached by 1 * 3 + 5 + 5.

If the number can be reached, return true, if not, return false.


Hint : use recursion.


This one might be really hard.

That's what she said.



Coding problem to solve using underscore.

Find out if an object or array contains the name "Jeffery".  Return true if the collection does, false if it doesn't.


Here's an object and an array you can use for testing:


var names1 = {

name1 : "Jeffery",
name2 : "Sam",
name3 : "Robert",
name4 : "Sarah",
name5 : "Susan",
name6 : "Jolene",
name7 : "Fred",
name8 : "Seth"


};


var names2 = ["Jeffery", "Sam", "Robert", "Sarah", "Susan", "Jolene", "Fred"', "Seth"];


By the way, if you want a true/ false if a certain property exist in an object, then use the in keyword.

For example,

"name2" in names1;

will return true.









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.


Friday, June 10, 2016

Problem's to solve using Underscore's functions

Take this array of numbers, and return a new array with each number multiplied by the next number.  Basically, calculate the total of each number in the array, multiplied together.  For example, if the array were, 4,5,6,7 the total would be 4 * 5 *6*7 = 840.


You can use this array:

var testArray1 = [4,8,12,16,20,24,28,32,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,100,104,108,112,116,120,124,128,132,136,140,144,148,152,3,156,160,164,168,172,176,180,184,188,192,196,200,204];


The easiest way is to use reduce.  


Problems to solve using Underscore's functions

Find out if any of the numbers in the array are divisible by three.  If there is at least one, return true, if not, return false.

var testArray2 = [4,8,12,16,20,24,28,32,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,100,104,108,112,116,120,124,128,132,136,140,144,148,152,3,156,160,164,168,172,176,180,184,188,192,196,200,204];


var testArray1 = [4,8,12,16,20,24,28,32,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,100,104,108,112,116,120,124,128,132,136,140,144,148,152,3,156,160,164,168,172,176,180,184,188,192,196,200,204];


_.some can do this very easily.  

Both the above arrays will return true.  However, this one should return false:


var testArray3 = [2,1,4,5,7,8,10,11,13,14,16,17,19,20,22,23,25,26,28];

Code problem to solve with Javascript's underscore functions.

Determine whether every number in the array is divisible by 4.  The function you make should return true or false.


var testArray1 = [4,8,12,16,20,24,28,32,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,100,104,108,112,116,120,124,128,132,136,140,144,148,152,156,160,164,168,172,176,180,184,188,192,196,200,204];

var testArray2 = [4,8,12,16,20,24,28,32,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,100,104,108,112,116,120,124,128,132,136,140,144,148,152,3,156,160,164,168,172,176,180,184,188,192,196,200,204];

testArray1 === true;

testArray2 === false;

I just used _.every.

Code problem to solve using Underscore functions

Take an array of names, and return a new array with only those names that are longer than 5 letters.


To make it a bit more complicated, I will use this array of objects, and will return just a single array with the correct names in it.  Also, the function you build should be adjustable as to the length the names need to be.  For example, it should accept two arguments, on is the array, and the other is the minimum length of letters the name needs to be  :

[ { Alice: '', Bob: '', Chelsea: '', Deborah: '', Katherine: '', Joel: '', Blaine: '', Elvis: '', Jules: '', Flo: '', Andy: '', Barney: '', Helen: '', Jim: '', Dwight: '', Michael: '', Meredith: '', Kevin: '', Angela: '', Kelly: '', Karen: '' }, { Sam: '', Sara: '', Wyona: '', Tyler: '', Rebecca: '', Wannita: '', 'Thema Lou': '', Otis: '', Pam: '', Phyllis: '', Stanley: '', Ryan: '' } ]

UnderScore coding challenge

Create a function that will take an array of names, and filter them into two new objects.  One with names A - M and the other with names N - Z, with the names as keys and an empty string as their values.  Then return a new array that contains both these objects.



You can use this array for testing if you like:

[ 'Sam', 'Sara', 'Alice', 'Wyona', 'Bob', 'Chelsea', 'Deborah', 'Katherine', 'Tyler', 'Joel', 'Blaine', 'Rebecca', 'Elvis', 'Jules', 'Flo', 'Wannita', 'Thema Lou', 'Andy', 'Barney', 'Otis', 'Helen', 'Jim', 'Dwight', 'Pam', 'Michael', 'Phyllis', 'Stanley', 'Meredith', 'Kevin', 'Angela', 'Ryan', 'Kelly', 'Karen' ]



This should be the result:

[ { Alice: '', Bob: '', Chelsea: '', Deborah: '', Katherine: '', Joel: '', Blaine: '', Elvis: '', Jules: '', Flo: '', Andy: '', Barney: '', Helen: '', Jim: '', Dwight: '', Michael: '', Meredith: '', Kevin: '', Angela: '', Kelly: '', Karen: '' }, { Sam: '', Sara: '', Wyona: '', Tyler: '', Rebecca: '', Wannita: '', 'Thema Lou': '', Otis: '', Pam: '', Phyllis: '', Stanley: '', Ryan: '' } ]



Hint : you'll want to use some Regexp here, for example, /[a-m]/i

Thursday, June 9, 2016

Problems to solve using Underscore functions

You have an object with a list of names and birthdays.  You want only the names on the list that have birthdays after 2000. Return an array of the names of all the people with birthdays after 2000.

Below is the object =

var dataBase =  {

Sam :1952,
Sara : 1978,
Alice : 1982,
Wyona : 1981,
Bob : 2004,
Chelsea : 2008,
Deborah : 1949,
Katherine : 2001,
Tyler : 1999,
Joel : 1961,
Blaine : 1979,
Rebecca : 1976,
Elvis : 1977,
Jules : 2014,
Flo : 2001,
Wannita : 1941,
"Thema Lou" : 1967,
Andy : 1987,
Barney : 2015,
Otis : 1978,
Helen : 1996,
Jim : 2002,
Dwight : 2008,
Pam : 1956,
Michael : 2005,
Phyllis : 2003,
Stanley : 1975,
Meredith : 1986,
Kevin: 1990,
Angela : 2008,
Ryan : 2002,
Kelly : 1960,
Karen : 1979
};


This is incredible easy to do with _.each.

Wednesday, June 8, 2016

Rewrite Underscore's extend function

Extend can add properties to an existing object  or copy the properties from other objects into an existing object.


Extend is called like this:  _.extend(obj);

Yep, that's it.  You feed it the object that you want added to , and then you either fill in a bunch of these : {example : example} or names of other objects.

Inside the extend function the arguments array will be accessed.  If you don't know what the arguments object is, I would go ahead an google it.  You'll need to learn about it at some point.

So, extend is rewritten like this:


_.extend = function(obj) {
_.each(arguments, function(item){
_.each(item, function(value, prop){
obj[prop] = value
})
})
return obj;
}


Pretty simple.  It's a function that takes an object as an argument, and like any function, can take any number of arguments.

It calls each and feed it the its own argumentsobject, which is accessed with the keyword arguments.

The arguments object is similar to  an array, but the only array property is has is .length.

The first each accesses each item in the arguments object, the second each iterates through each item, grabbing the key and the value in each obj, and then assigns the new key and value to the existing obj.

Finally, the object is returned.

If this confuses you, I would suggest making an array of objects and playing around with it.  

Rewrite Underscore's every function

I won't spend a lot of time on every, since we basically built every in the Rewrite Underscore's reduce function post.  Every returns true if every item in the array passes a truth test is truthy, and false if otherwise.  Every handles more situations than what we built in the previous post does though.  Say, for example, if no function is provided, or what if we get a mix of truthy and falsey results?  If you don't know what truthy or falsey means, google it.  There is also one other small point that has to be brought up.  The key word undefined is falsey, and should return false to every.

This word undefined causes a problem with the way I rewrote the Underscore reduce function.  Let me show you this quickly, and an alternative rewriting of reduce that you can use if you want to test these by copying and pasting into a repl editor.

var _ = {};



_.identity = function(val) {
  return val;

}

  _.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);
    }
  }
}

_.reduce = function(collection, iterator, accumulator) {

_.each(collection, function(item){
if(accumulator === undefined){
accumulator = item;
}
else{
accumulator = iterator(accumulator, item);
}
})
return accumulator;
}


_.every = function(collection, iterator) {
    iterator = iterator || _.identity;

    return !! _.reduce(collection, function(a, b){
    return a && iterator(b);
    }, true)

}


Every uses reduce and each.  Let's call every:

var words = [true, undefined, 1];

_.every(words);

That's it in this example.  I'm just going to feed it the variable words.  Notice in the every rewrite that every expects a function as an argument.  However, it's first line of code says that iterator = iterator(the function given) or the function _.identity.  Since I've provided no function when I called every, _.identity will be used, and remember, identity simply returns what ever value it is provided.

So, every calls reduce, feeds it the collection words, and hard wires in a function that takes two parameters(the accumulator and the item), and then returns the accumulator && the result of the function fed item, and we initially set the accumulator to true.

So, it walks through like this : accumulator equals true so we look on the right side of the && operator.  This function is identity so it just returns the value passed to it, which in this case is the boolean value true(which is the first item in the array words).  So this function returns true.  Now quickly look up at the reduce rewrite, look inside each, look inside the else statement, and look at the line accumulator = iterator(accumulator, item).  When I said, one sentence earlier, 'So this function returns true', this is where it gets returned to.  This line : accumulator = iterator(accumulator, item);

It looks something like this accumulator = true.

Next, the next iteration of each takes place.  Accumulator does not === undefined, so it moves on to the else statement.  accumulator = iterator(accumulator, item).

The iterator that we wrote says return a && iterator(b) - remember a is the accumulator and b is the item - since a equals true we look on the right side, iterator(b) returns the value : undefined.  Normally this would not be a problem.  The accumulator becomes equal to undefined, and since undefined is falsey, in the next iteration only undefined would be returned, and would continue to be returned.  Don't believe me.  Try this in a repl editor:

var test = function(x, y){
  return x && y;
}

var example = test(undefined, true);
example;

undefined will be returned because undefined is falsey and therefor the right side of the && operator will not be looked upon.

Try some other combinations as well:

"", "happy" = ""

"happy", "" =  ""

A string is truthy, an empty string is falsey.

1, 0 = 0

0, 1 = 0

1 is truthy, 0 is falsey

So, normally. we wouldn't have a problem with our set up, but with the word undefined we have a whoops moment.  The if statement in the each iteration hits true, because accumulator === undefined.  This is our problem, and to fix this we need to make it so that the if statement only checks on the very first iteration.  There are many different ways to do this but here's one below:

_.reduce = function(collection, iterator, accumulator) {
var initial = 0;
_.each(collection, function(item){

if(accumulator === undefined && initial === 0 ){
accumulator = item;

}
else{
accumulator = iterator(accumulator, item);
initial ++;
}
})
return accumulator;
}

In the above example, after running one time, initial is incremented so that the if statement will never again equate to true, and so will never be run again.

Is there anything left to say?

I think we've about covered it all.  There is another function named some which returns true if any of the items in an array pass a truth test or are truthy, and false if none of them do or are.

Some can be written in exactly the same way with one small tweak.

Replace the && operator with the || operator.

The difference:

return false && true = returns false

return true && false = returns false

return false || true = returns true

return true || false = returns true













Tuesday, June 7, 2016

Rewriting Underscore's reduce function

Reduce is a very handy function.

Solve this problem for instance:

what is the total of all the numbers in this array added together :

var numbers = [2,66,756,432,5,6,7,8989,765,434,22,12,12,45,6,7,8,453,67,54,33,22,123,999];

With reduce this is very simple :

var example = _.reduce(numbers, function(a, b){
      return a + b;
  })

console.log(example);

13325 will be printed to the console.

Reduce takes an array, and reduces it to one item.  It does this by setting an accumulator equal to the function provided with the accumulator as the first parameter and item as the second.

There's actually a lot that can be done with reduce, because reduce is more generic in nature than functions like map or filter, that are built with specific uses in mind.

We can concatenate words:

var words = ["Yesterday", "I", "went", "to", "the", "store."]

var example2 = _.reduce(words, function(a,b){
    return a + b;
})

console.log(example2); Will print : YesterdayIwenttothestore.

You may notice there are no space between the words, here's how to fix that:

_.reduce(words, function(a, b){
    return a + " " + b;
})

This will print : Yesterday I went to the store.

What if you want to know if every word in an array has a length of 8 or greater?

var example3 = _.reduce(words, function(a, b){
    return a && b.length >= 8;
}, true)

console.log(example3) Will print out false.  All of the words in the array names words do not have a length of 8 or greater.

However, if you run it with this array you will get true:

var words2 = ["Yesterday", "Kentucky", "Mongolia", "Computer"];

You might notice something about the way we called reduce this time, there is a third argument there, this time it is the boolean value of true.

Yes, reduce is designed to accept three arguments.  The collection, a function, and an accumulator.  If you provide no accumulator, then reduce makes the first item in the array the accumulator.  However, if you do provide an accumulator, like we did with true, then that will be the accumulator.

So, if I walk through the call to reduce above in example3 it goes something like this:

a, which is the accumulator = true.  The function is instructed to return a, which is true, however notice the && operator.  If the left side of an && operator is true then the right side is looked at and returned.  So, because a equals true, the right side is examined, and that value equates to either true or false.  If the right side equates to true, then true is returned and the accumulator(you'll understand this when we walk through the rewrite) is set to true.  This will continue until the right side, and only if the right side, returns a value of false.  If that happens, then the accumulator(a), is set to false.

If we look at the statement return a && b.length >= 8, if the left side equals false, then the right side will never again be examined, that's just how the && operator works.  If that confuses you, google it.  MDN does a good job of explaining the operators.  That's Mozilla Developer's Network.

So, if this function receives on return of false, then no matter what, it will return false.

Whoops, we've actually just written the blue print of the Underscore  Every function.

Okay, so we've gone into a lot without even re writing reduce yet, so let's just get to it:



var _  = {};

_.reduce = function(collection, iterator, accumulator) {

_.each(collection, function(item){
if(accumulator === undefined){
accumulator = item;
}
else{
accumulator = iterator(accumulator, item);
}
})
return accumulator;
}


As you can see reduce uses each so I'll include that here:

  _.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);
    }
  }
}


Let's walk through reduce:

First, reduce accepts an array, a function, and an accumulator.

Next, it calls each, and feeds it the collection, and hard wires in a function that takes item as an argument.  The first thing it does it to determine whether or not an accumulator has been provided as an argument when reduce was called.  If not, then the first iteration involves setting accumulator = to item.

The next iteration will take that accumulator and set it equal to the value of the function provided when reduce was called, and this function is fed the accumulator, and the item.  These two arguments are represented in our above examples as a and b.


Finally, the accumulator is returned.

Questions?














 


Rewriting Underscore's pluck function

Pluck is very useful working with something that can be quite tricky, an array of objects like this one:

var info = [{name:"Sam", age: 40}, {name: "John", age: 60}, {name: "Bill", age: 70}];

With pluck, one can simply pull out a specific value from each object in the array.  For example, say you wanted all the names, or all the ages.  Pluck can do this for you like so:


var example = _.pluck(info, "name");

console.log(example);

['Sam',  'John', 'Bill' ]  will be printed to the console.



Pluck will use map, and map will use each, so I'll paste all those below:

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);
    }
  }
}


_.map = function(collection, iterator) {
var mapArray = [];
_.each(collection, function(item){
mapArray.push(iterator(item));
})
    return mapArray;
}



_.pluck = function(collection, key) {
      return _.map(collection, function(item) {
        return item[key]
    })
}

Let's walk through pluck.  Pluck takes two arguments, the collection being dealt with, and the property or key from which the value should be extracted.  In the example above where we called pluck, "name" was the key given and the values were extracted from the key "name".

Pluck calls map, feeds it the same collection, and hard wires in a function that takes item.  Remember, this function is going to be fed to each, this is why it has access to item.  However, because we are dealing with an array of objects the array named info will return the first object if we try this:  console.log(info[0]);

So the item fed to the function in this case is actually the first object in the array.  If you were to type this : console.log(info[0]["name"])  or an alternative way of doing roughly the same thing :
console.log(info[0].name) then 'Sam' would be printed to the console.

So, after the function hard wired to map takes the item as an argument, it then returns the value of item[key], the variable key here is supplied when pluck is called and could be for example, "name".

Values are returned to the functions that called them, so this value is returned to the function hard wired in map, we know map returns a new array and then is returned to pluck via the key word return in front of map.









Rewriting Underscore's map function

Map also returns a new array built out of the old array.  It simply runs a function on each item, and then returns that result.

Map uses each so I'll past that here too:


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);
    }
  }
}



_.map = function(collection, iterator) {
var mapArray = [];
_.each(collection, function(item){
mapArray.push(iterator(item));
})
    return mapArray;
}



So, let me walk through map.  First a local variable is declared, mapArray and is set to an empty array.  Then map calls each, feeds it the collection, and hard wires in a function to each.  This function will take item(this parameter could have any name, but by having the function take only one parameter I will only be using each item in the array, not the index number, or the collection itself) and then it will push to mapArray the value returned from the function fed item.  This function fed item is what is fed to map when it is called.  The parameter is named iterator when map is rewritten here, so the word iterator must be used inside each.

Let me give an example of when map might be used.


Take an array of numbers and multiply each by 80.

var numbers = [2,4,7,6,5,6,8,9,1,2];


var example = _.map(numbers, function(num){
    return num * 80;
  })

console.log(example);

This is what will be printed to the console : [ 160, 320, 560, 480, 400, 480, 640, 720, 80, 160 ]

When I called map I gave it two arguments.  The collection, and the I wrote a function.  This function is referred to as iterator in the map rewrite.  This iterator is passed into each, that is why it has access to item.  The function each takes the iterator and feeds it three arguments, the value, the index number, and the collection itself.  If the function you write has only one parameter, then that will be fed with the value as an argument.  This value I speak of is often referred to as item.

The main advantage to using map over building for loops to do the same thing, is in reducing the size and number of characters involved in the code.








Monday, June 6, 2016

Rebuilding Underscore's uniq function

Uniq also produces a new array and returns it.  It will simply return only 1 instance of each item in the array.  So the array [4,5,6,7,4,3,25,6,5], would be returned as [4, 5, 6, 7, 3, 25].


Uniq will use each and indexOf.

var _ = {};


_.indexOf = function(array, target) {
    // Although indexOf has been implemented for you, it has a DEPENDENCY: the
    // iteration helper `each`, which you will need to write yourself (above).
    var result = -1

    _.each(array, function(item, index) {
        if (item === target && result === -1) {
            result = index
        }
    })

    return result
}



  _.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);
    }
  }
}



_.uniq = function(array) {
  var uniqArray = [];
  _.each(array, function(item){
    if(_.indexOf(uniqArray, item) === -1){
      uniqArray.push(item);
    }
  })
  return uniqArray;
}


And here's an alternative way of writing uniq:

 _.uniq = function(array) {
    var uniqueStorage = {};
    var results = [];

    _.each(array, function(item) {
      uniqueStorage[item] = item;
    });

    _.each(uniqueStorage, function(prop) {
      results.push(prop);
    });

    return results;
  };


I'll begin by walking through the first uniq re write:

Since uniq will be returning a new array, I start by making a new local variable called uniqArray and set its value to an empty array.

Next I call each, feed it the array, and hard wire in a function, that takes item and then sets a conditional statement.  Inside the if statement I call the value of indexOf with uniqArray as the array to be searched, and item as the target.  Because it's empty, the first search of the array will return -1, which means that item does not exist inside that array.  Then each will continue iterating through each item in the array, scanning uniqArray to see if that item is in there.  If it is, indexOf will return the index value where the match is, and therefore it will not equal -1, and that item will not be pushed into uniqArray.

Finally, at the end of the function, uniqArray is returned.

Now, I'll walk through the second version.

First, two new local variables are created, uniqueStorage which is set as an empty object, and results which is set as an empty array.

Next, uniq calls each, feeds it the array, and then hard wires a function which takes an item, and then it creates a new property for uniqueStorage.  The new property is the name of the item and its value is set to the same name of the item.  Remember, how objects work.  If you try to define another property with the same name and value, then it will simply overwrite the existing one, it will not make a new one.

For example, you could make an empty object named var emptyObject = {};

Then you can add some properties:

emptyObject[5] = 5;
emptyObject[5] = 5;
emptyObject[5] = 5;
console.log(emptyObject);

This is what will print to the console:  {'5' : 5}

This is because the property 5 already exist, so it's simply overwriting the property that is already there.

Because of this, objects will often be used to filter out occurrences like this.

Next each is called once again, this time to run through the object, and it pulls all the values and pushes them to the new area to be returned.

Don't be fooled, in the above example, the word prop is used, but it is the value that is being called.  Remember, in each in the for loop the first value provided is the value.  You cannot simply call prop by name.  If you use one parameter, you'll get the value, the second parameter will get you the property or the key, and the third parameter will be the collection itself.

I find the first rewrite to be easier, so I use that one myself.








Rebuilding Underscore's reject function

While filter returns a new array of items from the original array that pass a truth test, reject returns ones that don't pass the truth test.

While one could start from scratch re writing everything, it would be better to note that filter nearly does the same thing.  Can't one just fiddle with filter a bit?  Since we're calling reject here, we can't reach inside filter and fiddle, but what we can fiddle with is the function that we feed reject, but that same function is going to be fed to filter, and that's where the fiddling happens.

First, let's run reject one time:


console.log(_.reject([1,2,3,4,6,8], function(item){
  return item % 2 === 0;
}););

Look familiar?  If we fed the same test to filter we would get [2,4,6,8], but with reject we will get [1,3]

Reject will need filter and each in order to run, so I'll paste those in below here first:

  _.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);
    }
  }
}



_.filter = function(collection, test) {
  var filterArray = [];

  _.each(collection, function(item){
    if(test(item)){
      filterArray.push(item);
    }
  });
  return filterArray;
}



_.reject = function(collection, test) {
    return  _.filter(collection, function(item){
      return !test(item);
    })

}


So, the reject function calls filter, and it feeds filter the collection, and then hard wires in a function for filter.  The function given to filter says to return the value of the test (this is the function we give reject when we call reject) with item as the argument and the bang sign tells it to turn true into false and false into true.

If you need to see an example of how this works, try this out in the console, or repl.it :

(8 % 2) === 0     This will equate to true.

!(8 % 2) === 0    This will equate to false.

So, take a look at where the filter function is written above.  Filter calls each, and then each takes the test with item as a parameter.  It runs this function which will either return true or false.  If it returns true then it pushes that item to the new array, where it waits to be returned at the end of the function.

So, when we hard wire our function to filter inside our reject function, we are giving the test that will be passed to each, that's why this function has access to item.  However, where it would normally return true, it will not return false because of our bang sign.  And where it would normally return false, it will now return true.

This is why all the items that fail the test will be returned, instead of all those that pass it.








Rebuild Underscore's Filter function

Filter is also going to use each.  It's going to run a truth test on each item in the array.  If the test on the item equates to true, then it's going to push this item into a new array, and finally the function will return this new array.

A quick example would be to take an array of numbers, and return only the even numbers.

var test = _.filter([1,2,3,4,5,6], function(item){
  return item % 2 === 0 ;
});

test will equal = [2,4,6]

The test of % 2 === 0 will return true if the number is even and false if it is odd.  How this works inside the function, I'll show below:


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);
    }
  }
}





_.filter = function(collection, test) {
  var filterArray = [];

  _.each(collection, function(item){
    if(test(item)){
      filterArray.push(item);
    }
  });
  return filterArray;
}





Once again, I've included the each function above the filter function, because filter will use each to iterate through its array.

Since filter will be returning a new array with all of the items that pass the truth test, we start out be declaring a new local variable, I named mine filterArray and set its value to an empty array.

Next, I called each, which will be fed the same collection fed to filter and then I hard wired in a function for each.  In this function I make a conditional statement, which says that if the test (which is the function fed to filter) which is fed the item === true, then push that item to the new array.

Finally, when the entire array has been iterated through the filterArray is returned.  This is the new array holding all those items that passed the truth test.

Questions?

#1 - How does the function given as an argument to filter have access to 'item' which is supplied inside of the each function?

Look where the function is run.  It is passed all the way down inside the each function, and that is why it has access to 'item'.  Each then produces a side effect by pushing to filterArray, which is declared outside of each inside the filter function.  



Rewrite Underscore's indexOf function

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);
    }
  }
}





_.indexOf = function(array, target) {
   
    var result = -1

    _.each(array, function(item, index) {
        if (item === target && result === -1) {
            result = index
        }
    })

    return result
}


I've included _.each above _.indexOf because indexOf uses each.

IndexOf searches an array for for a target.  If that target is found, it returns the index at which the object is found, otherwise it returns -1.

First it defines two parameters, array and target.  Then it creates the local variable results and sets its value to -1.

Then _.each is called.  The same array that is fed to indexOf is fed to each, and a function is hard wired into each.  The function that is hard wired in calls for arguments, item and index.  (If only the item was required, then there would only be one parameter there.)

Then a conditional statement is made which says that if the item === the target is true and the result === -1 is true, then result changes its value to the index that is associated with that item.  Finally, the results returned.

So, let's walk through how it would work with this array called numbers.

var numbers = [1,2,3];

var test = _.indexOf(numbers, 3);
In this case test will be equal to = 2.

This is because first result = -1.

The function each test whether 1 is equal to the target which is 3.  That will equate to false, so the result = index statement inside the blocks will not happen, in fact, since there are no more if statement, absolutely nothing will happen, and each will iterate to the next item in the array.   Next, the same thing will happen with 2.  Now, 3 === target will equate to true so the right side of the && operator will be checked : result === -1 will equate to true so result = index will take place, the index in this case is 2.  With the each loops finished, the return result statement will be run, and it will return 2.


Maybe you have a couple of questions?

Question 1 = Why set  var result = -1 ?

First the var keyword is used to make result a local variable.  It's best to keep all variables inside a function local, incase there is a global variable named result.  By using the var keyword inside the function, even if there is a global variable with the same name, the function will use the local
one.  The reason it's given a value of -1 is so if the target is never found, then -1 will be returned.  A return value of -1 means that the target does not exist inside the array.

Question 2 = Why do you need && result = -1.

The function indexOf returns the index of the first instance of the target.  So, say there are several matches in an array like this one: var numbers = [2,6,4,5,2,4,5,4].

If this array were run with a target of 4, the index that matches the target would change each time if it weren't for the && result = -1 statement.

However, as soon as item === target = true "And" result === -1 === true, then result is set to that first 4s index number.  The next time there is a match, result will not equal -1, therefore it will not change the value of result.

Eventually, when each has finished iterating through the array, result will be returned and that value will be the index number of the first match with the target.


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.



Rebuild Underscore's last function

var _ = {};

This function is very similar to the first function, but instead it returns the last items in an array.  For example, if you feed it 5 as an argument, you will get the last 5 items in the array.  If 0 is fed to it, then an empty array will be returned.

This is probably the most elegant way to write it:



_.last = function(array, n) {

  return n === undefined ? array[array.length -1] : array.slice(Math.max(0,array.length - n));

}


and here's a more simplified way to understand it easier:

_.last = function(array, n){

  if ( n === undefined){
    return array.length[-1];
  }

  if (n === 0){
    return [];
  }

  else{
    return array.slice(-n);
  }
}


The first examples checks to see if n is undefined and if so, returns the length of the array -1.  Remember, the .length will return how many items are in the array starting with the number 1, but the index in the array starts with 0.  That's why you have to minus 1 to get the index number.  If n does not equal undefined then the function will return the value from array.slice, which calls Math.max, which will take the greater of either 0 or array.length -n.   You might need to play with this one a bit before you understand exactly how it works, but in a nutshell:

Say this is the array = [1,2,3];

array.length = 3

array[array.length] = will return nothing at all.  This is because array.length = 3, and array[3] does not exist.  There is an array[0], array[1], and an array[2], but no array[3] in the above array.

However,

array[array.length -1]  will equal 3

So,

if you say :

array.slice(array.length -n);

this will appear to work.  if n is 1 then you will receive array.slice(array.length -1), which will equal 3.   This is because array.length -1 is 2 and 3 is at index 2 in the array.  Therefore slice starts with the number 3 and copies everything else after it.  Since 3 is the last one in the array, it just return three.

Here's the problem.  array.slice(array.length -2) returns 2 and 3.
                                 array.slice(array.length -3) returns 1,2 and 3.
                                 array.slice(array.length -4) returns 3.  And this is our problem.  

If the n argument fed to _.last is greater than the number of items in the array, the entire array should be returned.  However, array.length -4, in this example, = -1, and array.slice(-1) equals 3.

This is why Math.max is used.  What's sliced is given two options.  If n is bigger than 0,  then array.slice(array.length -n ) is used, otherwise, array.slice(0) is used.  array.slice(0) will return the entire array.

But I like I said, you'll probably need to play around with that one a bit.







Rebuild Underscore's first function

var _ = {};


Underscore's first function will return the first, n , items in an array.  So for example, if you call first and give it 4 as an argument, then first will return the first 4 items in the array.



_.first = function(array, n) {
    return n === undefined ? array[0] : array.slice(0, n)
}

So, first takes two arguments, the collection or array, and the number you feed it.  If no argument is fed for n, then it will just return the first item in the array, else, it will start at the zero index, and stop at which ever number is fed in for n.

It literally reads like this:  return this value : if n is equal to undefined then return the first item in the array, if it's not equal to undefined, then slice the array starting with index 0 and ending at index n.

If you're not sure how slice works in javascript, then google it.  If you don't know how to call out items in an array using bracket notation, then google that too.   If the conditional statement above is confusing to you, note you could write it out using if/else statements, but the above is easier and cleaner.  Here's the same function written in if/ else statements:

_.first = function(array, n){

  if(n === undefined){
    return array[0];
  }
  else{
    return array.slice(0, n);
  }
}

Rebuild Underscore's identity function

var _ = {};


Identity is probably the easiest one.  It will be useful later on when a function is required as an argument but not given.  


_.identity = function(val) {
  return val;

}

This simply returns whatever value it is given.  

If this confuses you, then these exercises are probably going to be way over your head.  Just sayin.. 


Here's an example:  

var test = _.identity("hello");

console.log(test);

The console will display = hello

Recursion

Recursion:

If Mike could create a function, that then calls the function,that tells Mike to give himself one dollar, then Mike would have infinite wealth.  

Here's how it works.  Mike's function, instructs Mike to call his function, which gives himself one dollar.  That call then calls Mikes function, which calls Mike's function, which calls Mike's function, which calls Mike's function, ..... infinity. 

Okay.  

function power(base, exponent) {
  if (exponent == 0)
    return 1;
  else
    return base * power(base, exponent - 1);
}

console.log(power(2, 3));

8 will be returned to the console.  

How does this work?  

It's pretty simple, but you might need to take a pencil and paper to understand it.

Step 1 : the function power is called in the console.log function.  It's fed two arguments, 2 and 3.  So the base is 2, and the exponent is 3.  Exponent does not equal zero, so we move on to the else statement.  The else statement says to return 2 times the value of calling the function power with arguments of 2 and 2.

Step 2: the function power is called as I said in the last line of step 1, with base equal to 2 and exponent equal to 2.  So, exponent does not equal zero, so we move onto the else statement.  The else statement says to return 2 times the value of calling the function power with arguments of 2 and 1.

Step 3 : the function power is called as I said in the last line of step 2, with base equal to 2 and exponent equal to 1.  So, exponent does not equal zero, so we move onto the else statement.  The else statement says to return 2 times the value of calling the function power with arguments of 2 and 0.

Step 4 : the function power is called as I said in the last line of step3, with base equal to 2 and exponent equal to 0.  So, exponent does equal zero, so this particular function returns 1.  Where does it return 1 to?  It returns 1 to the function that called it, which is the function in step 3.

Step 5 : That means the function in step 3 now has a value for where it called the power function, it has the returned value of 1.  So we get 2 times 1 which is then returned to the function that called it, which is the function in step 2.

Step 6 : So, the function in step 2 now has a value where it called the power function, and that value is 2.  So the function in step 2 multiplies 2 by 2, which is 4,  and returns that value to the function that called it, which is the function in step 1.  

Step 7 : now we have a value where it says base * _______.  The value sitting there is 4.  2 times 4 is 8.  The value of 8 gets returned to the caller of power, which in this case is the console.log function, so 8 is printed to the console.