Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Start off #1260

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,66 @@ Demonstrate your understanding of this week's concepts by answering the followin

Edit this document to include your answers after each question. Make sure to leave a blank line above and below your answer so it is clear and easy to read by your team lead



1. Briefly compare and contrast `.forEach` & `.map` (2-3 sentences max)

Both are similar however .map returns a new array with transformed
elements while .forEach returns undefined. Also .map is chainable
while .forEach is not. This means .map can handle other calls like
.sort or .reduce after the .map call. This is something .forEach
is not capable of. Also both methods do not mutate the array's
elements on its own without a callback function in use to do so.


2. Explain the difference between a callback and a higher order function.

A higher order function is the outer scope block within the function
a global scope could call. However a callback function can not be
invoked or called by the global scope. Only the higher order function's
scope is capable of accessing the callback function.

3. What is closure?

Closure is a scope block a variable or function can be accessable within.
Depending on how many nested curly braces there are closure can be increased
or decreased.

4. Describe the four rules of the 'this' keyword.

1. Simple Function call: Where global functions defaults to the global object and in
strict mode they will default to undefined

2. Implicit value: The Implicit value points to the object from which it is called
and accounts for the majority of day to day code examples of this. This as an
Implicit value is what is to the left of the assignment operator. Which is used
when a constructor's value is referenced.


3. Explicti Value: Used when assigning a specific function or variable a value
for Prototypes bind apply or call all use this as a explicit value. In classes
this is similar to passing in values throug the super keyword or when assigning
a function to a variable to return an explicitvalue as the bind functions does.


4. new binding: Using the new keyword constructs a new object and this points to it.
So when a function is invoked as a constructor function the this will then point
to the new object created to the left of the assignment operator.





5. Why do we need super() in an extended class?

Super in a extended class will allow the parent class to be accessible from
the child class. So all properties a parent class have the child class will
as well by just adding in the paramerters need within the parent construtor
through the super function inside of the child class.




### Task 1 - Project Set up

Follow these steps to set up and work on your project:
Expand Down
168 changes: 139 additions & 29 deletions challenges/arrays-callbacks.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,125 @@
// ==== ADVANCED Array Methods ====

// Given this zoo data from around the United States, follow the instructions below. Use the specific array methods in the requests below to solve the problems.
// Given this zoo data from around the United States, follow the instructions below.
// Use the specific array methods in the requests below to solve the problems.

const zooAnimals = [
{ animal_name: "Jackal, asiatic", population: 5, scientific_name: "Canis aureus", state: "Kentucky" },
{ animal_name: "Screamer, southern", population: 1, scientific_name: "Chauna torquata", state: "Alabama" },
{ animal_name: "White spoonbill", population: 8, scientific_name: "Platalea leucordia", state: "Georgia" },
{ animal_name: "White-cheeked pintail", population: 1, scientific_name: "Anas bahamensis", state: "Oregon" },
{ animal_name: "Black-backed jackal", population: 2, scientific_name: "Canis mesomelas", state: "Washington" },
{ animal_name: "Brolga crane", population: 9, scientific_name: "Grus rubicundus", state: "New Mexico" },
{ animal_name: "Common melba finch", population: 5, scientific_name: "Pytilia melba", state: "Pennsylvania" },
{ animal_name: "Pampa gray fox", population: 10, scientific_name: "Pseudalopex gymnocercus", state: "Connecticut" },
{ animal_name: "Hawk-eagle, crowned", population: 10, scientific_name: "Spizaetus coronatus", state: "Florida" },
{ animal_name: "Australian pelican", population: 5, scientific_name: "Pelecanus conspicillatus", state: "West Virginia" },
{ animal_name: "Jackal, asiatic", population: 5,
scientific_name: "Canis aureus", state: "Kentucky" },
{ animal_name: "Screamer, southern", population: 1,
scientific_name: "Chauna torquata", state: "Alabama" },
{ animal_name: "White spoonbill", population: 8,
scientific_name: "Platalea leucordia", state: "Georgia" },
{ animal_name: "White-cheeked pintail", population: 1,
scientific_name: "Anas bahamensis", state: "Oregon" },
{ animal_name: "Black-backed jackal", population: 2,
scientific_name: "Canis mesomelas", state: "Washington" },
{ animal_name: "Brolga crane", population: 9,
scientific_name: "Grus rubicundus", state: "New Mexico" },
{ animal_name: "Common melba finch", population: 5,
scientific_name: "Pytilia melba", state: "Pennsylvania" },
{ animal_name: "Pampa gray fox", population: 10,
scientific_name: "Pseudalopex gymnocercus", state: "Connecticut" },
{ animal_name: "Hawk-eagle, crowned", population: 10,
scientific_name: "Spizaetus coronatus", state: "Florida" },
{ animal_name: "Australian pelican", population: 5,
scientific_name: "Pelecanus conspicillatus",
state: "West Virginia" },
];

