Tools => developer => new snippet
Delete everything between the first brackets after CDATA.
Fill in with what you want to populate on the page.
Uncomment tabtrigger line. Change the word between the tabTrigger tags to be any word you want. I'll refer to this as your special word.
Save file.
Give the file a name, and end the file name with .sublime-snippet
Boom, you're done. Open a new file. Type your special word and press tab. Boom!
Thursday, September 1, 2016
Monday, August 29, 2016
JS exercises - Palindrome
Write a recursive JS function to determine if a string is palindrome or not.
Return true if it is a palindrome, and false if it is not a palindrome.
I used regex to first get rid of the spaces and any puntuation.
For example :
Madam, I'm Adam - should return true, because it's the same backwards as forwards.
Answer in the comments.
Return true if it is a palindrome, and false if it is not a palindrome.
I used regex to first get rid of the spaces and any puntuation.
For example :
Madam, I'm Adam - should return true, because it's the same backwards as forwards.
Answer in the comments.
JS recursive exercise
This one feels like it's going to be very easy.
Write a recursive program to determine whether a number is even or odd.
What is wrong with just saying num % 2 === 0 ?
Yeah, I don't know why you would spend time doing this but:
function is_even_recursion(number){
if (number < 0) {
number = Math.abs(number);
}
if (number === 0) {
return true;
}
if (number === 1) {
return false;
}
else {
number = number - 2;
return is_even_recursion(number);
}
}
It works!
Write a recursive program to determine whether a number is even or odd.
What is wrong with just saying num % 2 === 0 ?
Yeah, I don't know why you would spend time doing this but:
function is_even_recursion(number){
if (number < 0) {
number = Math.abs(number);
}
if (number === 0) {
return true;
}
if (number === 1) {
return false;
}
else {
number = number - 2;
return is_even_recursion(number);
}
}
It works!
JS recursive function exercise
If I hear the word fibonacci again, I'm going to vomit. So, I'll skip the fib question from the website that I'm stealing all these problems from: http://www.w3resource.com/javascript-exercises/javascript-recursion-functions-exercises.php
I'm sorry, I am just so sick of Fibs and freaking fizz-buzz. Are there no other examples out there?
Well, maybe there just is a reason, so let's do the Fib problem after all. Just deal with it:
Write a recursive program to get the first n Fib numbers.
For example, fib(7) would output [1,1,2,3,5,8,13];
However, this is worth doing and seeing the answer in the comments, because this is probably the smartest solution to this problem that I've ever seen.
I'm sorry, I am just so sick of Fibs and freaking fizz-buzz. Are there no other examples out there?
Well, maybe there just is a reason, so let's do the Fib problem after all. Just deal with it:
Write a recursive program to get the first n Fib numbers.
For example, fib(7) would output [1,1,2,3,5,8,13];
However, this is worth doing and seeing the answer in the comments, because this is probably the smartest solution to this problem that I've ever seen.
Recursive reflections
If I call an inner function recursively, will it remember the setting of variables in an outer function?
The answer is yes!
For example:
var tester = function(a){
b = 0;
function poop(){
if(a === b){
return a;
}
console.log(b);
b++;
poop();
}
poop();
}
var maple = tester(5);
0
1
2
3
4
will print to the console. I suppose this is a recursive function that produces only side effects and returns nothing.
The answer is yes!
For example:
var tester = function(a){
b = 0;
function poop(){
if(a === b){
return a;
}
console.log(b);
b++;
poop();
}
poop();
}
var maple = tester(5);
0
1
2
3
4
will print to the console. I suppose this is a recursive function that produces only side effects and returns nothing.
JS recursive exercise 5
Write a recursive program to compute the exponent of a number:
8^3 = 8 * 8 * 8 = 512
This one is kind of easy, if you've finished the others.
You're just multiplying, 8 by all the other eights and returning the number.
Don't make this harder than it needs to be.
Once you've multiplied one eight, you've got one less exponent, etc...
8^3 = 8 * 8 * 8 = 512
This one is kind of easy, if you've finished the others.
You're just multiplying, 8 by all the other eights and returning the number.
Don't make this harder than it needs to be.
Once you've multiplied one eight, you've got one less exponent, etc...
JS recursive exercise 4
Write a recursive program to sum up an array.
Easily done with reduce, but more fun with recursion:
var sumMeUp = [3,4,5,6];
output should equal 18
Hint: Do you want a hint? If so, read down below:
pop it + everything else in the array.
Just keep popping.
Easily done with reduce, but more fun with recursion:
var sumMeUp = [3,4,5,6];
output should equal 18
Hint: Do you want a hint? If so, read down below:
pop it + everything else in the array.
Just keep popping.
Recursion exercise 3
By the way, I stole these problems from : http://www.w3resource.com/javascript-exercises/javascript-recursion-functions-exercises.php
Write a recursive function to get integers in a range.
For example, range(2,7) will return [3,4,5,6];
Yes, that is returned in an array.
Answer is in the comments.
Write a recursive function to get integers in a range.
For example, range(2,7) will return [3,4,5,6];
Yes, that is returned in an array.
Answer is in the comments.
Recursion exercise 2
Write a recursive JS program to find the greatest common divisor of two numbers.
Do you have no idea what the greatest common divisor is? Khan Academy video
This problem is really easy, if you understand the Math part of the problem very well.
If the lower number of the two can evenly divide into the larger number, then that is the greatest common divisor. Just return that number.
Else, what's the remainder from dividing the larger number by the smaller number?
Will that number divide evenly into the smaller number?
No?
Well, then what's the remainder from dividing the smaller number by that number?
Will that remainder divide equally into the smaller number? If yes, you've found your answer.
For example,
36, 96 - What's the greatest common divisor?
Step 1 - will 36 go into 96 evenly? No. Remainder = 24.
Step 2 - will 24 go into 36 evenly? No. Remainder = 12.
Step 3 - will 12 go into 36 evenly. Yes. Answer = 12.
12 is the greatest common divisor of 36 and 96.
Answer is in the comments.
Do you have no idea what the greatest common divisor is? Khan Academy video
This problem is really easy, if you understand the Math part of the problem very well.
If the lower number of the two can evenly divide into the larger number, then that is the greatest common divisor. Just return that number.
Else, what's the remainder from dividing the larger number by the smaller number?
Will that number divide evenly into the smaller number?
No?
Well, then what's the remainder from dividing the smaller number by that number?
Will that remainder divide equally into the smaller number? If yes, you've found your answer.
For example,
36, 96 - What's the greatest common divisor?
Step 1 - will 36 go into 96 evenly? No. Remainder = 24.
Step 2 - will 24 go into 36 evenly? No. Remainder = 12.
Step 3 - will 12 go into 36 evenly. Yes. Answer = 12.
12 is the greatest common divisor of 36 and 96.
Answer is in the comments.
Recursion exercises 1
Write a recursive JS program to calculate the factorial of a number.
For example. 5! = 5 * 4 * 3 * 2 * 1 = 120
One easy way to set this up is to create a base case that returns 1, once the decremented number reaches 1. By decremented number, I mean the recursive call the number being fed is decremented each time until 1 is reached. Then all the numbers come back and multiply themselves together.
Since this first one is easy, I'm going to walk through it, incase you're unfamiliar with recursion :
var factorial = function(num){
if(num === 1){
return 1;
}
return num * factorial(num -1);
}
var maple = factorial(9);
maple will equal 362880
First, the factorial function takes 9 as an argument, checks to see if it is equal to 1, it's not, it returns the value of 9 multiplied by the value received from calling the function factorial on 8. This function is just calling itself rather than another function. That value is then calculated by feeding 8 to another instance of factorial, it checks to see if 8 is equal to 1, it's not, so it returns the value of 8 multiplied by the value of calling factorial and feeding it 7.
This goes on and on until 1 is reached. At this point the function returns 1 as the value. That means that the function that had multiplied 2 by the value of factorial being fed 1, now has received the value from factorial being fed 1, that value is 1. So 2 will be multiplied by 1, and that equals 2, and that will be returned to the function before it, that had called factorial and fed it a 3 and had returned the value 3 multiplied by the value of factorial fed 2. Well, that factorial fed 2 now has a value, and that value is 2. So, 3 times 2 is six, and this value gets returned to the function that is waiting for that value, and so on, and so on, until we reach the very first function that started all this.
It may take a while to wrap one's head around.
For example. 5! = 5 * 4 * 3 * 2 * 1 = 120
One easy way to set this up is to create a base case that returns 1, once the decremented number reaches 1. By decremented number, I mean the recursive call the number being fed is decremented each time until 1 is reached. Then all the numbers come back and multiply themselves together.
Since this first one is easy, I'm going to walk through it, incase you're unfamiliar with recursion :
var factorial = function(num){
if(num === 1){
return 1;
}
return num * factorial(num -1);
}
var maple = factorial(9);
maple will equal 362880
First, the factorial function takes 9 as an argument, checks to see if it is equal to 1, it's not, it returns the value of 9 multiplied by the value received from calling the function factorial on 8. This function is just calling itself rather than another function. That value is then calculated by feeding 8 to another instance of factorial, it checks to see if 8 is equal to 1, it's not, so it returns the value of 8 multiplied by the value of calling factorial and feeding it 7.
This goes on and on until 1 is reached. At this point the function returns 1 as the value. That means that the function that had multiplied 2 by the value of factorial being fed 1, now has received the value from factorial being fed 1, that value is 1. So 2 will be multiplied by 1, and that equals 2, and that will be returned to the function before it, that had called factorial and fed it a 3 and had returned the value 3 multiplied by the value of factorial fed 2. Well, that factorial fed 2 now has a value, and that value is 2. So, 3 times 2 is six, and this value gets returned to the function that is waiting for that value, and so on, and so on, until we reach the very first function that started all this.
It may take a while to wrap one's head around.
Thursday, August 18, 2016
Sorry to throw this in the middle, but how the heck do you use bind? What is bind?
var dog = {
a:5,
b:10,
c:11
}
var cat = {
a:50,
b:100,
c:110
}
var fish = {
a:500,
b:1000,
c:1100
}
var bird = {
a:5000,
b:10000,
c:11000
}
var mammoth = {
a:50000,
b:100000,
c:110000
}
var howMany = function(){
console.log(this.a);
}
var howManydogs = howMany.bind(dog);
var howManyCats = howMany.bind(cat);
var howManyFish = howMany.bind(fish);
var howManybirds = howMany.bind(bird);
var howManyMammoths = howMany.bind(mammoth);
howManyMammoths(); will equal 50000
howManydogs(); will equal 5
And that's all there is to it. Bind simply gives a context to 'this'.
a:5,
b:10,
c:11
}
var cat = {
a:50,
b:100,
c:110
}
var fish = {
a:500,
b:1000,
c:1100
}
var bird = {
a:5000,
b:10000,
c:11000
}
var mammoth = {
a:50000,
b:100000,
c:110000
}
var howMany = function(){
console.log(this.a);
}
var howManydogs = howMany.bind(dog);
var howManyCats = howMany.bind(cat);
var howManyFish = howMany.bind(fish);
var howManybirds = howMany.bind(bird);
var howManyMammoths = howMany.bind(mammoth);
howManyMammoths(); will equal 50000
howManydogs(); will equal 5
And that's all there is to it. Bind simply gives a context to 'this'.
Saturday, August 13, 2016
Cool javascript functions part 2
swaparoo(a, b){
var temp = a;
a = b;
b = temp;
}
x = 1;
y = 2;
swaparoo(x,y);
x = ?
Answer is in the comments!
var temp = a;
a = b;
b = temp;
}
x = 1;
y = 2;
swaparoo(x,y);
x = ?
Answer is in the comments!
Cool javascript functions part 1
function happy(a){
a = null;
}
x = [];
happy(x);
x = ?
What will x equal?
The answer is in the comments.
a = null;
}
x = [];
happy(x);
x = ?
What will x equal?
The answer is in the comments.
Saturday, July 23, 2016
Coding Challenge: Telephone number check
Oh, I know it's boring and horrible, but let's make a function that verifies the telephone number entered by the user is in a correct format.
Here are the rules for a correct format:
Here are the rules for a correct format:
telephoneCheck("555-555-5555") should return true.telephoneCheck("1 555-555-5555") should return true.telephoneCheck("1 (555) 555-5555") should return true.telephoneCheck("5555555555") should return true.telephoneCheck("555-555-5555") should return true.telephoneCheck("(555)555-5555") should return true.telephoneCheck("1(555)555-5555") should return true.telephoneCheck("555-5555") should return false.telephoneCheck("5555555") should return false.telephoneCheck("1 555)555-5555") should return false.telephoneCheck("1 555 555 5555") should return true.telephoneCheck("1 456 789 4444") should return true.telephoneCheck("123**&!!asdf#") should return false.telephoneCheck("55555555") should return false.telephoneCheck("(6505552368)") should return falsetelephoneCheck("2 (757) 622-7382") should return false.telephoneCheck("0 (757) 622-7382") should return false.telephoneCheck("-1 (757) 622-7382") should return falsetelephoneCheck("2 757 622-7382") should return false.telephoneCheck("10 (757) 622-7382") should return false.telephoneCheck("27576227382") should return false.telephoneCheck("(275)76227382") should return false.telephoneCheck("2(757)6227382") should return false.telephoneCheck("2(757)622-7382") should return false.telephoneCheck("555)-555-5555") should return false.telephoneCheck("(555-555-5555") should return false.telephoneCheck("(555)5(55?)-5555") should return false.
If a country code is used, it must be 1.
Good luck. Solution is in the comments.
Monday, July 11, 2016
Yes you can use CSS to post an image
background-image:url(http://whateverthepictureurlis.com);
This is cool because you can make a div have a background of the picture, then you can easily type on top of it and not have to worry about responsiveness.
This is cool because you can make a div have a background of the picture, then you can easily type on top of it and not have to worry about responsiveness.
Sunday, July 10, 2016
Daddy Object
The Big Daddy of all in Javascript is Object.prototype
Once upon a time daddy was created:
var daddy = {
apples : 10
}
Daddy has only one variable, apples with a value of ten.
daddy; in a repl will return {apples: 10}
Daddy actually has more properties than just the one property of apple, you just can't see them, they've been inherited from the Big Daddy of all objects, the Object.prototype. Big Daddy Object.prototype contains methods that all children objects have access to.
So, daddy was created from Big Daddy, and then one say daddy had a son, name son object;
var son = Object.create(daddy);
Booooom, son is born.
son; run in a repl will return {};
This is because it's an empty object. However son.apples; run in a repl will return 10.
When the browser looks for a property named apples in son, and doesn't find one, it looks up the chain, the Big Daddy chain, or the prototype chain, to the next in line, which is daddy. Booom, inside daddy it finds a variable named apples, and so returns 10.
Once upon a time daddy was created:
var daddy = {
apples : 10
}
Daddy has only one variable, apples with a value of ten.
daddy; in a repl will return {apples: 10}
Daddy actually has more properties than just the one property of apple, you just can't see them, they've been inherited from the Big Daddy of all objects, the Object.prototype. Big Daddy Object.prototype contains methods that all children objects have access to.
So, daddy was created from Big Daddy, and then one say daddy had a son, name son object;
var son = Object.create(daddy);
Booooom, son is born.
son; run in a repl will return {};
This is because it's an empty object. However son.apples; run in a repl will return 10.
When the browser looks for a property named apples in son, and doesn't find one, it looks up the chain, the Big Daddy chain, or the prototype chain, to the next in line, which is daddy. Booom, inside daddy it finds a variable named apples, and so returns 10.
Wednesday, July 6, 2016
_.each, .forEach
I find it really frustrating that the native Javascript forEach does not iterate through objects.
The underscore each does, and I haven't used it, but apparently the jQuery each also does.
So what's a guy to do if you're too lazy to implement the underscore library.
Well, I suppose this will work for an object named obj:
Object.keys(obj).forEach(function(item){
console.log(obj[item]);
})
I'll probably update this in the future when I am smarter.
The underscore each does, and I haven't used it, but apparently the jQuery each also does.
So what's a guy to do if you're too lazy to implement the underscore library.
Well, I suppose this will work for an object named obj:
Object.keys(obj).forEach(function(item){
console.log(obj[item]);
})
I'll probably update this in the future when I am smarter.
Tuesday, July 5, 2016
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.
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
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.
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
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
};
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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;
}
_.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.
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.
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.
_.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.
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];
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.
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: '' } ]
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
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.
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.
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
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?
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?
Subscribe to:
Posts (Atom)