Skip to content

Instantly share code, notes, and snippets.

@37celsius
Last active February 14, 2019 19:50
Show Gist options
  • Save 37celsius/737ab70856650c836074 to your computer and use it in GitHub Desktop.
Save 37celsius/737ab70856650c836074 to your computer and use it in GitHub Desktop.
Learning fundamentals of JavaScript 3 Starting with sublevel 5

Forest of function expression (2 REVIEW)

/* Developers for the Forest of Function Expressions Theme Park have created a function declaration named forestFright, but they’ve decided not to keep the function in memory.

Convert the function from a named function declaration to an anonymous function expression and assign it to a variable called runAway.

function forestFright() {
  var toAlert = "";
  for (var i = 0; i < 5; i++) {
    toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";
  }
  alert(toAlert);
}
*/

var runAway = function(){
  var toAlert = "";
  for (var i = 0; i < 5; i++) {
    toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";
  }
  alert(toAlert);
};
/* The devs at the Death-Defying Dogwoods have determined a specific formula for the quantifiable amount of fear generated at the DDD. (This is important to know if you are running a theme park, ya know). Their mystery formula is based on the amount of people, the amount of rain, and the amount of sharks. Yes. Sharks.

Here is their genius formula:

var fearGenerated = function(numPeeps, rainInInches, numSharks) {
  var rainFear = numPeeps * rainInInches;
  var sharkFear = numSharks * numSharks * numSharks;
  var totalFear = sharkFear + rainFear;
  return totalFear;
};

The goal of the developers is to have the amount of fear generated to be no more than 400, but no less than 100 (they are running a business, after all!). In hauntedHickoryHouse.js, they’ve asked you to:

Analyze the formula.
Assign appropriate values to the people, rain, and sharks variables.
Call the fearGenerated function and pass in the variables as arguments.
Store the result of that function in a new variable called fear.
Note: You do not need to change the existing fearGenerated function.
*/

var people = 50;
var rain = 2;
var sharks = 3;

var fearGenerated = function(numPeeps, rainInInches, numSharks) {
  var rainFear = numPeeps * rainInInches;
  var sharkFear = numSharks * numSharks * numSharks;
  var totalFear = sharkFear + rainFear;
  return totalFear;
};

var fear = fearGenerated(people, rain, sharks);
/* Periodically, the devs at the Haunted Hickory House need to be reminded of their own genius formula. They’d like to view the contents of the function, rather than executing it.

In hauntedHickoryHouse.js, write a single line of code to alert the contents of the variable that stores the function to the screen. Below is the function expression assignment for reference.

var fearGenerated = function(numPeeps, rainInInches, numSharks) {
  var rainFear = numPeeps * rainInInches;
  var sharkFear = numSharks * numSharks * numSharks;
  var totalFear = sharkFear + rainFear;
  return totalFear;
};

*/

alert(fearGenerated);
/* Well, it stands to reason that some people might not want to experience the Haunted Hickory House if the fear is significantly elevated on that day.

Inside the fearMessage function expression, use conditional statements to check the already-generated fear value, and decide whether it is LOW, MEDIUM, or HIGH.
Inside each conditional statement, return a specific confirm message in the following formats:
For fear levels less than 200:

Fear Level: LOW
Still wanna ride?

For fear levels 200 through and including 300:

Fear Level: MEDIUM
Think you'll make it?

For fear levels above 300 and up to 400:

Fear Level: HIGH
Have a death wish?

Lastly, call the confirmRide function and pass in the fearMessage variable. Then assign the results of that function in a new variable called startRide.

*/

// Create a variable fear with function fearGenerated with 3 parameters that already been made previously
var fear = fearGenerated(numPeeps, rainInInches, numSharks);

// Create a variable with an anonymous function that have an if statement inside
// the IF statement is for the variable fear that hold the result from function fearGenerated function
var fearMessage = function() {
    // Insert conditional statements here
    if(fear < 200){
    	return confirm("Fear Level: LOW \n Still wanna ride?");
    
    } else if (fear <= 300){
        return confirm("Fear Level: MEDIUM \n Think you'll make it?");
    } else if (fear <= 400){
    		return confirm("Fear Level: HIGH \n Have a death wish?");
    }
};