/* Request 1: .forEach()

The zoos want to display both the scientific name and the animal name in front of the habitats. Populate the displayNames array with only the animal_name and scientific_name of each animal. displayNames will be an array of strings, and each string should follow this pattern: "Name: Jackal, asiatic, Scientific: Canis aureus."

The zoos want to display both the scientific name and the animal name in front of the habitats.
Populate the
displayNames array with only the animal_name and scientific_name of each animal. displayNames will
be an array
of strings, and each string should follow this pattern: "Name: Jackal, asiatic, Scientific:
Canis aureus."
Stretch goal
Convert the regular functions into new es6 arrow functions
*/
const displayNames = [];
console.log(displayNames);
let count = 0;
zooAnimals.forEach((e) =>{
// Add up the object properties
displayNames[count] = `Name: ${e.animal_name} Scientific: ${e.scientific_name}.`;
++count;
});

/* Request 2: .map()
console.log('Task1 - Array callbacks');
displayNames.forEach(e => console.log(e));

The zoos need a list of all their animal's names (animal_name only) converted to lower case. Using map, create a new array of strings named lowCaseAnimalNames, each string following this pattern: "jackal, asiatic". Log the resut.
/* Request 2: .map()
The zoos need a list of all their animal's names (animal_name only)
converted to lower case. Using map, create
a new array of strings named lowCaseAnimalNames, each string following
this pattern: "jackal, asiatic". Log the
resut.

*/
let lowCaseAnimalNames = [];
lowCaseAnimalNames = zooAnimals.map((e)=>{
// Return the lowercase animals names
return e.animal_name.toLowerCase();
});

const lowCaseAnimalNames = [];
console.log(lowCaseAnimalNames);

console.log('Task 2');
for(let i = 0; i < lowCaseAnimalNames.length; i++){
// Print the lowercase animal names
console.log(lowCaseAnimalNames[i]);
}

/* Request 3: .filter()

The zoos are concerned about animals with a lower population count. Using filter, create a new array of objects called lowPopulationAnimals which contains only the animals with a population less than 5.
The zoos are concerned about animals with a lower population count.
Using filter, create a new array of objects
called lowPopulationAnimals which contains only the animals with a
population less than 5.

*/
const lowPopulationAnimals = [];
console.log(lowPopulationAnimals);
let lowPopulationAnimals = [];

lowPopulationAnimals = zooAnimals.filter(e => e.population <= 5);

console.log('Task3');
for(let i in lowPopulationAnimals){
// All low population animals
console.log(lowPopulationAnimals[i].animal_name);
}

/* Request 4: .reduce()

The zoos need to know their total animal population across the United States. Find the total population from all the zoos using the .reduce() method. Remember the reduce method takes two arguments: a callback (which itself takes two args), and an initial value for the count.
The zoos need to know their total animal population across the United States.
Find the total population from all
the zoos using the .reduce() method. Remember the reduce method takes two
arguments: a callback (which itself
takes two args), and an initial value for the count.

*/
let populationTotal = 0;
console.log(populationTotal);
// Array reducer
const reducer = (accumulator, currentValue) => accumulator + currentValue;
/* Array OBject accumulator
let initialValue = 0
let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (accumulator, currentValue) {
return accumulator + currentValue.x
}, initialValue)

console.log(sum) // logs 6
*/
// population array
let popar = [];
for(let i = 0; i < zooAnimals.length; i++){
// Make a population array to use with reducer
popar.push(zooAnimals[i].population);
}

for(let i = 0; i< zooAnimals.length; i++){
// The population array added up
console.log('Task 4 Total Popualtion: '+popar.reduce(reducer));
}



// ==== Callbacks ====
Expand All @@ -55,28 +128,65 @@ console.log(populationTotal);
* Create a higher-order function named consume with 3 parameters: a, b and cb
* The first two parameters can take any argument (we can pass any value as argument)
* The last parameter accepts a callback
* The consume function should return the invocation of cb, passing a and b into cb as arguments
* The consume function should return the invocation of cb, passing a and b into cb as
* arguments
*/


/* Step 2: Create several functions to callback with consume();
* Create a function named add that returns the sum of two numbers
* Create a function named multiply that returns the product of two numbers
* Create a function named greeting that accepts a first and last name and returns "Hello first-name last-name, nice to meet you!"
* Create a function named greeting that accepts a first and last name and returns
* "Hello first-name last-name,
* nice to meet you!"
*/
add = (a,b) => {

return a+b;
}
multiply=(a,b)=>{

return a*b;
}
greeting=(a,b)=>{

return `Hello ${a} ${b}, nice to meet you!`;
}


