Thursday, January 12, 2017

Eloquent Javascript Chapter 2 and 3 Exercises

I've been finding that Eloquent Javascript is a lot easier to understand and has more exercises to practice! I think my goal is to finish this book in its entirety, read through YDKJS for more guidelines, and then get started on the Harvard CS50X class online. 

1.
  • Looping a triangle
Write a loop that makes seven calls to console.log to output the following triangle:
#
##
###
####
#####
######
#######
It may be useful to know that you can find the length of a string by writing .length after it.
var abc = "abc";
console.log(abc.length);
// → 3
Most exercises contain a piece of code that you can modify to solve the exercise. Remember that you can click code blocks to edit them.

  • My Answer:
 for (var line = "#"; line.length < = 7; line += "#")
  console.log(line);
 
  • Explanation:  
- The For loop will run and add a "#" to the original line "#" until the line's length reaches 7 (less than 8)
- Then, we print the line to the console using console.log

 2.
  • FizzBuzz
Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead.
When you have that working, modify your program to print "FizzBuzz", for numbers that are divisible by both 3 and 5 (and still print "Fizz" or "Buzz" for numbers divisible by only one of those).
(This is actually an interview question that has been claimed to weed out a significant percentage of programmer candidates. So if you solved it, you’re now allowed to feel good about yourself.)

  • Correct Answer: 
 for (var n = 1; n <= 100; n++) {
  var output = "";
  if (n % 3 == 0)
    output += "Fizz";
  if (n % 5 == 0)
    output += "Buzz";
  console.log(output || n);
}
  •  Explanation:
- We need to loop a "for" that lists numbers starting from 1 to 100, adding 1 each time (n++)
- The output will be " " - a string like Fizz or Buzz
- If it is divisible by 3 with no remainder (if n% 3== 0), then it spits out "Fizz"
- If it is divisible by 5 with no remainder (if n%5== 0), then it spits out "Buzz"
- The console.log will put the output on the screen or the number ("n") if it is not a string ("Fizz", "Buzz", "Fizzbuzz")
- "Fizzbuzz" doesn't have to be added separatedly, because this for loop will check to see if n % 5 ==0 as well and add "Buzz" to the output if that is the case!

I found these links to be very helpful:
 http://ditam.github.io/posts/fizzbuzz/
and
 http://learnjswith.me/javascript-fizzbuzz/

  •   Another possible answer: 
I prefer switch statements to "if/else" and "for" loops, so I wrote one in switch mode


function switchFizzBuzz () {
for (var n=1 n<=100;n++) {
switch(true) {
    case n%3==0 && n%5==0: //both cases have to be true, and this runs first to check both cases
    console.log("Fizzbuzz");  //prints "Fizzbuzz"
    break;

    case n%3==0: 
    console.log("Fizz");
    break;

    case n%5==0:
   console.log("Buzz"); 
   break;

   default: 
   console.log(n); //this prints the number if none of the above cases are true
   break; 
}
}
}

3.
  • Chess Board
Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board.
Passing this string to console.log should show something like this:
 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #
When you have a program that generates this pattern, define a variable size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.

  • My Answer:
var size= 8
var board= " "

for (var y = 0; y < size; y++) {
  for (var x= 0; x < size; x++) {
    if ((x+y) % 2 == 0)
      board += " ";
    else
      board += "#";
  }
  board += "\n";
}
console.log(board);