// Create a function name confirmRide that returns confirmToGo parameter which masking the result of another function
// that is why inside the function name confirmRide we use paranthesis and semicolon
function confirmRide(confirmToGo) {
  return confirmToGo();
}

// Create a variable startRide with the function name confirmRide
var startRide = confirmRide(fearMessage);

/* How this actually works is

fearGenerated function create result, ie: 300
that result stored in fear variable, so var fear = 300

the variable fear message function have an IF statement
that creating a confirm message for number lower or equal to 300
return confirm("Fear Level: MEDIUM \n Think you'll make it?");
that confirm method is kept in the variable fearMessage

The function name confirmRide is just another function calling 
another function ie:

function confirmRide(fearMessage) {
  return fearMessage();
}

After this keep everything inside variable startRide
var startRide = confirmRide(fearMessage);
*/
/* Over at Maple Mountain, the dev team has received some name data from the customer terminal that they want to use to customize greetings for each of their passengers. But the data consists of an array with many subarrays where the first and last names of each passenger are split up.

They want to take the passengers array and convert those subarrays into strings that contain the first and last name for each passenger.

Create a modifiedNames variable to store our new data.
Assign passengers.map() to the modifiedNames variable. This will allow us to pass in a function to be used on every element in the array.
Pass an anonymous function to map().
The anonymous function should take in arrayCell as a parameter and use that to return a string with the first and last name for a passenger. In other words, if you were to pass in a ["Jason", "Millhouse"] array, the function should return a "Jason Millhouse" string. 
*/

// We have a variable with ARRAY of ARRAYS
var passengers = [ ["Thomas", "Meeks"],
                   ["Gregg", "Pollack"],
                   ["Christine", "Wong"],
                   ["Dan", "McGaw"] ];

// Create a variable modifiedNames
// Because we want to find each ARRAY inside of the ARRAY of the variable passengers, we use .map()
// Insert anonymous function inside the map function with parameter call arrayCell
// passengers.map(function(arrayCell){ return arrayCell.join(" ")}); LAYMAN'S TERM IS
// in passengers variable, map everything, use function inside that passengers to grab each array(arrayCell)
// return that array(arrayCell) as a string and join them together

var modifiedNames = passengers.map(function(arrayCell){ return arrayCell.join(" ")});
/* The passengers have arrived at Maple Mountain! Take the modifiedNames array that you produced in the last challenge, and map a new anonymous function on it.

The function should alert the following message to the screen for each passenger in turn:
Yo, <name>!
*/
// We have a variable with ARRAY
var modifiedNames = [ "Thomas Meeks",
                      "Gregg Pollack",
                      "Christine Wong",
                      "Dan McGaw" ];
                      
// Use .map() straight away to map the variable modifiedName and alert each string in the array
// using the anonymous function
modifiedNames.map(function(name){ alert("Yo, " + joinName+ "!");});
/* The folks over at Poplar Puzzlers need an array of functions for one of their puzzles. They’ve requested your help in making the array, which they would like to be called puzzlers. The cells of the array should each contain a function, and these functions are listed here in order:

Returns 8 less than 3 times an input.
Returns the cube of the sum of an input and 2.
Returns 9 less than the result of an input squared.
Returns the remainder after an input is divided by 4.
Use your knowledge of arrays and anonymous function expressions to build this array of functions.

Note: Use parentheses with your return statements if you’re having trouble with the order of operations.
*/

// Create variable with 3 different functions inside the array
// The Math conditional statement is copying from the internet
var puzzlers = [
    function(i) {
      return (i * 3) - 8;
    },
    function(i) {
      return (i + 2) * (i + 2) * (i + 2);
    },
    function(i) {
      return (i * i) - 9;
    },
    function(i) {
      return i % 4;
    }
];
START INTERMEZZO
// Using an array as a "Queue" for Fast Pass Delivery
var parkRides = [
    ["Birch Bumpers", 40],
    ["Pines Plunge", 55],
    ["Cedar Coaster", 20],
    ["Ferris Wheel of Firs", 90]
];

var fastPassQueue = ["Cedar Coaster", "Pines Plunge", "Birch Bumpers", "Pines Plunge"];

