Bonfire: Factorialize a Number

Factorialize a Number – great JavaScript coding challenge from free online full-stack bootcamp FreeCodeCamp. This was a tough one that required a couple hours to figure out. Taking a break from these challenges really makes them harder when you start back up!

Challenge:

Return the factorial of the provided integer.

If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.

Factorials are often represented with the shorthand notation n!

For example: 5! = 1 * 2 * 3 * 4 * 5 = 120


Solution:

function factorialize(num) {
  var total = 1;
  for (var i = 0; num > i; i++) {
    total = total * (i+1);
  }
  return total;
}

factorialize(5);
Advertisements

Bonfire: Reverse a String

Completing the Bonfire: Reverse a String on FreeCodeCamp

Challenge:

Reverse the provided string.

You may need to turn the string into an array before you can reverse it.

Your result must be a string.

Use: .reverse()
.split()
.join()


Solution:

function reverseString(str) {
  var str = str.split("").reverse().join("");
  return str;
}

reverseString("hello");

Bonfire: Chunky Monkey

The Chunky Monkey Bonfire took me about 40 minutes to solve. It was a real tough one and I had to Google to find some help.  I used the .push() method and the .slice() method. Came across Wulkan’s blog in my search and his solution to the challenge really helped me find mine. Thanks Wulkan!

The Challenge:

Bonfire: Chunky Monkey

Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array.

For example:
chunk(["a", "b", "c", "d"], 2) should return [["a", "b"], ["c", "d"]]
chunk([0, 1, 2, 3, 4, 5], 3)
 should return [[0, 1, 2], [3, 4, 5]]


The Solution:

function chunk(arr, size) {

  var newArr = [];
  for (i = 0; i < arr.length;) {
    newArr.push(arr.slice(i, i += size));
  }
  return newArr;
 
}

chunk(["a", "b", "c", "d"], 2, "");

I was having trouble with controlling the incrementation in the ‘for loop’ so I just took out the ‘i++’ and it worked!

Bonfire: Truncate a string

Using .splice() to solve FreeCodeCamp‘s Bonfire: Truncate a string.

The Challenge:

Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a “…” ending.

Note that the three dots at the end add to the string length.

Try it yourself before viewing my solution! If you use Google Chrome as your browser, you can right click and Inspect Element to use the console to test your code.


The Solution:

function truncate(str, num) {

  if (str.length > num) {
    return str.slice(0, (num-3)) + "...";
  } else {
    return str;
  }
}

truncate("A-tisket a-tasket A green and yellow basket", 11, "");
truncate("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length);

Bonfire: Repeat a String Repeat a String

Three in a row! Are these challenges easier than the first Bonfires or is all this training really starting to improve my programming brain? (I hope it’s the latter!)

This is my solution to FreeCodeCamp‘s Bonfire: Repeat a string repeat a string. This one was much easier to complete as you only need to check if the num argument is less than zero.

The Challenge:

Repeat a given string (first argument) n times (second argument). Return an empty string if n is a negative number.

The Solution:

function repeat(str, num) {

  if (num < 0) {
    return "";
  } else {
    return str.repeat(num);
  }
}

repeat("*", 3, "");
repeat("abc", 3, "");

Bonfire: Confirm the Ending

On a roll! Just did two FreeCodeCamp Bonfire Algorithms back-to-back. This one took me about 20 minutes. Use .substr() method.

The Challenge:

Check if a string (first argument) ends with the given target string (second argument).

The Solution:

function end(str, target) {
  var lastLetter = str.substr(-(target.length), target.length);
  if (target === lastLetter) {
    return true;
  } else {
    return false;
  }
}
end("He has to give me a new name", "name")
end("Bastian", "n", "");

Use console.log(lastLetter); after defining the variable lastLetter to see what is printing. It really helps to see what is going wrong with your code.

Bonfire: Return Largest Numbers in Arrays

Took me about an hour, but I finally passed the Bonfire: Return Largest Numbers in Arrays from FreeCodeCamp’s Algorithm section. Whoohoo!

The Challenge:

Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.

The Solution:

function largestOfFour(arr) {

  var newArray = [];
  var x = 0;
  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr[i].length; j++) {
      if (x < arr[i][j]) {
        x = arr[i][j];       
      }
    }
   newArray.push(x);
    x = 0;
  }
  return newArray;
}


largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

There is a much easier way, by using the math.max.apply method, but I didn’t choose to use it.

JavaScript String Manipulation Challenge

Going through Udacity‘s free online JavaScript course, I came across this challenge:

Your Challenge

If given a string of a two word name formatted with any mix of capitalization, can you manipulate the string to ensure the first name has a capital first letter and the last name is totally capitalized? Assume there’s a space between the names. For instance, turning a string like "cAmEROn PittMAN" into "Cameron PITTMAN". Your answer should be a single string saved to the variable called finalName.