Explanations:
- There are two variables here:
1. How many lines there are (the size): 8 down and 8 across
2. Whether the board says " " (a blank) or "#" (a hash). We start out with a blank " " string and add more onto it
- We need two "for" loops to run, one inside of another:
1. The first for loop will run until it gets to a total of 8 lines
2. the second for loop, located inside of the first one, will determine if there will be a "blank" or a "#"
- Inside of the second for loop, we can use an if/else to print more to the board as blank or # by seeing if it's an even space (row 1, space 1 is even and prints " " vs. row 1, space 2 is odd and prints "#")
- This keeps printing until x of "size" is reached
- Outside of the second for loop and inside of the first loop, we need to print a new line after 8 total characters (there are 4 "#" and 4 " " per line), we do this by "board +="\n"
- Finally, we print the board by console.log(board)
- We can also reset the variable size to equal any value other than 8 (perhaps, 10 lines of 10 characters (5 # and 5 blank)

Chapter 3 Notes:

Variable- Local v. Global- Some readings:
http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch1.md
https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/

Define LOCAL variables with var variablenamehere =
otherwise, it will OVERWRITE the global variable that was pre-defined

if you use var  x = blank rather than x = blank, x will remain local to that function

Example:

var x = "outside";

var f1 = function() {
  var x = "inside f1";
};
f1();
console.log(x);
// → outside

var f2 = function() {
  x = "inside f2";
};
f2();
console.log(x);
// → inside f2


  • Chapter 3, Problem 3: Bean Counting

Bean counting

You can get the Nth character, or letter, from a string by writing"string".charAt(N), similar to how you get its length with "s".length. The returned value will be a string containing only one character (for example, "b"). The first character has position zero, which causes the last one to be found at position string.length - 1. In other words, a two-character string has length 2, and its characters have positions 0 and 1.
Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters are in the string.
Next, write a function called countChar that behaves like countBs, except it takes a second argument that indicates the character that is to be counted (rather than counting only uppercase “B” characters). Rewrite countBs to make use of this new function.

This is the first answer:

function countBs(str){
  var num = 0;

  for(var i = 0; i < str.length; i += 1){
    if(str[i] === "B"){
      num += 1;
    }
  }
  return num;
}

Explanation:
We create the function countBs.
Inside, we set the first variable to 0 (first letter)
Then, we run a for loop (we start a 0 and keep looping until the end of the string)
While the for loop runs, if the string matches "B", we count 1
Then, we return the number of "B"s that the function found

This is the final answer:
function countBs(str){
  function countChar(str, "B");
}

function countChar(str, letter){
  var num = 0;

  for (var i = 0; i < str.length; i +=1){
    if (str[i] === letter) {
      num += 1;
    }
  }
  return num;
}

Explanation:
Next, we have to create a function that's similar to countBs, but we can pass in any letter for the function to count.
It looks the same, except we set the parameters to (str, letter) and inside, if === letter (that we pass in)
to run function countBs, we then run function countChar with "B" passed into the letter so that it knows to count "B"s.







Monday, January 9, 2017

01/09/2017 Javascript Exercises

Very useful reading on array methods:
https://www.bennadel.com/blog/1796-javascript-array-methods-unshift-shift-push-and-pop.htm

Unshift (adds) Shift (removes)| things on the front  vs | Push (adds) Pop (removes) at the end.


  • I was stuck on this exercise-


function nextInLine(arr, item) {
  // Your code here

  return item;  // Change this line
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

This is the correct code:

function nextInLine(arr, item) {
  // Your code here
  arr.push(item);
  return arr.shift();  // Change this line
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 7)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

I was getting stuck because I called arr.shift(); twice. Once, and then again after "return".
console.log(nextInLine(testArr, 7)); means: print onto the screen the results of calling nextInLine on testArr (defined as [1,2,3,4,5]). The function's job was pushing 7 to the end, and then shifting the first number off.



  • I also liked this one:


function testLogicalOr(val) {
  // Only change code below this line

  if (val) {
    return "Outside";
  }

  if (val) {
    return "Outside";
  }

  // Only change code above this line
  return "Inside";
}

// Change this value to test
testLogicalOr(15);

Answer:
function testLogicalOr(val) {
  // Only change code below this line

  if (val>20 || val<10) {
    return "Outside";
 
  }

  // Only change code above this line
  return "Inside";
}

// Change this value to test
testLogicalOr(11);

Aha moment: I am not saying val should be between 10 and 20. In fact, if the value is "outside" of this range, aka more than 20 OR less than 10, then it is returned as outside! Therefore, when running testLogicalOr(11); we know that 11 is INSIDE of the range, and therefore "Inside" is returned. 

Sunday, January 8, 2017

01/08/2017 Progress

I have been working through the FCC Javascript exercises but with my existing knowledge it has been very slow moving. Instead, I am relying on traditional book/note taking to really drill in my JS learning. 

YDKJS Book 1, Chapter 2 
NOTES:


  • The best and most natural approach is to use arrays for numerically positioned values and use objects for named properties.



  • == checks for value equality with coercion allowed, and === checks for value equality without allowing coercion; === is often called "strict equality" for this reason.


  • Not only can you pass a value (argument) to a function, but a function itself can be a value that's assigned to variables, or passed to or returned from other functions. As such, a function value should be thought of as an expression, much like any other value or expression.

Saturday, January 7, 2017

01/07/2017 YDKJS- Exercises

https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch1.md

Today I worked through these exercises using the console of an about:blank webpage in order to get hands on with Javascript programming.

Some notes to self:
Use Shift + Control+ I to access the Console

By convention, JavaScript variables as constants are usually capitalized, with underscores _ between multiple words.
The newest version of JavaScript at the time of this writing (commonly called "ES6") includes a new way to declare constants, by using const instead of var

The for loop has three clauses: the initialization clause (var i=0), the conditional test clause (i <= 9), and the update clause (i = i + 1). So if you're going to do counting with your loop iterations, for is a more compact and often easier form to understand and write.

Practice: 
  • Write a program to calculate the total price of your phone purchase. You will keep purchasing phones (hint: loop!) until you run out of money in your bank account. You'll also buy accessories for each phone as long as your purchase amount is below your mental spending threshold.
  • After you've calculated your purchase amount, add in the tax, then print out the calculated purchase amount, properly formatted.
  • Finally, check the amount against your bank account balance to see if you can afford it or not.
  • You should set up some constants for the "tax rate," "phone price," "accessory price," and "spending threshold," as well as a variable for your "bank account balance.""
  • You should define functions for calculating the tax and for formatting the price with a "$" and rounding to two decimal places.
  • Bonus Challenge: Try to incorporate input into this program, perhaps with the prompt(..) covered in "Input" earlier. You may prompt the user for their bank account balance, for example. Have fun and be creative!
1. set up constants and variables

const TAX_RATE= 0.08;
const PHONE_PRICE = 99.99
const ACCS_PRICE = 9.99;
const SPENDING_THRESHOLD = 300; 
var bank_balance= 400; 
var amount = 0;

2. Define functions

a. calculating tax 

function calculateTax(amount) {
      return amount *TAX_RATE;
}

b. formatting price with $ and rounding to two decimal places

function formatAmount(amount) {
      return "$" + amount.toFixed(2); 
}

3. now we purchase phones until we run out of money in bank account (this runs as a loop) 

while (amount < bank_balance) {
amount = amount + PHONE_PRICE;  // if we have more money in the bank than the cost, we will buy the phone

if (amount < SPENDING_THRESHOLD) {
amount = amount + ACCS_PRICE; //if the price is still less that what we want to spend, we will get a charger
}
}

amount = amount + CalculateTAX(amount); //then, we have to calculate the final amount which is the total plus tax 

console.log ("Your total is: " + formatAmount(amount)); //this spits out our grand total 

if (amount > bank_balance) {
console.log("Don't buy it!");  //otherwise, this spits out that we shouldn't buy
}