// parameter allRides is for the variable parkRides
// parameter passRides is for the variable fastPassQueue
// parameter pick is for the user chossing
function buildTicket(allRides, passRides, pick){
  // Create an IF statement, if the first index of passRides equal to the one the user choose
  if(passRides[0] === pick ){
    // If the condition is TRUE then we shift the passRides and store it in a VARIABLE
    var pass = passRides.shift();
    // After that we return the result with a function
    return function(){
      
              alert("Quick! You have got a Fast Pass to " + pass + "!");
      
            };
  } else {
    // If nothing match from the pick, then we will find from the allRides using FOR loop
    for(var i = 0; i < allRides.length; i++) {
      // We create an IF condition if we found matching with the pick
      if(allRides[i][0] === pick){
      
        return function(){
                  alert("A ticket is printing for " + pick + "!\n" 
                  + "Your wait is " + allRides[i][1] + " minutes.");
                };
      }
    }
  }
}

// Create a variable for the user input pick, at this stage Hard coded first
var wantsRide = "Birch Bumper";

// To make it compact we can create variable with the FUNCTION name buildTicket
// That we have created with inserting variables into that function parameters
var ticket = buildTicket(parkRides, fastPassQueue, wantsRide);

// We then call that variable ticket
ticket();

END INTERMEZZO

/* Ash Adventures has three different “adventures” to choose from, and customers are prompted for a number at a terminal. The number is stored as userChoice and then passed into a function called adventureSelector.

Inside the function, you need to return an anonymous function based on the number that the user selected. Each of your three anonymous functions should contain a boarding alert message:

If the user selects 1:
You selected the Vines of Doom!

If the user selects 2:
Looks like you want the Lake of Despair!

If the user selects 3:
The Caves of Catastrophe!

Assume the user’s choice has already been stored as 1, 2, or 3, and is passed in as the userChoice parameter. Make sure that you return all message functions as anonymous functions, instead of stored in variables. You do not need to call the function at the end.
*/

function adventureSelector(userChoice) {
  // return anonymous functions inside conditional blocks
  if(userChoice === 1){
    return function(){
    	alert("You selected the Vines of Doom!");
    };
  } else if(userChoice === 2){
    return function(){
    	alert("Looks like you want the Lake of Despair!");
    };
  } else if(userChoice === 3){
    return function(){
    	alert("The Caves of Catastrophe!");
    };
  }
}
/* Write one line of code that calls adventureSelector when the user selects choice 3, and that immediately invokes the function that gets returned. Here’s the function for your reference:
function adventureSelector(userChoice) {
  if (userChoice == 1) {
    return function() {
      alert("You selected the Vines of Doom!");
    };
  } else if (userChoice == 2) {
    return function() {
      alert("Looks like you want the Lake of Despair!");
    };
  } else if (userChoice == 3) {
    return function() {
      alert("The Caves of Catastrophe!");
    };
  }
}
*/

adventureSelector(3)();

PLEASE RE-DO THIS MULTIPLE TIMES CS305_10 PROBLEM

/* The devs at Poplar Puzzles would like you to treat an array of functions like a Queue, passing the result of each function into the next until the Queue is empty. They’ve sent you the puzzlers Queue of functions, and the following instructions:

Build a function and assign it to a variable named applyAndEmpty.
The function should take in an input number and a queue of functions as parameters.
Using a for loop, call the functions in the queue in order with the input number, where the results of each function become the next function’s input. Additionally, the queue should be empty after the function is called.
Lastly, call the applyAndEmpty function using the provided start variable and the puzzlers Queue as arguments, and alert the result. */

SOLUTION FOR CS305_10 PROBLEM

var puzzlers = [
  function (a) { return 8*a - 10; },
  function (a) { return (a-3) * (a-3) * (a-3); },
  function (a) { return a * a + 4; },
  function (a) { return a % 5; }
];
var start = 2;

// The first part should be relatively easy if you've been following along and have a good grasp of function expressions:

var applyAndEmpty = function (input, queue) {
  
};

// This is where it gets really difficult:
/* Using a for loop, call the functions in the queue in order with the input number, where the results of each function become the next function’s input. Additionally, the queue should be empty after the function is called.*/

