Skip to content
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
91 changes: 82 additions & 9 deletions assignments/array-methods.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// A local community center is holding a fund raising 5k fun run and has invited 50 small businesses to make a small donation on their behalf for some much needed updates to their facilities. Each business has assigned a representative to attend the event along with a small donation.

// Scroll to the bottom of the list to use some advanced array methods to help the event director gather some information from the businesses.
console.log('########## Array Methods ##########');

const runners = [
{ id: 1, first_name: "Charmain", last_name: "Seiler", email: "[email protected]", shirt_size: "2XL", company_name: "Divanoodle", donation: 75 },
Expand Down Expand Up @@ -55,31 +56,103 @@ const runners = [
{ id: 50, first_name: "Shell", last_name: "Baine", email: "[email protected]", shirt_size: "M", company_name: "Gabtype", donation: 171 },
];

const msg = (val) => {
return JSON.stringify(val,null,'\t').replace(/,/g,'');
}

const display = (elId,msg) =>{
let list = []
if(Array.isArray(msg)){
msg = msg.map((m)=> `${m} <br/>`);

if(msg.length > 5){

for(let i = 0; i < 5; i++){

list.push(msg[i])
}

list.push('(The rest is in console.)')
}

else{

msg.map((item)=> list.push(item).toString())
}
}
else{

list.push(msg)
}
document.getElementById(elId).innerHTML += list.toString().replace(/,/g,'');

}

// ==== 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 and populate a new array called `fullNames`. This array will contain just strings.
let fullNames = [];
console.log(fullNames);
let fullNames = runners.map((person)=> `${person.first_name} ${person.last_name}`);
display('aChallenge1',fullNames)
console.log(msg(fullNames));

// ==== Challenge 2: Use .map() ====
// 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.
let firstNamesAllCaps = [];
console.log(firstNamesAllCaps);
let firstNamesAllCaps = runners.map((person) => `${person.last_name.toUpperCase()}`);
display('aChallenge2',firstNamesAllCaps)
console.log(msg(firstNamesAllCaps));

// ==== Challenge 3: Use .filter() ====
// 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.
let runnersLargeSizeShirt = [];
console.log(runnersLargeSizeShirt);
let runnersLargeSizeShirt = runners.filter((person)=> person.shirt_size === 'L');
let list = [];
runnersLargeSizeShirt.map((m)=> list.push(`ID: ${m.id} \t ${m.first_name} ${m.last_name}`))
display('aChallenge3', list)
console.log(msg(runnersLargeSizeShirt));

// ==== Challenge 4: Use .reduce() ====
// 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.
let ticketPriceTotal = 0;
let ticketPriceTotal = 0
runners.forEach((person) => ticketPriceTotal+= person.donation);
display('aChallenge4', ticketPriceTotal);
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

display('aChallenge5','<h3>Problem 1</h3>')
//Coach needs everyone with the sponsor of Jabbersphere
let peopleSpons = [];
let sponsered = runners.filter((r)=> r.company_name==='Jabbersphere')
sponsered.map((s) => peopleSpons.push(`ID: ${s.id} \t ${s.first_name} ${s.last_name}`));
display('aChallenge5', peopleSpons);
console.log(msg(sponsered));
// Problem 2
display('aChallenge5','<h3>Problem 2</h3>')
//Coach needs everyone that donated more than 100
let over100 = runners.filter((m)=> m.donation > 100);
let bangers = over100.map((b) => `ID: ${b.id} \t ${b.first_name} ${b.last_name}`)
display('aChallenge5', bangers);
console.log(msg(over100))

// Problem 3
display('aChallenge5','<h3>Problem 3</h3>')
//Coach needs 3 random people
let randomNum = (min = 0, max = runners.length) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
let num=[]
for(i=0; i<3;i++){
num.push(randomNum())
}

// Problem 3
let randomPeople = [];
num.map((x)=>{
runners.filter((i) =>{
if(i.id===x){
randomPeople.push(`ID: ${i.id} \t ${i.first_name} ${i.last_name}`)
}})
})
display('aChallenge5',randomPeople);
console.log(msg(randomPeople))
28 changes: 25 additions & 3 deletions assignments/callbacks.js
Original file line number Diff line number Diff line change
@@ -1,9 +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.

const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum'];
const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum','yo-yo'];

/*

// GIVEN THIS PROBLEM:

function firstItem(arr, cb) {
Expand Down Expand Up @@ -41,23 +39,28 @@ 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);
}

function last(arr, cb) {
// last passes the last item of the array into the callback.
return cb(arr[arr.length-1])
}

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.
return cb(list.includes(item))
}

/* STRETCH PROBLEM */
Expand All @@ -67,3 +70,22 @@ function removeDuplicates(array, cb) {
// Pass the duplicate free array to the callback function.
// Do not mutate the original array.
}

display('cChallenge1',getLength(items,length => `The Length of the array is: ${length}`));
console.log(getLength(items,length => `The Length of the array is: ${length}`));


display('cChallenge2',last(items,last => `The last item of the array is: ${last}`));
console.log(msg(last(items,last => `The last item of the array is: ${last}`)));


display('cChallenge3',sumNums(2,2,total => `2+2= ${total}`));
console.log(msg(sumNums(2,2,total => `2+2= ${total}`)));


display('cChallenge4',multiplyNums(2,2,total => `2x2= ${total}`))
console.log(msg(multiplyNums(2,2,total => `2x2= ${total}`)));


display('cChallenge5',contains('Gum',items,contained => `${contained}`))
console.log(msg(contains('Gum',items,contained => `${contained}`)));
45 changes: 44 additions & 1 deletion assignments/closure.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,48 @@
// that manipulates variables defined in the outer scope.
// The outer scope can be a parent function, or the top level of the script.

let context = 'Hi there';
console.log(context)
function parent(){
context = `Havn't we met before?`;
console.log(context);
function grandparent(){
context = `I swear I've seen you...`
console.log(context)
}
grandparent();
}
parent();


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


// ==== Challenge 2: Implement a "counter maker" function ====
const counterMaker = () => {
const counterMaker = (limit =5) => {
// IMPLEMENTATION OF counterMaker:
// 1- Declare a `count` variable with a value of 0. We will be mutating it, so declare it using `let`!
// 2- Declare a function `counter`. It should increment and return `count`.
// NOTE: This `counter` function, being nested inside `counterMaker`,
// "closes over" the `count` variable. It can "see" it in the parent scope!
// 3- Return the `counter` function.
let count = 0;
function counter(){
count+=1;
if (count > limit){count = 1}
return count;
}
return counter
};

const myCounter = counterMaker()

console.log(myCounter());
console.log(myCounter());
console.log(myCounter());
console.log(myCounter());
console.log(myCounter());
console.log(myCounter());
// Example usage: const myCounter = counterMaker();
// myCounter(); // 1
// myCounter(); // 2
Expand All @@ -30,4 +59,18 @@ 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 object = {
'increment':function(){
return count+= 1;
},
'decrement':function(){
return count-= 1;
}
}

};
const countMe =counterFactory();
console.log(countMe.increment());
console.log(countMe.increment());
console.log(countMe.increment());
79 changes: 75 additions & 4 deletions assignments/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,84 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>JS II</title>
</head>

<body>
<h1>JS II - Check your work in the console!... or NOT!</h1>
<section style="background: lightgrey; padding: 1%;">
<h2>
Array Methods
</h2>
<div>
<h2>
Challenge 1
</h2>
<p id="aChallenge1" style="white-space: pre-wrap;"></p>
</div>
<div>
<h2>
Challenge 2
</h2>
<p id="aChallenge2" style="white-space: pre-wrap;"></p>
</div>
<div>
<h2>
Challenge 3
</h2>
<p id="aChallenge3" style="white-space: pre-wrap;"></p>
</div>
<div>
<h2>
Challenge 4
</h2>
<p id="aChallenge4" style="white-space: pre-wrap;"></p>
</div>
<div>
<h2>
Challenge 5
</h2>
<p id="aChallenge5" style="white-space: pre-wrap;"></p>
</div>
</section>

<section style="background: lightgoldenrodyellow; padding: 1%;">
<h2>
Callbacks
</h2>
<div>
<h2>
Challenge 1
</h2>
<p id="cChallenge1" style="white-space: pre-wrap;"></p>
</div>
<div>
<h2>
Challenge 2
</h2>
<p id="cChallenge2" style="white-space: pre-wrap;"></p>
</div>
<div>
<h2>
Challenge 3
</h2>
<p id="cChallenge3" style="white-space: pre-wrap;"></p>
</div>
<div>
<h2>
Challenge 4
</h2>
<p id="cChallenge4" style="white-space: pre-wrap;"></p>
</div>
<div>
<h2>
Challenge 5
</h2>
<p id="cChallenge5" style="white-space: pre-wrap;"></p>
</div>
</section>
<script src="array-methods.js"></script>
<script src="callbacks.js"></script>
<script src="closure.js"></script>
</head>

<body>
<h1>JS II - Check your work in the console!</h1>
</body>

</html>