diff --git a/README.md b/README.md index 6288977c2..69346c133 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ - + # JavaScript - II 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. diff --git a/assignments/array-methods.js b/assignments/array-methods.js index f692c35c6..40238453e 100644 --- a/assignments/array-methods.js +++ b/assignments/array-methods.js @@ -54,30 +54,142 @@ const runners = [{"id":1,"first_name":"Charmain","last_name":"Seiler","email":"c {"id":50,"first_name":"Shell","last_name":"Baine","email":"sbaine1d@intel.com","shirt_size":"M","company_name":"Gabtype","donation":171}]; // ==== 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. +// 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 = []; -console.log(fullName); + +runners.forEach((item, index, array) => { + console.log(runners[index].first_name + " " + runners[index].last_name); + + fullName.push(runners[index].first_name + " " + runners[index].last_name); + console.log(fullName[index]); + +}); // ==== 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 = []; +// 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 = runners.map(runner => runner.first_name.toUpperCase());; 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 = []; -console.log(largeShirts); +const newRunnersData = runners.filter(runner => { + return runner.shirt_size === "L"; +}) + +console.log(newRunnersData); // ==== 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 +// 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 = []; -console.log(ticketPriceTotal); + +ticketPriceTotal = runners.map(runner => runner.donation); + +let reducedValue = ticketPriceTotal.reduce((acc, cur) => acc + cur); +console.log(reducedValue); // ==== 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. +// 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 +// Get the names of those who donated the most. +let donationData = []; +donationData = runners.map(runner => runner.first_name, runner => runner.last_name); +console.log(donationData); + +// keep track of highest donation and who made it +var highestDonation = 0; +var highestDonator = ""; + +// for each runner in the array, check donation amount, +// if higher than last, its the new highest donation +// and donation amount and donator are stored +runners.forEach((runner) => { + if(runner.donation > highestDonation){ + highestDonation = runner.donation; + highestDonator = (runner.first_name + " " + runner.last_name); + } +}) +// Console log out highest donator +console.log(highestDonator, highestDonation); + // Problem 2 +// Some crazy person wants to know if shirt size is +// somehow corrilated with donation ammout! +let shirtsL = []; +let shirtsS = []; +let lGroup = []; +let rGroup = []; + +// then use getAverageOfDonations(arr) fucntion to get avrages +// declare some variables for keeping track of our data +// then +function getGroupsDonationsByShirtSize(){ + var shirtLAvg; + var shirtSAvg; + var greaterAvg; + + // Use filter to take all donations and place in corrosponding array + // by shirt size + const getShirtData = runners.filter(runner => { + if(runner.shirt_size === "L"){ + shirtsL.push(runner.donation); + } + if(runner.shirt_size === "S"){ + shirtsS.push(runner.donation); + } + }) + + // calculate average of an array of values + function getAverageOfDonations(arr){ + var donationAvg = arr.reduce((a,b) => a + b, 0) / arr.length; + return donationAvg; + } + + // I could then use the function getAverageOfDonations and pass + // each array that where previously catagorized by shirt size + // with each element being a donation value of someone with + // either L or S shirt sizes. + shirtLAvg = getAverageOfDonations(shirtsL); + shirtSAvg = getAverageOfDonations(shirtsS); + + // Check which average is greater and we set our variables to + // reflect the data found + if(shirtLAvg > shirtSAvg){ + greaterAvg = "The higher avg for donations was by shirt size of L at the amount " + shirtLAvg; + console.log("Higher avg found"); + }else if(shirtSAvg > shirtLAvg){ + greaterAvg = "The higher avg for donations was by shirt size of S at the amount " + shirtSAvg; + console.log("Higher avg found"); + }else if(shirtSAvg == shirtLAvg){ + greaterAvg = "Shirt sizes L and shirt sizes S donated roughly the same amount"; + console.log("Higher avg found"); + } + console.log(greaterAvg); +} + +getGroupsDonationsByShirtSize(); + +// Problem 3 +// Someone needs to know everyone who works for a company whose company +// name starts with a G +var coStartWithG = []; +const coNameStartWithG = runners.filter(doesCoStartWithG); -// Problem 3 \ No newline at end of file +function doesCoStartWithG(runner){ + if(runner.company_name[0] === "G"){ + return true; + }else{ + return false; + } +} +console.log(coNameStartWithG); \ No newline at end of file diff --git a/assignments/callbacks.js b/assignments/callbacks.js index c1c013800..1fef0e0ac 100644 --- a/assignments/callbacks.js +++ b/assignments/callbacks.js @@ -1,4 +1,7 @@ -// Create a higher order function and invoke the callback function to test your work. You have been provided an example of a problem and a solution to see how this works with our items array. Study both the problem and the solution to figure out the rest of the problems. +// Create a higher order function and invoke the callback +//function to test your work. You have been provided an +//example of a problem and a solution to see how this works with our items array. +//Study both the problem and the solution to figure out the rest of the problems. const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum']; @@ -23,27 +26,38 @@ const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum']; }); */ - +getLength(items, function(len){ + console.log(len); +}); function getLength(arr, cb) { // getLength passes the length of the array into the callback. + return cb(arr.length); } function last(arr, cb) { // last passes the last item of the array into the callback. + return cb(arr[arr.length]); } function sumNums(x, y, cb) { // sumNums adds two numbers (x, y) and passes the result to the callback. + return cb(x + y); } function multiplyNums(x, y, cb) { // multiplyNums multiplies two numbers and passes the result to the callback. + return cb(x * y); } 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. + if(list.includes(item)){ + return cb(true); + }else{ + console.log("FAIL"); + } } /* STRETCH PROBLEM */ @@ -52,4 +66,12 @@ 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. + + var uniqueSet = new Set(array); + var backToArray = [...uniqueSet]; + + return cb(backToArray); + } + +removeDuplicates(items, (unique) => {}); diff --git a/assignments/closure.js b/assignments/closure.js index 4307524fc..05350947f 100644 --- a/assignments/closure.js +++ b/assignments/closure.js @@ -1,21 +1,52 @@ // ==== Challenge 1: Write your own closure ==== // Write a simple closure of your own creation. Keep it simple! +var outerData = [10, 20, 97]; +function addOuter(outer){ + var cnt = 0; // only accessible from within addOuter + outer.forEach((val, item) => { + cnt += val; + + }) + //console.log(cnt); + return cnt; +} +console.log(addOuter(outerData)); -/* STRETCH PROBLEMS, Do not attempt until you have completed all previous tasks for today's project files */ + +/* STRETCH PROBLEMS, Do not attempt until you have completed +all previous tasks for today's project files */ // ==== Challenge 2: Create a counter function ==== -const counter = () => { - // Return a function that when invoked increments and returns a counter variable. + +const counter = (interval, name) => { + // Return a function that when invoked increments and + // returns a counter variable. + var cnt = 0; + setInterval(timeIt, interval); + + // timeIt function can take a function as argument for either + // increment or decrement + function timeIt(){ + console.log(name + cnt); + cnt++; + } + + }; + + // Example usage: const newCounter = counter(); // newCounter(); // 1 // newCounter(); // 2 +//counter(500, "c one "); +//counter(2000, "c two "); + // ==== 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. -}; +}; \ No newline at end of file diff --git a/assignments/index.html b/assignments/index.html index d6c2e0f4d..dcf13093e 100644 --- a/assignments/index.html +++ b/assignments/index.html @@ -7,10 +7,10 @@