var applyAndEmpty = function (input, queue) {
  for (var i = 0; i < queue.length; i++) {
    // loop through function in order
    // call the functions and empty the queue
  }
  return input;
};

/* Now we use input to store the values through each iteration of the loop. The shift() function can be used used to remove the first part of the array off and then we immediately invoke the function using () and pass in input because that was holding the value of the previous results (confusing, I know): */

var applyAndEmpty = function (input, queue) {
  for (var i = 0; i < queue.length; i++) {
    input = queue.shift()(input);
  }
  return input;
};

// That led me to this error message:
/* Your queue is getting shorter, but your loop is also checking that decreasing length on each cycle. It needs to run for as many cycles as there WERE functions initially, NOT for as many cycles as there currently ARE in any given cycle. */

// Basically what's happening is that the inside of the for loop is affecting it's length. So we have to move the length to a variable outside the loop:

var applyAndEmpty = function (input, queue) {
  var length = queue.length;
  for (var i = 0; i < length; i++) {
    input = queue.shift()(input);
  }
  return input;
};

// Then just alert the value:

alert(applyAndEmpty(start, puzzlers));

PLEASE RE-DO THIS MULTIPLE TIMES CS305_11 PROBLEM

/* Now the Poplar Puzzle-makers have sent you a puzzle with a new set of functions to use on that puzzle. To display your overwhelming array and function expression mastery, alert the answer to the following question:

“What is obtained when the result of passing 9 into the fourth function of the puzzlers array is then passed into the function whose array index matches the result of passing 3 into the second function of the puzzlers array?”

To really impress them, the expression used in your alert should:

Use just one line of code.
Involve no manual calculation or hard-coded math on your part.
Use indices of arrays to access functions.
Use parentheses to pass in parameters to immediately-invoking functions. */

SOLUTION FOR CS305_11 PROBLEM

// So first we know we're going to be using alert() to produce the final output:
alert();

// This is the hard part because it's all one sentence and it's not broken down into easy chunks:
/* “What is obtained when the result of passing 9 into the fourth function of the puzzlers array is then passed into the function whose array index matches the result of passing 3 into the second function?” */

// the result of passing 9 into the fourth function of the puzzlers array...
puzzlers[3](9)

/* But it's followed with this:
is then passed into the function whose array index matches the result of passing 3 into the second function of the puzzlers array...
*/

puzzlers[1](3)

// So far I've got two small chunks of the instructions taken care of:

puzzlers[3](9)
puzzlers[1](3)

/* 
Here are the full instructions again:
“What is obtained when the result of passing 9 into the fourth function of the puzzlers array is then passed into the function whose array index matches the result of passing 3 into the second function of the puzzlers array?”

Basically I translated this into this:

puzzlers[3](9) is then passed into the function whose array index matches puzzlers[1](3)

That's a little more manageable mentally. There's probably a thousand ways to wrap your head around this.
*/

puzzlers[puzzlers[1](3)](puzzlers[3](9))

// And lastly we pass all that into the alert() function:
alert(puzzlers[puzzlers[1](3)](puzzlers[3](9)));

The Concept of Closure (1 REVIEW)

START INTERMEZZO
// Lets build a ticketing system
// We have 3 transports, Submarine, Battleship and Giant Seagull
// First create a function

function buildCoveTicketMaker(transport){

  // Inside this function, we want to return a function
  // To make everything automatic result/ easy to call later on
  return function(passengerName)  {
    console.log("Here is your transportaion ticket via the " + transport + "\.n" +
                "Welcome to the Cold Closures Cove, " + passengerName + " !");
  }

}

// So we have build a core function
// next we can put any transportation system into that function and we can seperate them
// by creating variable depending on the transportation;

var getSubmarineTicket = buildCoveTicketMaker("Submarine");
var getBattleshipTicket = buildCoveTicketMaker("Battleship");
var getGiantSeagullTicket = buildCoveTicketMaker("Giant Seagull");

// Since we have create variables for transportation ticket
// We can easily put passenger name in the get transportation
// But if we did not put the passenger name, the variable with the ticket function will not working
// because the parameter passengerName inside the ticket function is undefined
// The way we make it work is by adding the name

