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

"studio functios" #58

Open
wants to merge 3 commits into
base: main
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
63 changes: 60 additions & 3 deletions classes/exercises/ClassExercises.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,67 @@
// Define your Book class here:
class Book {
constructor(title, author, copyright, isbn, pages, timesCheckedOut, discarded) {
this.title = title;
this.author = author;
this.copyright = copyright;
this.isbn = isbn;
this.pages = pages;
this.timesCheckedOut = timesCheckedOut;
this.discarded = discarded;

}
checkout() {
this.timesCheckedOut += 1
}
}


// Define your Manual and Novel classes here:
class Manual extends Book {
constructor(title, author, copyright, isbn, pages, timesCheckedOut, discarded) {
super(title, author, copyright, isbn, pages, timesCheckedOut, discarded)
}
dispose(currentYear = new Date().getFullYear()) {
if (currentYear - this.copyright > 5) {
this.discarded = true;
}
}
}

class Novel extends Book {
constructor(title, author, copyright, isbn, pages, timesCheckedOut, discarded) {
super(title, author, copyright, isbn, pages, timesCheckedOut, discarded)
}
dispose() {
if (this.timesCheckedOut > 100) {
this.discarded = true;
}
}
}

// Declare the objects for exercises 2 and 3 here:


// Code exercises 4 & 5 here:
let pride = new Novel(
'Pride and Prejudice',
'Jane Austen',
1813,
'11111111111',
432,
32,
'false'
);
let top = new Manual('Top Secret Shuttle Building Manual',
'Redacted',
2013,
'00000000000',
1147,
1,
'false'
);
// Code exercises 4 & 5 here:
top.dispose();
pride.checkout(5);
console.log(pride.timesCheckedOut);
top.dispose();
pride.dispose();
console.log(top.discarded);
console.log(pride.discarded);
38 changes: 36 additions & 2 deletions classes/studio/ClassStudio.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,41 @@
//Declare a class called CrewCandidate with a constructor that takes three parameters—name, mass, and scores. Note that scores will be an array of test results.
class CrewCandidate {
constructor(name, mass, scores){
this.name = name;
this.mass = mass;
this.scores = scores;
}
addScore(newScore){
this.scores.push(newScore);
}

average(){
const sum = this.scores.reduce((acc, score) => acc + score, 0);
const avg = sum / this.scores.length;
return avg.toFixed(1)
}



status(){
const avg = this.average();
if (avg >= 90){
return "Accepted";
} else if (avg >= 80){
return "Reserve";
} else if (avg >= 70){
return "Probationary";
} else{
return "Rejected";
}
}
}
const bubbaBear = new CrewCandidate('Bubba Bear', 135, [88, 85, 90])
const merryMaltese = new CrewCandidate('Merry Maltese', 1.5, [93, 88, 97])
const gladGator = new CrewCandidate('Glad Gator', 225, [75, 78, 62])
bubbaBear.addScore(83);
console.log(bubbaBear.scores);
console.log(`Merry's average test score of ${merryMaltese.average()}% and has a status of ${merryMaltese.status()}.`);
console.log(`Bubba's average test score of ${bubbaBear.average()}% and has a status of ${bubbaBear.status()}.`);
console.log(`Gator's average test score of ${gladGator.average()}% and has a status of ${gladGator.status()}.`);
//Add methods for adding scores, averaging scores and determining candidate status as described in the studio activity.


Expand Down
20 changes: 19 additions & 1 deletion dom-and-events/exercises/script.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,28 @@
function init () {
const missionAbort = document.getElementById("abortMission");
missionAbort.addEventListener("mouseover", event => {
event.target.style.backgroundColor = "red";
})
missionAbort.addEventListener("mouseout", event => {
event.target.style.backgroundColor = "lightblue";
})
missionAbort.addEventListener("click", event => {
window.alert("Are you sure you want to abort the mission?")
paragraph.innerHTML = "Mission aborted! Damn! Space shuttle returning home..."
})

const button = document.getElementById("liftoffButton");
button.addEventListener("click", event => {
paragraph.innerHTML = "Houston! We have liftoff!";

})
const paragraph = document.getElementById("statusReport");

// Put your code for the exercises here.

}

