This is how you add a property to a pre-existing object:
var Car = function() {
this.wheels = 4;
};
// Only change code below this line.
var myCar = new Car();
myCar.engines = 1;
//Add the property "engines" to myCar, and make it a number.
The map method is a way to iterate through an array, here's an example of it's use, we added three to every item in the array:
//Use map to add three to each value in the array
var array = [1,2,3,4,5];
// Only change code below this line.
array = array.map(function(val){
return val+3;
});
The output would be [4, 5, 6, 7, 8].
Then we used reduce, which condenses the data in an array, in the case below adding every number and outputting the total:
var array = [4,5,6,7,8];
var singleVal = 0;
// Only change code below this line.
var singleVal = array.reduce(function(previousVal, currentVal){
return previousVal+currentVal;
});
This method, filter, will filter an array for desired data, in this case all numbers less than or equal to 5:
var array = [1,2,3,4,5,6,7,8,9,10];
// Only change code below this line.
array = array.filter(function(val) {
return val <= 5;
});
The output in this case would be [1,2,3,4,5]. That's cool.
The sort method will sort an array numerically or alphabetically:
var array = ['beta', 'alpha', 'charlie'];
// Only change code below this line.
array = array.sort();
Output would be ["alpha","beta","charlie"].
The .reverse function will reverse an array, like so:
var array = [1,2,3,4,5,6,7];
// Only change code below this line.
array.reverse();
Output would be [ 7, 6, 5, 4, 3, 2, 1 ].
The .concat() function will concatenate two functions, like so:
var array = [1,2,3];
var concatMe = [4,5,6];
// Only change code below this line.
array = array.concat(concatMe);
Output would be [ 1, 2, 3, 4, 5, 6 ].
The .split function will split a string into an array, like so:
var string = "Split me into an array";
// Only change code below this line.
var array = string.split(' ');
Output would be [ "Split", "me", "into", "an", "array" ]. Interestingly, if we use this instead (we remove the space between the parentheses):
var string = "Split me into an array";
// Only change code below this line.
var array = string.split('');
The output then becomes:
[ "S", "p", "l", "i", "t", " ", "m", "e", " ", "i", and so on until every letter and space has its own index in the array]
That's cool. Then if you do this:
var string = "Split me into an array";
// Only change code below this line.
var array = string.split("me");
It will output this:
[ "Split ", " into an array" ]
That's a really neat function.
The .join() method joins each element of an array with whatever delimiter you specify (in this case, none), for example:
var joinMe = ["Split","me","into","an","array"];
// Only change code below this line.
joinMe = joinMe.join("");
The output from the code above will be "Splitmeintoanarray". Here's another example, with an 8 as the delimiter:
var joinMe = ["Split","me","into","an","array"];
// Only change code below this line.
joinMe = joinMe.join("8");
The output would be "Split8me8into8an8array". That's interesting. Oh, by the way, I'm on section 6 of 17 now! Check it out:
This is great! That said, it's getting tougher now! :)
This function reverses a string:
function reverseString(str) {
var theArray = str.split('');
var newArray = theArray.reverse();
str = newArray.join("");
return str;
};
reverseString("hello", "");
It does so by splitting the string into individual characters on line 2 and indexing them in an array, reversing the characters in the array on line 3, then joining the characters in the array on line 4.
The output is "olleh".
This does the same thing:
function reverseString(str) {
str = str.split('').reverse().join("");
return str;
};
reverseString("hello", "");
Again, the output is "olleh".
I remembered that you could chain methods. My second solution is much cleaner. I created this formula to factorialize a number:
function factorialize(num) {
var x = num - 1;
while (x > 0) {
num = num * (x)
x = x- 1;
}
if (num === 0 || num === 1) {
return 1;
}
return num;
}
factorialize(5, '');
The output is 120. The num === 1 is not necessary, because if num is 1, the formula will simply return it anyways, so this is actually better:
function factorialize(num) {
var x = num - 1;
while (x > 0) {
num = num * (x)
x = x- 1;
}
if (num === 0) {
return 1;
}
return num;
}
factorialize(5, '');
The output is 120 again. O.k., the next Bonfire challenge is to check for a palindrome. I'm on Bonfire challenge number 4 of 12 in the Basic Algorithm Scripting section. I'm going to take a quick look at the challenge, follow that with a short break to cook up some lunch, and then I'll be back at it.
O.k., I got really into the problem and skipped lunch. This is what I have so far:
function palindrome(str) {
// Good luck!
str = str.toLowerCase();
str = str.replace(/[^A-z_0-9:]+/g,"");
if (str.split('').reverse().join('') === str) {
return true;
}
else return false;
}
Still working on it...
O.k., now I'm taking a break for lunch! O.k., I'm back. I'm still working on this problem, and the key to it is the regular expressions, I'm not too familiar with them, so I'm going to take a moment to browse some info on regular expressions.
I learned that this is a negative expression filter: ^. So, for example:
[^a-z]
Will match any character NOT in the range of a-z. Interesting.
I got it! Here's my final answer:
function palindrome(str) {
// Good luck!
str = str.toLowerCase().replace(/[^a-z0-9]/g,"")
if (str.split('').reverse().join('') === str) {
console.log(str);
return true;
}
return false;
}
palindrome("My age is 0, 0 si ega ym.");
The output for the above is true, and that output is based on the function turning the input into "myageis00siegaym".
Woohoo! Okay, for the next challenge, we had to return the length of the largest word in a string. Here's my code!
function findLongestWord(str) {
myArray = str.split(" ");
var newArray = [];
for (i = 0; i < myArray.length; i++) {
newArray[i] = myArray[i].length;
}
str = Math.max(...newArray);
return str;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
The output for that one is 6. Let's see if I do it without using Math.max. Got it, so here's a different way to do it, without Math.max:
function findLongestWord(str) {
myArray = str.split(" ");
var newArray = [];
for (var i = 0; i < myArray.length; i++) {
newArray[i] = myArray[i].length;
}
var bigWord= newArray[0];
for (var j = 0; j < newArray.length; j++){
if (bigWord < newArray[j]) {
bigWord = newArray[j];
}
}
return bigWord;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
The result for that would be 6, as jumped is the longest word. And here's the code solution posted in our wiki, it's much cleaner than mine, I like it, so I'm saving it:
function findLongestWord(str) { var words = str.split(' '); var maxLength = 0; for (var i = 0; i < words.length; i++) { if (words[i].length > maxLength) { maxLength = words[i].length; } } return maxLength; }
That's so elegant. I like it. I'm going over it again, I think it's a good one to memorize, it's neat how the maxLength variable is set to 0, and then it is replaced by the first item in the array, every time, because the first item will always be greater than zero. Then, every time after that, it will only be replaced if the next item in the array is greater than the current value of the variable...it's great!
The next problem asks me to capitalize the first letter of every word in a string. Working on it. This was my first attempt:
function titleCase(str) {
str = str.toLowerCase();
str = str.replace(/\b./g, function(m){return m.toUpperCase();});
return str;
}
titleCase("I'm a little tea pot", "");
It works in most scenarios, but the weakness is that it capitalizes letters after things like "-" or an apostrophe, so it doesn't work in that scenario. Going back to the drawing board! O.k., I've been working at it a while now, I had to erase everything and start from scratch. The key to this one was the char.At() method, which can target a character in a string by the index number in the parentheses. Since we are targeting the first letter of each word in the string, once we break the string into an array by using .split(' '), each first letter can then be targeted by charAt(0). Here's what I've got:
function titleCase(str) {
str = str.toLowerCase().split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = str[i].replace(str[i].charAt(0), str[i].charAt(0).toUpperCase());
}
str = str.join(' ');
return str;
}
titleCase("I'm a little tea pot", "");
I have to make it lowercase first in case there's scenarios where someone capitalizes a random letter, .toLowerCase will undo that. The problem started out with the hint to use string.charAt, and I should have followed that line of thought from the beginning instead of going for the regular expression solution, but I did learn quite a bit more about regular expressions, so that was a worthwhile use of my time!
By the way, this is how to target a value inside a sub-array:
myArray[2][1]
That would target the element with an index value of 1 inside of the element with an index value of 2. For the next problem, we had to find the largest number in four arrays and make a new array with them. Here's what I did:
function largestOfFour(arr) {
var testNum1 = 0;
var testNum2 = 0;
var testNum3 = 0;
var testNum4 = 0;
var arr1 = arr[0];
var arr2 = arr[1];
var arr3 = arr[2];
var arr4 = arr[3];
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] > testNum1) {
testNum1 = arr1[i];
}
}
for (var i = 0; i < arr2.length; i++) {
if (arr2[i] > testNum2) {
testNum2 = arr2[i];
}
}
for (var i = 0; i < arr3.length; i++) {
if (arr3[i] > testNum3) {
testNum3 = arr3[i];
}
}
for (var i = 0; i < arr4.length; i++) {
if (arr4[i] > testNum4) {
testNum4 = arr4[i];
}
}
var finalArray = [testNum1, testNum2, testNum3, testNum4];
return finalArray;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");
That worked, but let's see if there's a way to cycle through them with one for loop instead of four...
I did it!!!
function largestOfFour(arr) {
var x = 0;
var finalArray = [];
for (var j = 0; j < arr.length; j++) {
for (var i = 0; i < arr[j].length; i++) {
if (arr[j][i] > x) {
x = arr[j][i];
}
}
finalArray.push(x);
x = 0;
}
return finalArray;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");
I remembered in Mark Myers' book, how we nested for loops, and I applied that here, and it worked. I'm pretty proud of that one. :)
I think I will do that one again tomorrow to hammer again on the concept of nesting for loops and also on the concept of finding the largest value in an array. That problem goes over both scenarios in one, so it's a good learning experience.
The code for my next problem checked if a given string (the second parameter) matched the last part of another string (the first parameter). Here's my code:
function end(str, target) {
targLength = target.length;
lastString = str.substr(-targLength);
console.log(lastString);
if (target === lastString) {
return true;
}
else return false;
}
end("Bastian", "n", "");
It works. :)
That's the first time I use the .substr method. It's interesting, but I need more practice with it to fully utilize it.
This is where I'm at now:
It took 11 hours of solid coding today, but I finished Object Oriented and Functional Programming and got halfway through Basic Algorithm Scripting!
I'm spending the day with my girl tomorrow, but I'll see if I can squeeze in some hours, I love the feeling of accomplishment I get when I put in the time and see the fruits of my labor. :)
Well, I've got two hours left in the day and I felt like continuing, so...the next problem required me to repeat a string a certain number of times (the first parameter is the string, the second parameter is the multiplier) and to return an empty string if the second parameter was a negative number.
Here's my code:
function repeat(str, num) {
if (num > 0) {
str = str.repeat(num);
return str;
}
else return '';
}
repeat("abc", 3, "");
That worked, but here's a solution I found on stack exchange for when the .repeat() method is not available:
function repeat(s, n){
var a = [];
while(a.length < n){
a.push(s);
}
return a.join('');
}
Next problem...
Next problem requires us to truncate a string if it is longer than the number given as the second parameter, and to return it with "..." added at the end (again, only if it is longer). Here's my code:
function truncate(str, num) {
if (str.length > num) {
var str = str.slice(0, num-3);
return str + "...";
}
else return str;
}
truncate("A-tisket a-tasket A green and yellow basket", 11, "");
If it is not longer, the string is simply returned unchanged. All right, tomorrow I'm starting on problem 11 of 16.
Good stuff!
SUMMARY OF CODING SKILLS
Total Treehouse Points: 5,385
Treehouse Points by Subject Matter (Miscellaneous not included):
HTML: 663
CSS: 1,599
Design: 1,193
Development Tools: 747
JavaScript: 1,120
Treehouse Ranking (%): "You have more total points than 94% of all students."
Treehouse Badge(s) Earned Today:
Treehouse Courses Completed:
How to Make a Website
HTML
CSS Foundations
CSS Layout Techniques
Aesthetic Foundations
Design Foundations
Adobe Photoshop Foundations
Adobe Illustrator Foundations (66% complete, switched focus from web design to web dev)
Git Basics
Introduction to Programming
JavaScript Basics
Codecademy (& other) Courses Completed:
HTML and CSS (Codecademy)
Design Foundations
Adobe Photoshop Foundations
Adobe Illustrator Foundations (66% complete, switched focus from web design to web dev)
Git Basics
Introduction to Programming
JavaScript Basics
Codecademy (& other) Courses Completed:
HTML and CSS (Codecademy)
Books Read or in Progress:
Completed: "Head First HTML and CSS," by E. Robson & E. Freeman (768 pgs.)
In Progress: "Head First JavaScript," by Eric Freeman and Elisabeth Robson (on pg. 56)
Completed: "A Smarter Way to Learn JavaScript," by Mark Myers (293 pgs., 89 chapters with 20 questions/problems per chapter, for a total of 1,780 coding questions/problems answered)
My Progress on The Odin Project:
1. Introduction to Web Development 100% Complete
2. Web Development 101 33% Complete
Note: Switched to FCC for the great online community and better updates/support.
Note: Switched to FCC for the great online community and better updates/support.
My Progress on Free Code Camp (FCC):
1. HTML5 and CSS Complete
2. Responsive Design with Bootstrap Complete
3. jQuery Complete
4. Basic JavaScript Complete
5. Object Oriented and Functional Programming Complete
6. Basic Algorithm Scripting On 11 of 16
7. Basic Front End Development Projects
8. Intermediate Algorithm Scripting
9. Upper Intermediate Algorithm Scripting
10. Automated Testing and Debugging
11. Advanced Algorithm Scripting
12. AngularJS
13. Intermediate Front End Development Projects
14. Git
15. Node.js and Express.js
16. MongoDB
17. Full Stack JavaScript Projects
After the FCC work above (estimated to take 800 hours), there are 800 more hours of coding projects on behalf of non-profits, which, in addition to contributing to the common good, provide us an opportunity to expand our networks and build a robust portfolio.
Hours Spent Coding Today: 12
Total Hours Coding: 641
No comments:
Post a Comment