consume=(a,b,cb)=>{

return cb(a,b);

}
//console.log(consume(3,3,cconsume()));
console.log('Consume callback functions ');
/* Step 3: Check your work by un-commenting the following calls to consume(): */
// console.log(consume(2, 2, add)); // 4
// console.log(consume(10, 16, multiply)); // 160
// console.log(consume("Mary", "Poppins", greeting)); // Hello Mary Poppins, nice to meet you!
console.log(consume(2, 2, add)); // 4
console.log(consume(10, 16, multiply)); // 160
console.log(consume("Mary", "Poppins", greeting)); // Hello Mary Poppins, nice
//to meet you!




/*

Stretch: If you haven't already, convert your array method callbacks into arrow functions.
Stretch: If you haven't already, convert your array method callbacks into arrow
functions.

*/



/*
Call back function for buttons clickes
<button id="callback-btn">Click here</button>
This time we will see a message on the console only when the user clicks on the button:

document.queryselector("#callback-btn")
.addEventListener("click", function() {
console.log("User has clicked on the button!");
});

*/
61 changes: 57 additions & 4 deletions challenges/classes.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,60 @@
// 1. Copy and paste your prototype in here and refactor into class syntax.
// 1. Copy and paste your prototype in here and refactor into
//class syntax.


class CuboidMaker{
constructor(length,width,height){
this.length = length;
this.height = height;
this.width = width;
}

volume = () =>{
return this.length * this.width * this.height;
}

surfaceArea = () =>{
return 2 * (this.length * this.width + this.length * this.height +
this.width * this.height);
}
}


console.log('Cklasses ');

let cuboid = new CuboidMaker(5,5,4);

// Test your volume and surfaceArea methods by uncommenting the logs below:
// console.log(cuboid.volume()); // 100
// console.log(cuboid.surfaceArea()); // 130
console.log(cuboid.volume()); // 100
console.log(cuboid.surfaceArea()); // 130


// console.log(c.volume()); // 100
// console.log(c.surfaceArea()); // 130

// Stretch Task: Extend the base class CuboidMaker with a sub class
//called CubeMaker. Find out the formulas for volume and surface area for
// cubes and create those methods using the dimension properties
//from CuboidMaker. Test your work by logging out your volume and surface
//area.

class CubeMaker extends CuboidMaker{
constructor(a,b,c){
super(a,b,c);
this.cubeMakerValue = 0;
}
makeAcube = (c,d) =>{
this.cubeMakerValue = c * d;
}
theCube = () =>{
return this.cubeMakerValue;
}
}
let cube = new CubeMaker(5,5,4);
console.log('With the strech goal');
console.log('Volume '+cube.volume()); // 100
console.log('Surface Area '+cube.surfaceArea()); // 130
cube.makeAcube(cube.volume(),cube.surfaceArea());
console.log('The cube with surface area and volume '+ cube.theCube());


// Stretch Task: Extend the base class CuboidMaker with a sub class called CubeMaker. Find out the formulas for volume and surface area for cubes and create those methods using the dimension properties from CuboidMaker. Test your work by logging out your volume and surface area.
25 changes: 21 additions & 4 deletions challenges/closure.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,41 @@
// ==== Closures ====

/* Task 1: Study the code below and explain in your own words why nested function can access the variable internal. */
/* Task 1: Study the code below and explain in your own words why nested
function can access the variable internal. */


const external = "I'm outside the function";

function myFunction() {
myFunction = () => {
console.log(external);
const internal = "Hello! I'm inside myFunction!";

function nestedFunction() {
nestedFunction=()=> {
console.log(internal);
};
nestedFunction();
}
myFunction();

// Explanation:
/*
The reason internal is accessbile by nested function is the same type of
reason external is accessible within the myFunction. Its because of scope block
The inner nested scope blocks allow these variables closure to those functions.
*/


/* Task 2: Counter */

/* Create a function called `sumation` that accepts a parameter and uses a counter to return the summation of that number. For example, `summation(4)` should return 10 because 1+2+3+4 is 10. */
/* Create a function called `sumation` that accepts a parameter and uses
a counter to return the summation of that number. For example,
`summation(4)` should return 10 because 1+2+3+4 is 10. */
const sumation = (p) => {
let result = 0;
for(let counter = 0; counter <= p; counter++){
result = result + counter;
}
return result;
};
console.log('summation '+ sumation(4));

Loading