getSubmarineTicket("mario");
getBattleshipTicket("Luigi");
getGianSeagullTicket("Bowser");
END INTERMEZZO
/* After examining the code below, calculate the final value of the result variable and alert the value as a number using one line of code. 

function mystery() {
  var secret = 6;
  function mystery2(multiplier) {
    multiplier *= 3;
    return secret * multiplier;
  }
  return mystery2;
}

var hidden = mystery();
var result = hidden(3);
*/

// variable hidden have zero parameter for function mystery
// but function mystery still undefined because we did not set the multiplier parameter in mystery2 function
// we set mystery2 paremeter to 3 in the variable result
// so 3 * 3 = 9, secret is 6 from the variable inside parent function, so 6 * 9 = 54

alert(54);
/* We’ve made the code a little trickier this time. Again, calculate the final value of the result variable and alert the value as a number using one line of code.

function mystery(input) {
  var secret = 5;
  function mystery2(multiplier) {
    multiplier *= input;
    return secret * multiplier;
  }
  return mystery2;
}

var hidden = mystery(4);
var result = hidden(2);
*/

alert(40);

PLEASE RE-DO THIS MULTIPLE TIMES CS306_03 PROBLEM

/* Moar tricky. Moar tough! Again, calculate the final value of the result variable and alert the value as a number using one line of code. Hehe, good luck with this one!

function mystery(input) {
  var secret = 4;
  input += 2;
  function mystery2(multiplier) {
    multiplier *= input;
    return secret * multiplier;
  }
  return mystery2;
}

function mystery3(param) {
  function mystery4(bonus) {
    return param(6) + bonus;
  }
  return mystery4;
}

var hidden = mystery(3);
var jumble = mystery3(hidden);
var result = jumble(2);
*/

SOLUTION FOR CS306_03 PROBLEM

alert(122);
/* The Dev Girls at the Cold Closures Cove sometimes need to provide warnings to travelers about various obstacles that sometimes float into the Cove. They need you to prepare a very efficient warning maker that will allow them to create only the warnings they need, and only when they need it. Closures to the rescue! 

They’ve started a function called warningMaker with a parameter called obstacle. Within this function, return an anonymous function that displays a specific alert message based on the specific obstacle encountered. The format of the message should be as follows: 

Beware! There have been <obstacle> sightings in the Cove today!
*/

function warningMaker(obstacle) {
  return function(){
 		alert("Beware! There have been "+ obstacle + " sightings in the Cove today!");
  };
}
/* The Cove’s Dev Girls just got reports of icebergs in the area!

Build a warning message by passing a "iceberg" obstacle as an argument into the warningMaker function.
Store the results in a new variable called icebergAlert.
Call the icebergAlert function to view the warning message.
Note: You do not need to change the existing warningMaker function. */

function warningMaker(obstacle) {
  return function() {
    alert("Beware! There have been " + obstacle + " sightings in the Cove today!");
  };
}

// build your warning message here
var icebergAlert = warningMaker("iceberg");

icebergAlert();
/* The Cold Closures Cove devs are troubled by the amount of the warnings that have been coming back lately. Some obstacles have been particularly troublesome, while others are not as frequent.

They’d like you modify the warningMaker function to internally count the number of times a particular warning has been issued.

In order to accomplish this, you’ll need to set up a count variable and figure out how to increment it appropriately within the context of your functions.

Lastly, add that count to the alert message. The format of the message should match the following: 

een <obstacle> sightings in the Cove today!
<number> have been spotted at the <location>!
This is alert #<count> today for <obstacle> danger.

*/

function warningMaker(obstacle) {
  // create a count
  var count = 0;
  return function(number, location) {
    // keep track of warnings
    count++;
    
    alert("Beware! There have been " + obstacle +
          " sightings in the Cove today!\n" +
          number + " have been spotted at the " +
          location + "!\n" +
          // finish the warning message here
          "This is alert #" + count + " today for " + obstacle + " danger."
    );
  };
}

PLEASE RE-DO THIS MULTIPLE TIMES CS306_9 PROBLEM