Take a look at MDN’s documentation on string methods for clues, then try it yourself!

==============================================

My solution:

Unnamed QQ Screenshot20151001081020

The breakdown:

Line 1: var name = "AlbERt EINstEiN";

A variable called name has the value AlbErt EINstEiN. All lines in JS have to end with a semicolon so that the system knows it is the end of a line.

Line 3: function nameChanger(oldName) {

A function called nameChanger will take in an argument called oldName. All functions will start with a curly brace after the function name.

Line 4: var finalName = oldName;

A variable called finalName has the value of oldName.

Line 6:  var nameArray = oldName.split(' ');

The value of oldName is taken and a .split() method is called to make a string array from oldName. The array values are created using a ‘ ‘ (space) as the separator. For example, if
oldName = "AlbERt EINstEiN";
oldName.split(' ');
would equal have the values: [AlbERt', 'EINstEiN']

Then these values would be saved in a new variable called nameArray.

Line 7: var lastName = nameArray[1].toUpperCase();

The second value (since arrays start with 0, nameArray[1] would be the second value) in nameArray is changed to all uppercase letters. This is stored in a new variable called lastName. For example, if
nameArray = ['AlbERt', 'EINstEiN']
nameArray[0] = ['AlbERt']
nameArray[1] = ['EINstEiN']
nameArray[1].toUpperCase();
would be equal to ['EINSTEIN']
var lastName = ['EINSTEIN']

Line 8: var firstName = nameArray[0].toLowerCase().split('');

The first value in nameArray is changed to all lowercase letters. Then the letters will be separated from each other since the .split(”) is an empty string. So if
nameArray[0] = ['AlbERt'],
firstName = ['a', 'l', 'b', 'e', 'r', 't'];

Line 9: var firstLetter = firstName.splice(1).join('');

firstName will start the array from the second value (1) and then the array will be joined together to form one string. For example:
firstName = ['a', 'l', 'b', 'e', 'r', 't'];
firstName.splice(1) = ['l', 'b', 'e', 'r', 't'];
firstLetter = ['l', 'b', 'e', 'r', 't'].join('') = ['lbert'];

.splice() method
.join() method

Line 10: var firstNameJoin = firstName[0].toUpperCase() + firstLetter;

The first value in the array firstName is changed to uppercase, then added to the value of firstLetter.
firstName = ['a', 'l', 'b', 'e', 'r', 't'];
firstName[0] = ['a'];
firstName[0].toUpperCase() = ['A']
firstNameJoin = ['A'] + ['lbert'] = ['Albert'];

Line 12: finalName = firstNameJoin + ' ' + lastName;

finalName = [‘Albert’] + [‘ ‘] + [‘EINSTEIN’] = [‘Albert EINSTEIN’];

Line 14: return finalName;

Saves the value of finalName.

Line 18: console.log(nameChanger(name));

'console.log' will show on the screen whatever is in the parentheses. Inside the parentheses, the function we made, nameChanger, is called with a parameter inserted called ‘name‘. ‘name‘ is the name of the variable that was defined in the beginning on Line 1.

There are many other ways to find a workable solution, so don’t think you HAVE to do it this way.

Github Pages

Did you know that you can use Github Pages to host your websites live?

It’s free and easy to setup whether you are on Windows or Mac.

There are two different types of Github Pages, one for Users & Organizations, and one for Projects. Each User & Organization can only have ONE Github Page. With each Github Page, you can have unlimited Project Pages. Project Pages are located as a subpath to the User Page (http://username.github.io/projectpage). To get more information about the similarities and differences, click here.

To set up a User Page, you first will need to create a new repository called username.github.io (where username is your Github username). This will be the URL of your website.

Then follow the instructions located here: https://pages.github.com/

To read about setting up a custom domain, go here.
Adding a CNAME file to your repository (for custom domains), go here.

Cash Register lesson in Codecademy

While completing the Cash Register (step 3/7) exercise on Codecademy’s JavaScript course, I came across this answer from tony de araujo that helped me understand how the code I was writing was executed.

alt text

On line 29 we call the scan method from object cashRegister and pass in an item called “eggs”

“eggs” gets inserted into the function via the input parameter item which is an interface.

For this function call instance, “eggs” becomes the value of variable item.

The switch switches the case “eggs” to true, which triggers the function add on line 4 and the value of 0.98 is added to variable total on line 2.

In truth, the program only starts executing at line 29. All the stuff above line 29 is preliminary data that JavaScript will use once it starts running the program. What I mean is that JavaScript scans the program once and it makes an inventory of what is supposed to do. Then, it starts running at line 29 and downward.

Source: https://www.codecademy.com/forum_questions/54b129f79113cbb05a0035e4