window.addEventListener("load", init);
window.addEventListener("load", init)



89 changes: 86 additions & 3 deletions functions/studio/studio-functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@
// 4. Below the function, define and initialize a variable to hold a string.
// 5. Use console.log(reverseCharacters(myVariableName)); to call the function and verify that it correctly reverses the characters in the string.
// 6. Optional: Use method chaining to reduce the lines of code within the function.
function reverseCharacters(str){
return str.split('').reverse().join('');
}
let stringy = "hello, world!"

console.log(reverseCharacters(stringy));




// Part Two: Reverse Digits

Expand All @@ -17,6 +26,26 @@
// 4. Return the reversed number.
// 5. Be sure to print the result returned by the function to verify that your code works for both strings and numbers. Do this before moving on to the next exercise.

function reverseCharacters(input) {
if(typeof input === 'string'){
return input.split('').reverse().join('');
}else if(typeof input === 'number'){
const reversedString = input.toString().split('').reverse().join('');
return parseFloat(reversedString) * Math.sign(input);
} else {
return 'Unsupported type';
}
}

let baby = "Hello, Lilah";
let number = 5224;
let negativeNumber = -5224;

console.log(reverseCharacters(baby));
console.log(reverseCharacters(number));
console.log(reverseCharacters(negativeNumber));


// Part Three: Complete Reversal - Create a new function with one parameter, which is the array we want to change. The function should:

// 1. Define and initialize an empty array.
Expand All @@ -25,17 +54,46 @@
// 4. Add the reversed string (or number) to the array defined in part ‘a’.
// 5. Return the final, reversed array.
// 6. Be sure to print the results from each test case in order to verify your code.
function completeReversal(arrayToReverse){
let reversedArray = [];

for(let index of arrayToReverse){
let reversedIndex = reverseCharacters(index);

reversedArray.push(reversedIndex);
}
return reversedArray;
}

let arrayTest1 = ['apple', 'potato', 'Capitalized Words'];
let arrayTest2 = [123, 8897, 42, 1168, 8675309];
let arrayTest3 = ['hello', 'world', 123, 'orange'];
let testArray1 = ["Hello", "Lilah", "12345"];
let testArray2 = [123, -456, "Lauren", 0];
let testArray3 = ["Racecar", 9876, -54321];

console.log(completeReversal(testArray1)); // Output: [ 'olleH', 'dlroW', '54321' ]
console.log(completeReversal(testArray2)); // Output: [ 321, -654, 'cba', 0 ]
console.log(completeReversal(testArray3));
// Bonus Missions

// 1. Have a clear, descriptive name like funPhrase.
// 2. Retrieve only the last character from strings with lengths of 3 or less.
// 3. Retrieve only the first 3 characters from strings with lengths larger than 3.
// 4. Use a template literal to return the phrase We put the '___' in '___'. Fill the first blank with the modified string, and fill the second blank with the original string.
function funPhrase(inputString){
let modifiedString;

if (inputString.length <= 3){
modifiedString = inputString.slice(-1);
}else{
modifiedString = inputString.slice(0,3);
}

return `We put the '${modifiedString}' in '${inputString}'.`;
}
console.log(funPhrase("cat"));
console.log(funPhrase("banana"));
console.log(funPhrase("dog"));
console.log(funPhrase("elephant"));


// Test Function

Expand All @@ -49,3 +107,28 @@ let arrayTest3 = ['hello', 'world', 123, 'orange'];
// 3. Call your area function by passing in two arguments - the length and width.
// 4. If only one argument is passed to the function, then the shape is a square. Modify your code to deal with this case.
// 5. Use a template literal to print, “The area is ____ cm^2.”

let str = "Functions rock!";

console.log(funPhrase(str));

function funPhrase(inputString){
let modifiedString;
if (inputString.length <= 3){
modifiedString = inputString.slice(-1);

}else{
modifiedString = inputString.slice(0,3);
}
return `We put the '${modifiedString}' in '${inputString}'.`;
}