/* The Dev Girls need you to store each location so that a list of danger zones for each obstacle can be reported with every new warning.

Inside the warningMaker function:

Store each location in an array called zones.
Add each zone to the list string.
Report the list of danger zones with the alert message in this format:

Beware! There have been <obstacle> sightings in the Cove today!
<number> have been spotted at the <location>!
This is alert #<count> today for <obstacle> danger.
Current danger zones are:
<zone1>
<zone2>
<zone3>
*/

SOLUTION FOR CS305_9 PROBLEM

function warningMaker(obstacle) {
  var count = 0;
  var zones = [];
  return function(number, location) {
    count++;
    var list = "";
    zones.push(location);
    for (var i = 0; i < zones.length; i++) {
      list += zones[i] + "\n";
    }
    alert("Beware! There have been " + obstacle +
          " sightings in the Cove today!\n" +
          number + " have been spotted at the " +
          location + "!\n" +
          "This is alert #" + count +
          " today for " + obstacle + " danger.\n" +
          "Current danger zones are:\n" +
          list);
  };
}
/* Well, it’s nice for new travelers to know where the danger zones are, but what if some of them are thrill-seekers? They might actually want to visit the zones that have the highest number of obstacles.

We already have a list of danger zones, and now the Dev Girls at the Cove want you to add a number alongside each of the locations.

Using the zones array, push a sub-array containing both the location and number for each obstacle.
Inside the for loop, find a way to access those values from the zones array in order to add them to the list string.
The final alert should be displayed in the following format:

Beware! There have been <obstacle> sightings in the Cove today!
<number> have been spotted at the <location>!
This is alert #<count> today for <obstacle> danger.
Current danger zones are:
<zone1> (<number1>)
<zone2> (<number2>)
<zone3> (<number3>)
...
*/

function warningMaker(obstacle) {
  var count = 0;
  var zones = [];
  return function(number, location) {
    count++;
    var list = "";
    // push an array with location and number
    zones.push([location, number]);
    for (var i = 0; i < zones.length; i++) {
      // replace location and number with appropriate code
      list += zones[i][0] + " (" + zones[i][1] + ")" + "\n";
    }
    alert("Beware! There have been " + obstacle +
          " sightings in the Cove today!\n" +
          number + " have been spotted at the " +
          location + "!\n" +
          "This is alert #" + count +
          " today for " + obstacle + " danger.\n" +
          "Current danger zones are:\n" +
          list);
  };
}

Object creation and manipulation

START INTERMEZZO
// Create a new object call myBox with properties
var myBox = {
  height: 6,
  width: 8,
  length: 10,
  volume: 480,
  materials: "carboards"
  weight: 24,
  destination1: "Orlando",
  destination2: "Miami",
  "# of stops": 2,
  "# of books": 0
};

// To create a loop finding the destination depending number of stops
/*
for (var i = 1; i <= myBox["# of stops"]; i++){
  console.log(myBox["destination" + i]);
};
*/

// Let's create a function to create a Book object and add them to myBox
function addBook(box, name, writer){
  box["# of books"]++ // Each time we create a new book, we increase the number of books
  // So we create a new property and concenate with the newly "# of books" value
  // When we first call this function it will become "book1"
  box["book" + box["# of books"] ] = {title: name, author: writer};
}


// Call the function
addBook(myBox, "The Great Expectation", "Charles Dicken");
END INTERMEZZO
/*
We need to assign each of the ranger-devs to a super-blinding light bulb based on their station number. So we’re building a function that creates an alert message for the ranger-devs in the following format:

---
Avast, me hearties!
There be Pirates nearby! Stations!
<name>, man the <superblinder>!
<name>, man the <superblinder>!
<name>, man the <superblinder>!
---

We’ve created a dontPanic function for you that already contains the alert message. Your job is to finish building the list string:

Create a for loop to loop through all of the rangers at the location, using the numRangers property to keep track.
Inside the loop, begin by using the correct property to append the name of the current ranger to the list.
Also, concatenate the text between the ranger name and the superblinder so that it matches the format above.
Lastly, add the name of the correct super-blinding light bulb from the weaponBulbs array to the list. In order to retrieve the name of the correct bulb, you’ll need to use the ranger’s station number.

*/

