diff --git a/README.md b/README.md index 6288977c2..a70fe1fc1 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -# JavaScript - II +# JavaScript - II - Isaac Aderogba With some basic JavaScript principles in hand, we can now expand our skills out even further by exploring callback functions, array methods, and closure. Finish each task in order as the concepts build on one another. @@ -7,36 +7,36 @@ With some basic JavaScript principles in hand, we can now expand our skills out **Follow these steps to set up and work on your project:** -* [ ] Create a forked copy of this project. -* [ ] Add your project manager as collaborator on Github. -* [ ] Clone your OWN version of the repository (Not Lambda's by mistake!). -* [ ] Create a new branch: git checkout -b ``. -* [ ] Implement the project on your newly created `` branch, committing changes regularly. -* [ ] Push commits: git push origin ``. +* [X] Create a forked copy of this project. +* [X] Add your project manager as collaborator on Github. +* [X] Clone your OWN version of the repository (Not Lambda's by mistake!). +* [X] Create a new branch: git checkout -b ``. +* [X] Implement the project on your newly created `` branch, committing changes regularly. +* [X] Push commits: git push origin ``. **Follow these steps for completing your project.** -* [ ] Submit a Pull-Request to merge Branch into master (student's Repo). **Please don't merge your own pull request** -* [ ] Add your project manager as a reviewer on the pull-request -* [ ] Your project manager will count the project as complete by merging the branch back into master. +* [X] Submit a Pull-Request to merge Branch into master (student's Repo). **Please don't merge your own pull request** +* [X] Add your project manager as a reviewer on the pull-request +* [X] Your project manager will count the project as complete by merging the branch back into master. ## Task 2: Higher Order Functions and Callbacks 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. -* [ ] 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. +* [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. -* [ ] Complete the problems provided to you but skip over stretch problems until you are complete with every other JS file first. +* [X] Complete the problems provided to you but skip over stretch problems until you are complete with every other JS file first. ## Task 3: Array Methods 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. -* [ ] Review the contents of the [array-methods.js](assignments/array-methods.js) file. +* [X] Review the contents of the [array-methods.js](assignments/array-methods.js) file. -* [ ] Complete the problems provided to you but skip over stretch problems until you are complete with every other JS file first. +* [X] Complete the problems provided to you but skip over stretch problems until you are complete with every other JS file first. -* [ ] 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. +* [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. ## Task 4: Closures @@ -44,10 +44,10 @@ We have learned that closures allow us to access values in scope that have alrea **Hint: Utilize debugger statements in your code in combination with your developer tools to easily identify closure values.** -* [ ] Review the contents of the [closure.js](assignments/closure.js) file. -* [ ] Complete the problems provided to you but skip over stretch problems until you are complete with every other JS file first. +* [X] Review the contents of the [closure.js](assignments/closure.js) file. +* [X] Complete the problems provided to you but skip over stretch problems until you are complete with every other JS file first. ## Stretch Goals -* [ ] Go back through the stretch problems that you skipped over and complete as many as you can. -* [ ] Look up what an IIFE is in JavaScript and experiment with them \ No newline at end of file +* [X] Go back through the stretch problems that you skipped over and complete as many as you can. +* [X] Look up what an IIFE is in JavaScript and experiment with them \ No newline at end of file diff --git a/assignments/array-methods.js b/assignments/array-methods.js index f692c35c6..2ebd1848a 100644 --- a/assignments/array-methods.js +++ b/assignments/array-methods.js @@ -55,29 +55,86 @@ const runners = [{"id":1,"first_name":"Charmain","last_name":"Seiler","email":"c // ==== Challenge 1: Use .forEach() ==== // The event director needs both the first and last names of each runner for their running bibs. Combine both the first and last names into a new array called fullName. -let fullName = []; +const fullName = []; + +runners.forEach(element => { + + fullName.push(`${element.first_name} ${element.last_name}`); +}); + +console.log("*** Q1 ***"); console.log(fullName); // ==== Challenge 2: Use .map() ==== // The event director needs to have all the runner's first names converted to uppercase because the director BECAME DRUNK WITH POWER. Convert each first name into all caps and log the result -let allCaps = []; +// Explicit approach +const allCaps = runners.map(function(element) { + return element.first_name.toUpperCase(); +}); + +// implicit approach +// let allCaps = runners.map(element => element.first_name.toUpperCase()); + +console.log("\n*** Q2 ***"); console.log(allCaps); // ==== Challenge 3: Use .filter() ==== // The large shirts won't be available for the event due to an ordering issue. Get a list of runners with large sized shirts so they can choose a different size. Return an array named largeShirts that contains information about the runners that have a shirt size of L and log the result -let largeShirts = []; +const largeShirts = runners.filter(function(element) { + return element.shirt_size === "L" +}); + +console.log("\n*** Q3 ***"); console.log(largeShirts); // ==== Challenge 4: Use .reduce() ==== // The donations need to be tallied up and reported for tax purposes. Add up all the donations into a ticketPriceTotal array and log the result -let ticketPriceTotal = []; +const ticketPriceTotal = runners.reduce((total, currentElement) => { + return total += currentElement.donation}, 0); + +console.log("\n*** Q4 ***"); console.log(ticketPriceTotal); // ==== Challenge 5: Be Creative ==== // 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. // Problem 1 +// group donations into 3 buckets - those between 0 and 100, 100 and 200, and 200+, and tally them +const less100 = []; +const more100less200 = []; +const more200 = []; + +runners.forEach(element => { + if (element.donation < 100) { + less100.push(element) + } else if (element.donation < 200){ + more100less200.push(element) + } else if (element.donation >= 200) { + more200.push(element) + } +}); + +console.log("\n*** Q5.1 ***"); +console.log("0-99: " + less100.length); +console.log("100-199: " + more100less200.length); +console.log("200+: " + more200.length); // Problem 2 +// Map the employee and company names of those who raised more than 200, so that we can thank them personally +console.log("\n*** Q5.2 ***"); +const highValueDonators = more200.map(function(element) { + return `${element.first_name} ${element.last_name} - ${element.company_name}`; +}); + +console.log(highValueDonators); + + +// Problem 3 +// Find out what the value is of the average donation, using reduce +let averageDonation = runners.reduce((total, element) => { + return total += element.donation; +}, 0) / runners.length; + +console.log("\n*** Q5.3 ***"); +console.log(averageDonation); -// Problem 3 \ No newline at end of file diff --git a/assignments/callbacks.js b/assignments/callbacks.js index c1c013800..81114fc31 100644 --- a/assignments/callbacks.js +++ b/assignments/callbacks.js @@ -27,29 +27,77 @@ const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum']; function getLength(arr, cb) { // getLength passes the length of the array into the callback. + return cb(arr.length) } +getLength(items, function(length) { + console.log("Q1 Callbacks: " + length); +}) + function last(arr, cb) { // last passes the last item of the array into the callback. + return cb(arr.length - 1); } +last(items, function(lastItem) { + console.log("Q2 Callbacks: " + lastItem); +}) + function sumNums(x, y, cb) { // sumNums adds two numbers (x, y) and passes the result to the callback. + let sum = x + y; + return cb(sum); } +sumNums(5, 9, function(theSum) { + console.log("Q3 Callbacks: " + theSum); +}) + function multiplyNums(x, y, cb) { // multiplyNums multiplies two numbers and passes the result to the callback. + let result = x * y; + return cb(result) } +multiplyNums(10, 3, function(theResult) { + console.log("Q4 Callbacks: " + theResult); +}) + function contains(item, list, cb) { // contains checks if an item is present inside of the given array/list. // Pass true to the callback if it is, otherwise pass false. + for(i = 0; i < list.length; i++){ + if(item === list[i]){ + return cb(true); + } + } + return cb(false); } +contains("Notebook", items, function(booleanValue) { + console.log("Q5.1 Callbacks: " + booleanValue); +}); + +contains("Peanuts", items, function(booleanValue) { + console.log("Q5.2 Callbacks: " + booleanValue); +}); + /* STRETCH PROBLEM */ function removeDuplicates(array, cb) { // removeDuplicates removes all duplicate values from the given array. // Pass the duplicate free array to the callback function. // Do not mutate the original array. + + let newArray = array.map(element => element); // create new array + let uniqueItems = Array.from(new Set(newArray)); // convert array to set and back to Array + return cb(uniqueItems); } + +console.log("*** Stretch Challenge ***"); +items.push("Pencil"); // duplicate item +console.log(items) + +removeDuplicates(items, function(array) { + console.log(array) +}); \ No newline at end of file diff --git a/assignments/closure.js b/assignments/closure.js index 4307524fc..d7101b694 100644 --- a/assignments/closure.js +++ b/assignments/closure.js @@ -1,6 +1,15 @@ // ==== Challenge 1: Write your own closure ==== // Write a simple closure of your own creation. Keep it simple! +function whoLikesIceCream(yourName) { + const name = yourName; + function likesIceCream() { + console.log(`${name} likes ice-cream`) + } + likesIceCream(); +} + +whoLikesIceCream("Isaac"); /* STRETCH PROBLEMS, Do not attempt until you have completed all previous tasks for today's project files */ @@ -8,14 +17,39 @@ // ==== Challenge 2: Create a counter function ==== const counter = () => { // Return a function that when invoked increments and returns a counter variable. + let count = 0; + return function() { + return ++count; + } }; // Example usage: const newCounter = counter(); // newCounter(); // 1 // newCounter(); // 2 +const newCounter = counter(); +console.log(newCounter()); +console.log(newCounter()); // ==== Challenge 3: Create a counter function with an object that can increment and decrement ==== const counterFactory = () => { // Return an object that has two methods called `increment` and `decrement`. // `increment` should increment a counter variable in closure scope and return it. // `decrement` should decrement the counter variable and return it. + + let count = 0; + + return ({ + "increment": () => ++count, + "decrement": () => --count + }) }; + +const newCounterFactory = counterFactory(); +console.log("incremented, now: " + newCounterFactory.increment()); +console.log("incremented, now: " +newCounterFactory.increment()); +console.log("decremented, now: " +newCounterFactory.decrement()); +console.log("incremented, now: " +newCounterFactory.increment()); +console.log("incremented, now: " + newCounterFactory.increment()); +console.log("incremented, now: " +newCounterFactory.increment()); +console.log("decremented, now: " +newCounterFactory.decrement()); +console.log("incremented, now: " +newCounterFactory.increment()); + diff --git a/assignments/iffe.js b/assignments/iffe.js new file mode 100644 index 000000000..c386e1abf --- /dev/null +++ b/assignments/iffe.js @@ -0,0 +1,33 @@ +// function that returns as soon as it is defined + +// approach 1 +(function () { + console.log("My favourite number is 27"); +})(); + +// approach 2 - see last three paranetheses +(function () { + console.log("My favourite number is 17"); +}()); + + + +(favNumber = function (num = 7) { + console.log("My favourite number is " + num); + return num; +})(); + +let favNum = favNumber(37); + +console.log(favNum); + + + +let a = 2; +(function() { + let a = 3; + console.log(a); // uses a from within function +})(); + +console.log(a); + diff --git a/assignments/index.html b/assignments/index.html index d6c2e0f4d..40dc28571 100644 --- a/assignments/index.html +++ b/assignments/index.html @@ -11,6 +11,7 @@ +