function calculateArea(length, width = length){
return length * width;
}

let rectangleArea = calculateArea(10, 5);
console.log(`The area is '${rectangleArea}' cm^2.`);

let squareArea = calculateArea(7);
console.log(`The area is '${squareArea}' cm^2.`);
74 changes: 56 additions & 18 deletions loops/studio/solution.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,61 +2,99 @@ const input = require('readline-sync');

// Part A: #1 Populate these arrays

let protein = [];
let grains = [];
let veggies = [];
let beverages = [];
let desserts = [];
let protein = ['chicken', 'pork', 'tofu', 'beef', 'fish', 'beans'];
let grains = ['rice', 'pasta', 'corn', 'potato', 'quinoa', 'crackers'];
let veggies = ['peas', 'green beans', 'kale', 'edamame', 'broccoli', 'asparagus'];
let beverages = ['juice', 'milk', 'water', 'soy milk', 'soda', 'tea'];
let desserts = ['apple', 'banana', 'more kale', 'ice cream', 'chocolate', 'kiwi'];


function mealAssembly(protein, grains, veggies, beverages, desserts, numMeals) {
let pantry = [protein, grains, veggies, beverages, desserts];
let meals = [];

/// Part A #2: Write a ``for`` loop inside this function
/// Code your solution for part A #2 below this comment (and above the return statement) ... ///
for (let i = 0; i < numMeals; i++) {

let meal = protein[i] + ", " + grains[i] + ", "
+ veggies[i] + ", " + beverages[i] + ", " + desserts[i];
meals.push(meal);
}

return meals;
}




function askForNumber() {
numMeals = input.question("How many meals would you like to make?");

/// CODE YOUR SOLUTION TO PART B here ///
let numMeals = 0;
let validInput = false;

while (!validInput) {

numMeals = input.question("How many meals would you like to make? (1-6): ");
numMeals = parseInt(numMeals);

if (numMeals >= 1 && numMeals <= 6) {
validInput = true;
}
else {
console.log("Please enter a number between 1 and 6.")
}

}

return numMeals;
}



function generatePassword(string1, string2) {
let code = '';


/// Code your Bonus Mission Solution here ///

for (i = 0; i < string1.length || i < string2.length; i++) {
if (string1.length) {
code += string1[i];
}
if (string2.length) {
code += string2[i];
}
}

return code;
}

console.log(generatePassword("1234", "5678"));
console.log(generatePassword("ABCDEF", "notyet"));
console.log(generatePassword("LoOt", "oku!"));
console.log(generatePassword("yes", "hoe"));

function runProgram() {

const numMeals = askForNumber();
const meals = mealAssembly(protein, grains, veggies, beverages, desserts, numMeals);
console.log("Here are your meals: ")
console.log(meals)
/// TEST PART A #2 HERE ///
/// UNCOMMENT the two lines of code below that invoke the mealAssembly function (starting with 'let meals =') and print the result ///
/// Change the final input variable (aka numMeals) here to ensure your solution makes the right number of meals ///
/// We've started with the number 2 for now. Does your solution still work if you change this value? ///

// let meals = mealAssembly(protein, grains, veggies, beverages, desserts, 2);
// console.log(meals)


/// TEST PART B HERE ///
/// UNCOMMENT the next two lines to test your ``askForNumber`` solution ///
/// Tip - don't test this part until you're happy with your solution to part A #2 ///


// TEST PART B HERE
// UNCOMMENT the next two lines to test your ``askForNumber`` solution ///
// Tip - don't test this part until you're happy with your solution to part A #2 ///

// let mealsForX = mealAssembly(protein, grains, veggies, beverages, desserts, askForNumber());
// console.log(mealsForX);

/// TEST PART C HERE ///
/// TEST PART C HERE ///
/// UNCOMMENT the remaining commented lines and change the password1 and password2 strings to ensure your code is doing its job ///

// let password1 = '';
Expand Down
Loading