// From CodeSchool
var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];

var lighthouseRock = {
  gateClosed: true,
  weaponBulbs: superBlinders,
  capacity: 30,
  secretPassageTo: "Underwater Outpost",
  numRangers: 3,
  ranger1: {name: "Nick Walsh", skillz: "magnification burn", station: 2},
  ranger2: {name: "Drew Barontini", skillz: "uppercut launch", station: 3},
  ranger3: {name: "Christine Wong", skillz: "bomb defusing", station: 1}
};

function dontPanic(location) {
  var list = "Avast, me hearties!\n" +
             "There be Pirates nearby! Stations!\n";

  // Start the exsercise
  // first we create a FOR loop to grab the rangers
  for(var i = 1; i <= location.numRangers; i++){
    
    // To understand what we need to do, create a mockup scaffolding first
    // Since we want to append to the list we use the plus symbol
    // => list += name + ", man the " + superBlinder + "!/n";
    
    // We can concatenate the values directly to the list,
    // But for the sake of the details we create a variable so
    // we know exactly what is happening from that variable
    // => var name = something;
    // => var superBlinder = something;
    
    var name = location["ranger" + i].name ;
    var superBlinder = location.weaponBulbs[location["ranger" + i].station - 1][0];
    
    list += name + ", man the " + superBlinder + "!/n";
    
  }

  alert(list);
}

dontPanic(lighthouseRock);

Functionality in objects (1 REVIEW)

START INTERMEZZO
var aquarium = {
	nemo: {type: "fish", species: "clownFish", length: 3.7 },
	marlin: {type: "fish", species: "clownFish", length: 4.1 },
	dory: {type: "fish", species: "blue tang", length: 6.2 },
	peach: {type: "echinoderm", species: "starfish", length: 5.3 },
	"coral castle": {type: "environment", species: "coquina", moves: false },
	"dragon statue": {type: "environment", species: "plastic", moves: false },

	// we create a method for adding an object property
	addCriter: function (name, type, species, length) {
		// this refer to the object property name (new or existed) 
		this[name] = {type: type, species: species, length: length};
	}
}

// If we want to delete a property inside the object we create a function
aquarium.takeOut = function(name) {
	// we create temp variable to help us hold on to the item that we remove
	var temp =  this[name];	

	// next we remove the property from the object
	delete this[name];

	// the last one is we return temp variable so we can still have
	// reference to the removed object property
	return temp;
};

// if we create a variable with the takeOut method
// we deleting marlin object from the aquarium and put it in the fishOutOfWater variable
var fishOutOfWater = aquarium.takeOut("marlin");

// we can check if everything working by console.log the fishOutOfWater variable
console.log(fishOutOfWater);

// The problem with this is that we will be losing the name of the object
// to fix that we create an extra line of code inside the takeOut method to capture the name

this[name].name // create a new property
this[name].name = name // assign the name parameter to that new property

// so the complete method will look like
aquarium.takeOut = function(name) {
	this[name].name = name;
	var temp = this[name];
	delete this[name];
	return temp;
}
END INTERMEZZO

PLEASE RE-DO THIS MULTIPLE TIMES CS308_5 PROBLEM

/*
Vehicle objects now contain objects that represent ranger-devs. We want to keep track of which ranger-devs are assigned to patrol duty on specific vehicles. The vehicle3 object is provided in the challenge editor as an example.

We need to get the offDuty rangers out of the vehicle while holding on to their objects for further use, as well as renumbering the rangers who should remain onDuty in the vehicle.

Build a relieveDuty function that accepts a vehicle object and a day of the week as parameters.

Use a for loop along with the numRangers property to search through all of the ranger objects contained within the vehicle object.

Sort all ranger objects into offDuty and onDuty arrays based on their dayOff property. The offDuty array will be returned from the function. The onDuty array will contain remaining rangers that need to be renumbered.

Adjust the numRangers property by subtracting the number of offDuty rangers.

Shift all rangers from the onDuty array back to the vehicle object. Their property names should be rebuilt with ranger numbers starting from 1.

Lastly, call the relieveDuty function and pass in vehicle3 and "Friday". The resulting array of objects should be stored in a variable called offToday.

Use the hints as you get stuck!
*/

