Skip to content

Commit 2f8c473

Browse files
Merge pull request #1 from CarnunMP/Carnun-Marcus-Page
JS-II
2 parents 7c951ac + ceb32cb commit 2f8c473

4 files changed

Lines changed: 155 additions & 29 deletions

File tree

README.md

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,47 +7,47 @@ With some basic JavaScript principles in hand, we can now expand our skills out
77

88
**Follow these steps to set up and work on your project:**
99

10-
* [ ] Create a forked copy of this project.
11-
* [ ] Add your team lead as collaborator on Github.
12-
* [ ] Clone your OWN version of the repository (Not Lambda's by mistake!).
13-
* [ ] Create a new branch: git checkout -b `<firstName-lastName>`.
14-
* [ ] Implement the project on your newly created `<firstName-lastName>` branch, committing changes regularly.
15-
* [ ] Push commits: git push origin `<firstName-lastName>`.
10+
* [x] Create a forked copy of this project.
11+
* [x] Add your team lead as collaborator on Github.
12+
* [x] Clone your OWN version of the repository (Not Lambda's by mistake!).
13+
* [x] Create a new branch: git checkout -b `<firstName-lastName>`.
14+
* [x] Implement the project on your newly created `<firstName-lastName>` branch, committing changes regularly.
15+
* [x] Push commits: git push origin `<firstName-lastName>`.
1616

1717
**Follow these steps for completing your project.**
1818

19-
* [ ] Submit a Pull-Request to merge <firstName-lastName> Branch into master (student's Repo). **Please don't merge your own pull request**
20-
* [ ] Add your team lead as a reviewer on the pull-request
21-
* [ ] Your team lead will count the project as complete by merging the branch back into master.
19+
* [x] Submit a Pull-Request to merge <firstName-lastName> Branch into master (student's Repo). **Please don't merge your own pull request**
20+
* [x] Add your team lead as a reviewer on the pull-request
21+
* [x] Your team lead will count the project as complete by merging the branch back into master.
2222

2323
## Task 1: Higher Order Functions and Callbacks
2424

2525
This task focuses on getting practice with higher order functions and callback functions by giving you an array of values and instructions on what to do with that array.
2626

27-
* [ ] Review the contents of the [callbacks.js](assignments/callbacks.js) file. Notice you are given an array at the top of the page. Use that array to aid you with your functions.
27+
* [x] Review the contents of the [callbacks.js](assignments/callbacks.js) file. Notice you are given an array at the top of the page. Use that array to aid you with your functions.
2828

29-
* [ ] Complete the problems provided to you but skip over stretch problems until you are complete with every other JS file first.
29+
* [x] Complete the problems provided to you but skip over stretch problems until you are complete with every other JS file first.
3030

3131
## Task 2: Array Methods
3232

3333
Use `.forEach()`, `.map()`, `.filter()`, and `.reduce()` to loop over an array with 50 objects in it. The [array-methods.js](assignments/array-methods.js) file contains several challenges built around a fundraising 5K fun run event.
3434

35-
* [ ] Review the contents of the [array-methods.js](assignments/array-methods.js) file.
35+
* [x] Review the contents of the [array-methods.js](assignments/array-methods.js) file.
3636

37-
* [ ] Complete the problems provided to you but skip over stretch problems until you are complete with every other JS file first.
37+
* [x] Complete the problems provided to you but skip over stretch problems until you are complete with every other JS file first.
3838

39-
* [ ] Notice the last three problems are up to you to create and solve. This is an awesome opportunity for you to push your critical thinking about array methods, have fun with it.
39+
* [x] Notice the last three problems are up to you to create and solve. This is an awesome opportunity for you to push your critical thinking about array methods, have fun with it.
4040

4141
## Task 3: Closures
4242

4343
We have learned that closures allow us to access values in scope that have already been invoked (lexical scope).
4444

4545
**Hint: Utilize debugger statements in your code in combination with your developer tools to easily identify closure values.**
4646

47-
* [ ] Review the contents of the [closure.js](assignments/closure.js) file.
48-
* [ ] Complete the problems provided to you but skip over stretch problems until you are complete with every other JS file first.
47+
* [x] Review the contents of the [closure.js](assignments/closure.js) file.
48+
* [x] Complete the problems provided to you but skip over stretch problems until you are complete with every other JS file first.
4949

5050
## Stretch Goals
5151

52-
* [ ] Go back through the stretch problems that you skipped over and complete as many as you can.
53-
* [ ] Look up what an IIFE is in JavaScript and experiment with them
52+
* [x] Go back through the stretch problems that you skipped over and complete as many as you can.
53+
* [x] Look up what an IIFE is in JavaScript and experiment with them

assignments/array-methods.js

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -55,31 +55,67 @@ const runners = [
5555
{ id: 50, first_name: "Shell", last_name: "Baine", email: "[email protected]", shirt_size: "M", company_name: "Gabtype", donation: 171 },
5656
];
5757

58+
console.log("Array-methods:");
59+
5860
// ==== Challenge 1: Use .forEach() ====
5961
// The event director needs both the first and last names of each runner for their running bibs. Combine both the first and last names and populate a new array called `fullNames`. This array will contain just strings.
6062
let fullNames = [];
63+
runners.forEach(runner => {
64+
let fullName = runner.first_name + " " + runner.last_name;
65+
fullNames.push(fullName);
66+
});
6167
console.log(fullNames);
6268

6369
// ==== Challenge 2: Use .map() ====
6470
// The event director needs to have all the runners' first names in uppercase because the director BECAME DRUNK WITH POWER. Populate an array called `firstNamesAllCaps`. This array will contain just strings.
65-
let firstNamesAllCaps = [];
71+
let firstNamesAllCaps = runners.map(runner => runner.first_name.toUpperCase());
6672
console.log(firstNamesAllCaps);
6773

6874
// ==== Challenge 3: Use .filter() ====
6975
// The large shirts won't be available for the event due to an ordering issue. We need a filtered version of the runners array, containing only those runners with large sized shirts so they can choose a different size. This will be an array of objects.
70-
let runnersLargeSizeShirt = [];
76+
let runnersLargeSizeShirt = runners.filter(runner => {
77+
return runner.shirt_size === "L";
78+
});
7179
console.log(runnersLargeSizeShirt);
7280

7381
// ==== Challenge 4: Use .reduce() ====
7482
// The donations need to be tallied up and reported for tax purposes. Add up all the donations and save the total into a ticketPriceTotal variable.
75-
let ticketPriceTotal = 0;
83+
let ticketPriceTotal = runners.reduce((total, runner) => {
84+
return total + runner.donation;
85+
}, 0);
7686
console.log(ticketPriceTotal);
7787

7888
// ==== Challenge 5: Be Creative ====
7989
// Now that you have used .forEach(), .map(), .filter(), and .reduce(). I want you to think of potential problems you could solve given the data set and the 5k fun run theme. Try to create and then solve 3 unique problems using one or many of the array methods listed above.
8090

81-
// Problem 1
91+
// Problem 1: You decide to give flowers to the top three donors. Produce an array of the top three runner objects, ranked in descending order of size of donation.
92+
function topThreeDonors() {
93+
let donationsRankedDescending = runners.sort((runnerA, runnerB) => {
94+
if (runnerA.donation < runnerB.donation) {return 1}
95+
if (runnerA.donation > runnerB.donation) {return -1}
96+
return 0
97+
});
98+
99+
return donationsRankedDescending.slice(0, 3);
100+
}
101+
console.log(topThreeDonors());
102+
103+
// Problem 2: An anonymous 51st company wants to join the fundraiser, matching everyone else's donations. Add them to runners. (Do not mutuate.)
104+
let runnersAndMysteryDonor = runners.concat({
105+
id: 51,
106+
first_name: "",
107+
last_name: "",
108+
email: "",
109+
shirt_size: "N/A",
110+
donation: ticketPriceTotal,
111+
}); // Interesting that you can .concat() an object (/value?) which isn't itself an array!
112+
console.log(runnersAndMysteryDonor[runnersAndMysteryDonor.length - 1]);
82113

83-
// Problem 2
114+
// Problem 3: You decide that companies whose names begin with "W" or end in "le" are morally reprehensible, and that it would be criminal to accept their money. Remove them from runners. (Do not mutuate.)
115+
let runnersAfterPurge = runners.filter(runner => {
116+
return !(runner.company_name[0] === "W" || runner.company_name.slice(-2) === "le");
117+
});
118+
console.log(runnersAfterPurge);
119+
// Looks good!
84120

85-
// Problem 3
121+
console.log("———");

assignments/callbacks.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,32 +38,69 @@ const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum'];
3838
// "this Pencil is worth a million dollars!"
3939
*/
4040

41+
console.log("Callbacks: ");
4142

4243
function getLength(arr, cb) {
4344
// getLength passes the length of the array into the callback.
45+
cb(arr.length);
4446
}
47+
getLength(items, item => console.log(`Length is ${item}!`));
4548

4649
function last(arr, cb) {
4750
// last passes the last item of the array into the callback.
51+
cb(arr[arr.length - 1]);
4852
}
53+
last(items, item => console.log(`Last item is ${item}`));
4954

5055
function sumNums(x, y, cb) {
5156
// sumNums adds two numbers (x, y) and passes the result to the callback.
57+
cb(x + y);
5258
}
59+
sumNums(2, 3, sum => console.log("Sum is " + sum));
5360

5461
function multiplyNums(x, y, cb) {
5562
// multiplyNums multiplies two numbers and passes the result to the callback.
63+
cb(x * y);
5664
}
65+
multiplyNums(2, 3, product => console.log("Product is " + product));
5766

5867
function contains(item, list, cb) {
5968
// contains checks if an item is present inside of the given array/list.
6069
// Pass true to the callback if it is, otherwise pass false.
70+
let isInList = false;
71+
list.forEach(i => {
72+
if (!isInList && (item === i)) {
73+
isInList = true;
74+
}
75+
});
76+
77+
cb(isInList);
6178
}
79+
contains("Notebook", items, isInList => console.log("There is a notebook in the list: " + isInList));
80+
contains("T-Rex", items, isInList => console.log("There is a T-Rex in the list: " + isInList));
6281

6382
/* STRETCH PROBLEM */
6483

6584
function removeDuplicates(array, cb) {
6685
// removeDuplicates removes all duplicate values from the given array.
6786
// Pass the duplicate free array to the callback function.
6887
// Do not mutate the original array.
88+
let counts = {};
89+
array.forEach(item => {
90+
if (counts[item] === undefined) {
91+
counts[item] = 1;
92+
} else {
93+
counts[item]++;
94+
}
95+
});
96+
97+
console.log(counts);
98+
cb(Object.keys(counts));
6999
}
100+
101+
let testArray = ["A", "A", "B", "C", "C", "C"];
102+
removeDuplicates(testArray, duplicatesRemoved => console.log(`Original array: [${testArray.toString()}]. Duplicates removed: [${duplicatesRemoved}]`));
103+
104+
// A little hacky, but it works! :P
105+
106+
console.log("———")

assignments/closure.js

Lines changed: 58 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,86 @@
1+
console.log("Closure:");
2+
13
// ==== Challenge 1: Write your own closure ====
24
// Write a closure of your own creation.
35
// Keep it simple! Remember a closure is just a function
46
// that manipulates variables defined in the outer scope.
57
// The outer scope can be a parent function, or the top level of the script.
6-
8+
let yo = "yo";
9+
function makeYoYoyo() {
10+
yo += "yo";
11+
}
12+
makeYoYoyo();
13+
console.log(yo);
714

815
/* STRETCH PROBLEMS, Do not attempt until you have completed all previous tasks for today's project files */
916

1017

1118
// ==== Challenge 2: Implement a "counter maker" function ====
12-
const counterMaker = () => {
19+
const counterMaker = (limit = 3) => {
1320
// IMPLEMENTATION OF counterMaker:
1421
// 1- Declare a `count` variable with a value of 0. We will be mutating it, so declare it using `let`!
1522
// 2- Declare a function `counter`. It should increment and return `count`.
1623
// NOTE: This `counter` function, being nested inside `counterMaker`,
1724
// "closes over" the `count` variable. It can "see" it in the parent scope!
1825
// 3- Return the `counter` function.
26+
let count = 0;
27+
function counter() {
28+
if (count < limit) {
29+
count++;
30+
} else {
31+
count = 1;
32+
}
33+
return count;
34+
}
35+
return counter;
1936
};
20-
// Example usage: const myCounter = counterMaker();
21-
// myCounter(); // 1
22-
// myCounter(); // 2
37+
// Example usage:
38+
const myCounter = counterMaker();
39+
myCounter(); // 1
40+
myCounter(); // 2
41+
console.log(myCounter()); // Expected: 3
42+
console.log(myCounter()); // Expected: 1
43+
console.log(myCounter()); // Expected: 2
2344

2445
// ==== Challenge 3: Make `counterMaker` more sophisticated ====
2546
// It should have a `limit` parameter. Any counters we make with `counterMaker`
2647
// will refuse to go over the limit, and start back at 1.
2748

2849
// ==== Challenge 4: Create a counter function with an object that can increment and decrement ====
50+
let counter = 0;
2951
const counterFactory = () => {
3052
// Return an object that has two methods called `increment` and `decrement`.
3153
// `increment` should increment a counter variable in closure scope and return it.
3254
// `decrement` should decrement the counter variable and return it.
55+
let counterObject = {
56+
increment: function() {
57+
counter++;
58+
// console.log(counter);
59+
return counter;
60+
},
61+
decrement: function() {
62+
counter--;
63+
return counter;
64+
}
65+
}
66+
67+
return counterObject;
3368
};
69+
70+
console.log(counterFactory().decrement(), counterFactory().decrement(), counterFactory().increment(), counterFactory().increment(), counterFactory().increment());
71+
// Hmm... seems to be working!
72+
73+
console.log("———");
74+
75+
// Some IIFE experiments:
76+
console.log((function () {
77+
return 5 * 5;
78+
})());
79+
80+
let iifeTestArray = ["Cat", "Dog", "Giant Man-Eating Lizard"];
81+
console.log(iifeTestArray.sort((function (a, b) {
82+
if (a < b) {return -1}
83+
if (b < a) {return 1}
84+
return 0;
85+
})())); // These parentheses are getting a little ridiculous!
86+
// In any case, the above causes an error... because sort expects a function (as opposed to some returned value)?

0 commit comments

Comments
 (0)