// From CodeSchool
var vehicle3 = {
  type: "Submarine", capacity: 8, storedAt: "Underwater Outpost",
  ranger1: {name: "Gregg Pollack", skillz: "Lasering", dayOff: "Friday"},
  ranger2: {name: "Bijan Boustani", skillz: "Working", dayOff: "Saturday"},
  ranger3: {name: "Ashley Smith", skillz: "Torpedoing", dayOff: "Friday"},
  ranger4: {name: "Mark Krupinski", skillz: "Sniping", dayOff: "Wednesday"},
  numRangers: 4
};

// Start excersice
var vehicle3 = {
  type: "Submarine", capacity: 8, storedAt: "Underwater Outpost",
  ranger1: {name: "Gregg Pollack", skillz: "Lasering", dayOff: "Friday"},
  ranger2: {name: "Bijan Boustani", skillz: "Working", dayOff: "Saturday"},
  ranger3: {name: "Ashley Smith", skillz: "Torpedoing", dayOff: "Friday"},
  ranger4: {name: "Mark Krupinski", skillz: "Sniping", dayOff: "Wednesday"},
  numRangers: 4
};

// First create a function expresssion

var relieveDuty = function(vehicle, day){
	// We need to create an empty variable array to hold the ranger objects
	var offDuty = [];
	var onDuty = [];

	// Then we create a for LOOP to grab all the ranger numbers
	for(var i = 1; i <= vehicle.numRangers; i++){
		// We are using conditional to see if the ranger object's dayOff property
		// is equal to the day parameter that is being passed into the function

		if(vehicle["ranger" + i ].dayOff === day ){
			// If the day is equal to the offDay property in the ranger object
			// we push the array to the offDuty Variable that we created inside 
			// this function
			offDuty.push(vehicle["ranger" + i]);
		} else {
			// If it is not equal we push it to onDuty variable that we created
			// inside this function
			onDuty.push(vehicle["ranger" + i]);
		}

		// Since we already log all the offDuty and onDuty rangers to their
		// respective variables that we created inside this function
		// we can now delete the ranger objects inside the vehicle object

		delete vehicle["ranger" + i];
	}

	// we still need to update numRangers total by subtracting from the total of
	// offRanger in the array
	vehicle.numRangers -= offDuty.length;


	// Since we removed all the rangers in the vehicle3 objects, and the
	// task is to add the onDuty into the vehicle3 object with correct numbering.
	// We will use loop 

	for(var j = 1; j <= vehicle.numRangers; j++){
		// Since the ranger objects are stored in order in the onDuty array,
		// we can shift values from the beginning of the array and add them
		// as a numbered ranger for each iteration of the loop.
		vehicle["ranger" + j] = onDuty.shift();

	}

	// Everything is working, now we just need value requested with just the offDuty rangers

	return offDuty;
};

// Lastly, call the relieveDuty function and pass in vehicle3 and "friday".
// since we want to store the array of objects, we create a variable called offToday.

var offToday = relieveDuty(vehicle3, "Friday");

Prototypes and inheritance

START INTERMEZZO
/*

---
About prototype
----

A prototype is like a blueprint object for the object we are trying to create


*/

// Playing around with prototype
// Lets create string variables

var witch = "I'll get you my pretty...and your little dog, too!",
	scarecrow = "Well, some people without brains do an awful lot of talking don't they?",
	glinda = "Be gone! Before someone drops a house on you!",
	dorothy = "There's no place like home.",
	lion = "Come on, get up and fight, you shivering junkyard!",
	wizard = "Do not arouse the wrath of the great and powerful Oz!",
	tinman = "Now I know I have a heart, because it's breaking.";

// Start to built a function inside string prototype

// To add the function to the string prototype we use dot notation and assign new
// property name called countAll
String.prototype.countAll = function(letter){
	var letterCount = 0;
	for (var i = 0; i < this.length; i++){
		if( this.charAt(i).toUpperCase() == letter.toUpperCase() ){
			letterCount++;
		}
	}
	return letterCount;

};
END INTERMEZZO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment