diff --git a/arrays/exercises/part-five-arrays.js b/arrays/exercises/part-five-arrays.js index 4cdf1bba41..09b91ddf7c 100644 --- a/arrays/exercises/part-five-arrays.js +++ b/arrays/exercises/part-five-arrays.js @@ -3,9 +3,19 @@ let arr = ['B', 'n', 'n', 5]; //1) Use the split method on the string to identify the purpose of the parameter inside the (). +console.log(str.split("")); // splits the string by individual characters into an array. +console.log(str.split(" ")); // splits the string and separates by one space into an array. + //2) Use the join method on the array to identify the purpose of the parameter inside the (). +console.log(arr.join("")); // joins together the elements of an array into a string with nothing inbetween. +console.log(arr.join(" ")); // joins together the elements of an array into a string with what is inside the parameter. + //3) Do split or join change the original string/array? +// NO. Split and join do not change the original string/array. + //4) We can take a comma-separated string and convert it into a modifiable array. Try it! Alphabetize the cargoHold string, and then combine the contents into a new string. let cargoHold = "water,space suits,food,plasma sword,batteries"; + +console.log(cargoHold.split(",").sort().join(",")); \ No newline at end of file diff --git a/arrays/exercises/part-four-arrays.js b/arrays/exercises/part-four-arrays.js index 498149702e..b1396582c6 100644 --- a/arrays/exercises/part-four-arrays.js +++ b/arrays/exercises/part-four-arrays.js @@ -5,6 +5,31 @@ let holdCabinet2 = ['orange drink', 'nerf toys', 'camera', 42, 'parsnip']; //1) Print the result of using concat on the two arrays. Does concat alter the original arrays? Verify this by printing holdCabinet1 after using the method. +let holdCabinet = holdCabinet1.concat(holdCabinet2); +console.log(holdCabinet); +console.log(holdCabinet1); + +// .concat() does not alter the original arrays. + //2) Print a slice of two elements from each array. Does slice alter the original arrays? +holdCabinet1.slice(1, 2); +console.log(holdCabinet1); +console.log(holdCabinet1.slice(1, 2)); + +holdCabinet2.slice(0, 2); +console.log(holdCabinet2); +console.log(holdCabinet2.slice(0, 2)); + +// .slice() does not alter the original arrays. + //3) reverse the first array, and sort the second. What is the difference between these two methods? Do the methods alter the original arrays? + +holdCabinet1.reverse(); +console.log(holdCabinet1); + +holdCabinet2.sort(); +console.log(holdCabinet2); + +// .reverse() reverses the array and .sort() sorts the array (number accending, then alphabetical) +// the methods do change the arrays \ No newline at end of file diff --git a/arrays/exercises/part-one-arrays.js b/arrays/exercises/part-one-arrays.js index 92f4e45170..143b92806b 100644 --- a/arrays/exercises/part-one-arrays.js +++ b/arrays/exercises/part-one-arrays.js @@ -1,5 +1,17 @@ //Create an array called practiceFile with the following entry: 273.15 +let practiceFile = [273.15]; +console.log(practiceFile); + //Use the bracket notation method to add "42" and "hello" to the array. Add these new items one at a time. Print the array after each step to confirm the changes. +practiceFile[1] = 42; +console.log(practiceFile); + +practiceFile[2] = "hello"; +console.log(practiceFile); + //Use a single .push() to add the following items: false, -4.6, and "87". Print the array to confirm the changes. + +practiceFile.push(false, -4.6, "87"); +console.log(practiceFile); \ No newline at end of file diff --git a/arrays/exercises/part-six-arrays.js b/arrays/exercises/part-six-arrays.js index d0a28bed56..63f6a66d22 100644 --- a/arrays/exercises/part-six-arrays.js +++ b/arrays/exercises/part-six-arrays.js @@ -2,10 +2,64 @@ //1) Define and initialize the arrays specified in the exercise to hold the name, chemical symbol and mass for different elements. +let element1 = ['hydrogen', 'H', 1.008]; +let element2 = ['helium', 'He', 4.003]; +let element26 = ['iron', 'Fe', 55.85]; + //2) Define the array 'table', and use 'push' to add each of the element arrays to it. Print 'table' to see its structure. +let table = []; + +table.push(element1, element2, element26); + +console.log(table); + //3) Use bracket notation to examine the difference between printing 'table' with one index vs. two indices (table[][]). +console.log(table[0]); +console.log(table[1]); +console.log(table[2]); + +console.log(table[0][0]); +console.log(table[0][1]); +console.log(table[0][2]); + +console.log(table[1][0]); +console.log(table[1][1]); +console.log(table[1][2]); + +console.log(table[2][0]); +console.log(table[2][1]); +console.log(table[2][2]); + //4) Using bracket notation and the table array, print the mass of element1, the name for element 2 and the symbol for element26. +console.log(`Mass of element1: ${table[0][2]}`); + +console.log(`Name of element2: ${table[1][0]}`); + +console.log(`Symbol of element26: ${table[2][1]}`); + //5) 'table' is an example of a 2-dimensional array. The first “level” contains the element arrays, and the second level holds the name/symbol/mass values. Experiment! Create a 3-dimensional array and print out one entry from each level in the array. + +let threeD = [ + [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] + ], + [ + [10, 11, 12], + [13, 14, 15], + [16, 17, 18] + ], + [ + [19, 20, 21], + [22, 23, 24], + [25, 26, 27] + ] +] + +console.log(threeD[1]); +console.log(threeD[0][1]); +console.log(threeD[2][0][1]); \ No newline at end of file diff --git a/arrays/exercises/part-three-arrays.js b/arrays/exercises/part-three-arrays.js index d43918a702..40339680f6 100644 --- a/arrays/exercises/part-three-arrays.js +++ b/arrays/exercises/part-three-arrays.js @@ -4,6 +4,15 @@ let cargoHold = [1138, 'space suits', 'parrot', 'instruction manual', 'meal pack //1) Insert the string 'keys' at index 3 without replacing any other entries. +cargoHold.splice(3, 0, 'keys'); +console.log(cargoHold); + //2) Remove ‘instruction manual’ from the array. (Hint: indexOf is helpful to avoid manually counting an index). +cargoHold.splice(cargoHold.indexOf('instruction manual'), 1); +console.log(cargoHold); + //3) Replace the elements at indexes 2 - 4 with the items ‘cat’, ‘fob’, and ‘string cheese’. + +cargoHold.splice(2, 3, 'cat', 'fob', 'string cheese'); +console.log(cargoHold); \ No newline at end of file diff --git a/arrays/exercises/part-two-arrays.js b/arrays/exercises/part-two-arrays.js index a940b1d0ff..dd88a05815 100644 --- a/arrays/exercises/part-two-arrays.js +++ b/arrays/exercises/part-two-arrays.js @@ -2,10 +2,29 @@ let cargoHold = ['oxygen tanks', 'space suits', 'parrot', 'instruction manual', //1) Use bracket notation to replace ‘slinky’ with ‘space tether’. Print the array to confirm the change. +cargoHold[5] = 'space tether'; +console.log(cargoHold); + //2) Remove the last item from the array with pop. Print the element removed and the updated array. +let lastItem = cargoHold.pop(); +console.log(lastItem); +console.log(cargoHold); + //3) Remove the first item from the array with shift. Print the element removed and the updated array. +let firstItem = cargoHold.shift(); +console.log(firstItem); +console.log(cargoHold); + //4) Unlike pop and shift, push and unshift require arguments inside the (). Add the items 1138 and ‘20 meters’ to the the array - the number at the start and the string at the end. Print the updated array to confirm the changes. +cargoHold.unshift(1138); +cargoHold.push('20 meters'); +console.log(cargoHold); + //5) Use a template literal to print the final array and its length. + +console.log( +`Array: ${cargoHold} +Length: ${cargoHold.length}.`); \ No newline at end of file diff --git a/arrays/studio/array-string-conversion/array-testing.js b/arrays/studio/array-string-conversion/array-testing.js index c4d5899385..ea8081e780 100644 --- a/arrays/studio/array-string-conversion/array-testing.js +++ b/arrays/studio/array-string-conversion/array-testing.js @@ -8,9 +8,14 @@ strings = [protoArray1, protoArray2, protoArray3, protoArray4]; //2) function reverseCommas() { //TODO: 1. create and instantiate your variables. - let check; + let check = protoArray1.includes(","); + + let output; //TODO: 2. write the code required for this step + if (check) { + output = protoArray1.split(",").reverse().join(","); + } //NOTE: For the code to run properly, you must return your output. this needs to be the final line of code within the function's { }. return output; @@ -18,29 +23,37 @@ function reverseCommas() { //3) function semiDash() { - let check; + let check = protoArray2.includes(";"); let output; //TODO: write the code required for this step - + if (check) { + output = protoArray2.split(";").sort().join("-"); + } return output; } //4) function reverseSpaces() { - let check; + let check = protoArray3.includes(" "); let output; //TODO: write the code required for this step + if (check) { + output = protoArray3.split(" ").sort().reverse().join(" "); + } return output; } //5) function commaSpace() { - let check; + let check = protoArray4.includes(", "); let output; //TODO: write the code required for this step - + if (check) { + output = protoArray4.split(", ").reverse().join(","); + } + return output; } diff --git a/arrays/studio/multi-dimensional-arrays.js b/arrays/studio/multi-dimensional-arrays.js index 18761a8934..ca3169813d 100644 --- a/arrays/studio/multi-dimensional-arrays.js +++ b/arrays/studio/multi-dimensional-arrays.js @@ -1,3 +1,5 @@ +const input = require('readline-sync'); + let food = "water bottles,meal packs,snacks,chocolate"; let equipment = "space suits,jet packs,tool belts,thermal detonators"; let pets = "parrots,cats,moose,alien eggs"; @@ -5,10 +7,48 @@ let sleepAids = "blankets,pillows,eyepatches,alarm clocks"; //1) Use split to convert the strings into four cabinet arrays. Alphabetize the contents of each cabinet. +let foodArr = food.split(",").sort(); +console.log(foodArr); + +let equipmentArr = equipment.split(",").sort(); +console.log(equipmentArr); + +let petsArr = pets.split(",").sort(); +console.log(petsArr); + +let sleepAidsArr = sleepAids.split(",").sort(); +console.log(sleepAidsArr); + //2) Initialize a cargoHold array and add the cabinet arrays to it. Print cargoHold to verify its structure. +let cargoHold = []; + +cargoHold.push(foodArr, equipmentArr, petsArr, sleepAidsArr); +console.log(cargoHold); + //3) Query the user to select a cabinet (0 - 3) in the cargoHold. +let selectCabinet = input.question("Choose a number (0, 1, 2, or 3): "); + //4) Use bracket notation and a template literal to display the contents of the selected cabinet. If the user entered an invalid number, print an error message. +if (selectCabinet >= 0 && selectCabinet <= 3) { + console.log(`The contents of the selected canbinet: ${cargoHold[selectCabinet]}`); +} else { + console.error(`The number ${selectCabinet} is out of range.`); +} + //5) Modify the code to query the user for BOTH a cabinet in cargoHold AND a particular item. Use the 'includes' method to check if the cabinet contains the selected item, then print “Cabinet ____ DOES/DOES NOT contain ____.” + +let num = input.question("Choose a number (0, 1, 2, or 3): "); +let item = input.question("What item are you looking for?: "); + +if (num >= 0 && num <= 3) { + if (cargoHold[num].includes(item.trim().toLowerCase())) { + console.log(`Cabinet ${num} DOES contain ${item}.`); + } else { + console.log(`Cabinet ${num} DOES NOT contain ${item}.`); + } +} else { + console.error(`The number ${num} is out of range.`); +} \ No newline at end of file diff --git a/arrays/studio/string-modification.js b/arrays/studio/string-modification.js index 45991b15fc..1deeda55c3 100644 --- a/arrays/studio/string-modification.js +++ b/arrays/studio/string-modification.js @@ -4,8 +4,30 @@ let str = "LaunchCode"; //1) Use string methods to remove the first three characters from the string and add them to the end. //Hint - define another variable to hold the new string or reassign the new string to str. +let firstThree = str.slice(0, 3); +let last = str.slice(3) +console.log(last.concat(firstThree)); + //Use a template literal to print the original and modified string in a descriptive phrase. //2) Modify your code to accept user input. Query the user to enter the number of letters that will be relocated. +let num = input.question("Enter a number: "); +let part1 = ''; +let part2 = ''; +let combined = ''; + //3) Add validation to your code to deal with user inputs that are longer than the word. In such cases, default to moving 3 characters. Also, the template literal should note the error. + +if (num > str.length) { + part1 = str.slice(0, 3); + part2 = str.slice(3); + combined = part2.concat(part1); + console.log(`Number entered, ${num}, is greater than the length of the string 'LaunchCode', ${str.length}. + Returning default, with num = 3: ${combined}`); +} else { + part1 = str.slice(0, num); + part2 = str.slice(num); + combined = part2.concat(part1); + console.log(`With num = ${num}, the first ${num} letters moved to the end looks like this: ${combined}`); +} \ No newline at end of file diff --git a/booleans-and-conditionals/exercises/part-1.js b/booleans-and-conditionals/exercises/part-1.js index b829140a07..7392b64eb0 100644 --- a/booleans-and-conditionals/exercises/part-1.js +++ b/booleans-and-conditionals/exercises/part-1.js @@ -1,5 +1,12 @@ // Declare and initialize the variables for exercise 1 here: +let engineIndicatorLight = "red blinking"; +let spaceSuitsOn = true; +let shuttleCabinReady = true; +let crewStatus = spaceSuitsOn && shuttleCabinReady; +let computerStatusCode = 200; +let shuttleSpeed = 15000; + // BEFORE running the code, predict what will be printed to the console by the following statements: if (engineIndicatorLight === "green") { diff --git a/booleans-and-conditionals/exercises/part-2.js b/booleans-and-conditionals/exercises/part-2.js index ff11fbab8a..ba519a5ef1 100644 --- a/booleans-and-conditionals/exercises/part-2.js +++ b/booleans-and-conditionals/exercises/part-2.js @@ -9,13 +9,34 @@ let shuttleSpeed = 15000; // a) If crewStatus is true, print "Crew Ready" else print "Crew Not Ready". +if (crewStatus === true) { + console.log("Crew Ready"); +} else { + console.log("Crew Not Ready"); +} // b) If computerStatusCode is 200, print "Please stand by. Computer is rebooting." Else if computerStatusCode is 400, print "Success! Computer online." Else print "ALERT: Computer offline!" +if (computerStatusCode === 200) { + console.log("Please stand by. Computer is rebooting."); +} else if (computerStatusCode === 400) { + console.log("Sucess! Computer online."); +} else { + console.log("ALERT: Computer offline!"); +} // c) If shuttleSpeed is > 17,500, print "ALERT: Escape velocity reached!" Else if shuttleSpeed is < 8000, print "ALERT: Cannot maintain orbit!" Else print "Stable speed". +if (shuttleSpeed > 17500) { + console.log("ALERT: Escape velocity reached!"); +} else if (shuttleSpeed < 8000) { + console.log("ALERT: Cannot maintain orbit!"); +} else { + console.log("Stable speed"); +} // 4) PREDICT: Do the code blocks shown in the 'predict.txt' file produce the same result? -console.log(/* "Yes" or "No" */); +console.log("Yes"); + + diff --git a/booleans-and-conditionals/exercises/part-3.js b/booleans-and-conditionals/exercises/part-3.js index 9ed686d097..65789e5fa4 100644 --- a/booleans-and-conditionals/exercises/part-3.js +++ b/booleans-and-conditionals/exercises/part-3.js @@ -18,7 +18,39 @@ f) Otherwise, print "Fuel and engine status pending..." */ // Code 5a - 5f here: +if (fuelLevel < 1000 || engineTemperature > 3500 || engineIndicatorLight === "red blinking") { + console.log("ENGINE FAILURE IMMINENT!"); +} else if (fuelLevel <= 5000 || engineTemperature > 2500) { + console.log("Check fuel level. Engines running hot."); +} else if (fuelLevel > 20000 && engineTemperature <= 2500) { + console.log("Full tank. Engines good."); +} else if (fuelLevel > 10000 && engineTemperature <= 2500) { + console.log("Fuel level above 50%. Engines good."); +} else if (fuelLevel > 5000 && engineTemperature <= 2500) { + console.log("Fuel level above 25%. Engines good."); +} else { + console.log("Fuel and engine status pending..."); +} + // 6) a) Create the variable commandOverride, and set it to be true or false. If commandOverride is false, then the shuttle should only launch if the fuel and engine check are OK. If commandOverride is true, then the shuttle will launch regardless of the fuel and engine status. +let commandOverride = false; + +if (!commandOverride) { + if (fuelLevel > 20000 && engineTemperature <= 2500) { + console.log("Full tank. Engines good."); + } +} + +if (commandOverride) { + console.log("Override initiated. Prepare to launch."); +} + /* 6) b) Code the following if/else check: If fuelLevel is above 20000 AND engineIndicatorLight is NOT red blinking OR commandOverride is true print "Cleared to launch!" Else print "Launch scrubbed!" */ + +if ((fuelLevel > 20000 && engineIndicatorLight !== "red blinking") || commandOverride === true) { + console.log("Cleared to launch!"); +} else { + console.log("Launch scrubbed!"); +} \ No newline at end of file diff --git a/booleans-and-conditionals/studio/data-variables-conditionals.js b/booleans-and-conditionals/studio/data-variables-conditionals.js index 6a15e146f4..2bbdeb231d 100644 --- a/booleans-and-conditionals/studio/data-variables-conditionals.js +++ b/booleans-and-conditionals/studio/data-variables-conditionals.js @@ -1,5 +1,22 @@ // Initialize Variables below +let date = "Monday 2019-03-18" +let time = "10:05:34 AM" +let astronautCount = 7 +let astronautStatus = "ready" +let averageAstronautMassKg = 80.7 +let crewMassKg = astronautCount * averageAstronautMassKg +let fuelMassKg = 760000 +let shuttleMassKg = 74842.31 +let totalMassKg = crewMassKg + fuelMassKg + shuttleMassKg +let maximumMassLimit = 850000 +let fuelTempCelsius = -225 +let minimumFuelTemp = -300 +let maximumFuelTemp = -150 +let fuelLevel = 100 +let weatherStatus = "clear" +let preparedForLiftOff = true + // add logic below to verify total number of astronauts for shuttle launch does not exceed 7 // add logic below to verify all astronauts are ready @@ -13,3 +30,22 @@ // add logic below to verify the weather status is clear // Verify shuttle launch can proceed based on above conditions + +if ((astronautCount <= 7) && (astronautStatus === 'ready') && (totalMassKg < maximumMassLimit) && (fuelTempCelsius >= minimumFuelTemp || fuelTempCelsius <= maximumFuelTemp) && (fuelLevel === 100) && (weatherStatus === 'clear')) { + console.log( + "All systems are a go! Initiating space shuttle launch sequence.\n" + + "----------------------------------------------------------------\n" + + "Date: " + date + "\n" + + "Time: " + time + "\n" + + "Astronaught Count: " + astronautCount + "\n" + + "Crew Mass: " + crewMassKg + " kg\n" + + "Fuel Mass: " + fuelMassKg + " kg\n" + + "Shuttle Mass: " + shuttleMassKg + " kg\n" + + "Total Mass: " + totalMassKg + " kg\n" + + "Fuel Temperature: " + fuelTempCelsius + " °C\n" + + "Weather Status: " + weatherStatus + "\n" + + "----------------------------------------------------------------\n" + + "Have a safe trip astronauts!" + ); +} + diff --git a/classes/exercises/ClassExercises.js b/classes/exercises/ClassExercises.js index 91b9ee5b9d..24b787ec20 100644 --- a/classes/exercises/ClassExercises.js +++ b/classes/exercises/ClassExercises.js @@ -1,10 +1,69 @@ // Define your Book class here: +class Book { + constructor(title, author, copyrightDate, iSBN, pages, numCheckout, discarded) { + this.title = title; + this.author = author; + this.copyrightDate = copyrightDate; + this.iSBN = iSBN; + this.pages = pages; + this.numCheckout = numCheckout; + this.discarded = discarded; + } + + checkout(num) { + this.numCheckout += num; + } +} // Define your Manual and Novel classes here: +class Manual extends Book { + constructor(title, author, copyrightDate, iSBN, pages, numCheckout, discarded) { + super(title, author, copyrightDate, iSBN, pages, numCheckout, discarded); + } + + dispose(year) { + if (year - this.copyrightDate > 5) { + this.discarded = 'Yes'; + } + } +} + +class Novel extends Book { + constructor(title, author, copyrightDate, iSBN, pages, numCheckout, discarded) { + super(title, author, copyrightDate, iSBN, pages, numCheckout, discarded); + } + + dispose() { + if (this.numCheckout > 100) { + this.discarded = 'Yes'; + } + } +} // Declare the objects for exercises 2 and 3 here: +let novel1 = new Novel('Pride and Prejudice', 'Jane Austen', 1813, '1111111111111', 432, 32, 'No'); +let manual1 = new Manual('Top Secret Shuttle Building Manual', 'Redacted', 2013, '0000000000000', 1147, 1, 'No'); + +// Code exercises 4 & 5 here: + +console.log(`Has the novel '${novel1.title}' by ${novel1.author} been disposed?: ${novel1.discarded}`); +console.log(`Has the novel '${manual1.title}' by ${novel1.author} been disposed?: ${manual1.discarded}`); + +novel1.dispose(); +manual1.dispose(2024); + +console.log(`Has the novel '${novel1.title}' by ${novel1.author} been disposed?: ${novel1.discarded}`); +console.log(`Has the novel '${manual1.title}' by ${novel1.author} been disposed?: ${manual1.discarded}`); + +console.log(`Number of times '${novel1.title}' by ${novel1.author} has been checked out: ${novel1.numCheckout}`); + +novel1.checkout(5); + +console.log(`Number of times '${novel1.title}' by ${novel1.author} has been checked out: ${novel1.numCheckout}`); + +novel1.dispose(); -// Code exercises 4 & 5 here: \ No newline at end of file +console.log(`Has the novel '${novel1.title}' by ${novel1.author} been disposed?: ${novel1.discarded}`); \ No newline at end of file diff --git a/css/exercises/Git-Exercises.png b/css/exercises/Git-Exercises.png new file mode 100644 index 0000000000..2f43aa342e Binary files /dev/null and b/css/exercises/Git-Exercises.png differ diff --git a/css/exercises/index.html b/css/exercises/index.html index 922e8e3885..fa85869f45 100644 --- a/css/exercises/index.html +++ b/css/exercises/index.html @@ -9,13 +9,13 @@ -

My Very Cool Web Page

-

Why this Website is Very Cool

-
    +

    My Very Cool Web Page

    +

    Why this Website is Very Cool

    +
    1. I made it!
    2. This website is colorful!
    -

    Why I love Web Development

    +

    Why I love Web Development

    Web Development is a very cool skill that I love learning!

    I love making websites because all I have to do is reload the page to see the changes I have made!

    diff --git a/css/exercises/styles.css b/css/exercises/styles.css index 3b88bed453..635c6046df 100644 --- a/css/exercises/styles.css +++ b/css/exercises/styles.css @@ -1 +1,25 @@ /* Start adding your styling below! */ + +body { + background-color: yellow; +} + +p { + color: green; +} + +h1 { + font-size: 36px; +} + +.center { + text-align: center; +} + +#cool-text { + color: blue; +} + +#pink-text { + color: pink; +} \ No newline at end of file diff --git a/data-and-variables/exercises/data-and-variables-exercises.js b/data-and-variables/exercises/data-and-variables-exercises.js index 6433bcd641..696148752a 100644 --- a/data-and-variables/exercises/data-and-variables-exercises.js +++ b/data-and-variables/exercises/data-and-variables-exercises.js @@ -1,11 +1,35 @@ // Declare and assign the variables below +let spaceShuttle = "Determination"; +let shuttleSpeed = 17500; +let distanceToMars = 225000000; +let distanceToMoon = 384000; +const mpk = 0.621; + // Use console.log to print the 'typeof' each variable. Print one item per line. +console.log(typeof spaceShuttle); +console.log(typeof shuttleSpeed); +console.log(typeof distanceToMars); +console.log(typeof distanceToMoon); +console.log(typeof mpk); + // Calculate a space mission below +let milesToMars = distanceToMars * mpk; +let hoursMars = milesToMars / shuttleSpeed; +let daysMars = hoursMars / 24; + // Print the results of the space mission calculations below +console.log(spaceShuttle + " will take " + daysMars + " days to reach Mars."); + // Calculate a trip to the moon below -// Print the results of the trip to the moon below \ No newline at end of file +let milesToMoon = distanceToMoon * mpk; +let hoursMoon = milesToMoon / shuttleSpeed; +let daysMoon = hoursMoon / 24; + +// Print the results of the trip to the moon below + +console.log(spaceShuttle + " will take " + daysMoon + " days to reach the Moon."); \ No newline at end of file diff --git a/dom-and-events/exercises/script.js b/dom-and-events/exercises/script.js index de6b630519..b397c7b2a7 100644 --- a/dom-and-events/exercises/script.js +++ b/dom-and-events/exercises/script.js @@ -5,6 +5,24 @@ function init () { // Put your code for the exercises here. + button.addEventListener("click", (e) => { + paragraph.innerHTML = "Houston, we have liftoff!"; + }); + + missionAbort.addEventListener("mouseover", (e) => { + missionAbort.style.backgroundColor = "red"; + }); + + missionAbort.addEventListener("mouseleave", (e) => { + missionAbort.style.backgroundColor = ""; + }); + + missionAbort.addEventListener("click", (e) => { + let response = window.confirm("Are you sure you want to abort the mission?"); + if (response) { + paragraph.innerHTML = "Mission aborted! Space shuttle returning home"; + } + }); } window.addEventListener("load", init); diff --git a/dom-and-events/studio/scripts.js b/dom-and-events/studio/scripts.js index 45c9b3a9d1..d5325c193f 100644 --- a/dom-and-events/studio/scripts.js +++ b/dom-and-events/studio/scripts.js @@ -1,2 +1,76 @@ // Write your JavaScript code here. // Remember to pay attention to page loading! + +window.addEventListener('load', () => { + const rocket = document.getElementById('rocket'); + + const liftOffBtn = document.getElementById('takeoff'); + const landBtn = document.getElementById('landing'); + const abortBtn = document.getElementById('missionAbort'); + + const upButton = document.getElementById('up'); + const downButton = document.getElementById('down'); + const rightButton = document.getElementById('right'); + const leftButton = document.getElementById('left'); + + const flightStat = document.getElementById('flightStatus'); + const shuttleBackground = document.getElementById('shuttleBackground'); + const shuttleHeight = document.getElementById('spaceShuttleHeight'); + + liftOffBtn.addEventListener('click', function (e) { + let response = window.confirm('Confirm that the shuttle is ready for takeoff.'); + + if (response) { + flightStat.innerHTML = 'Shuttle in flight.'; + shuttleBackground.style.backgroundColor = "blue"; + shuttleHeight.innerHTML = 10000; + } + }) + + landBtn.addEventListener('click', e => { + window.alert('The shuttle is landing. Landing gear engaged.'); + + flightStat.innerHTML = 'The shuttle has landed'; + shuttleBackground.style.backgroundColor = "green"; + shuttleHeight.innerHTML = 0; + rocket.style.top = '50%'; + rocket.style.left = '50%'; + }) + + abortBtn.addEventListener('click', e => { + let response = window.confirm('Confirm that you want to abort the mission.'); + + if (response) { + flightStat.innerHTML = 'Mission aborted.'; + shuttleBackground.style.backgroundColor = "green"; + shuttleHeight.innerHTML = 0; + rocket.style.top = '50%'; + rocket.style.left = '50%'; + } + }) + + upButton.addEventListener('click', function () { + moveRocket(0, -10); + shuttleHeight.innerText = parseInt(shuttleHeight.innerText) + 10000; + }); + downButton.addEventListener('click', function () { + moveRocket(0, 10); + shuttleHeight.innerText = parseInt(shuttleHeight.innerText) - 10000; + if (shuttleHeight <= 0) { + shuttleHeight.innerHTML = 0; + } + }); + leftButton.addEventListener('click', function () { + moveRocket(-10, 0); + }); + rightButton.addEventListener('click', function () { + moveRocket(10, 0); + }); + function moveRocket(dx, dy) { + let left = parseInt(rocket.style.left.replace('px', '')) + dx; + let top = parseInt(rocket.style.top.replace('px', '')) + dy; + rocket.style.paddingLeft = `${left}px`; + rocket.style.paddingTop = `${top}px`; + } + +}) \ No newline at end of file diff --git a/dom-and-events/studio/styles.css b/dom-and-events/studio/styles.css index cc932dd89d..23f1a07c0d 100644 --- a/dom-and-events/studio/styles.css +++ b/dom-and-events/studio/styles.css @@ -27,4 +27,11 @@ .centered { text-align: center; +} + +#rocket { + position: absolute; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); } \ No newline at end of file diff --git a/errors-and-debugging/exercises/Debugging1stSyntaxError.js b/errors-and-debugging/exercises/Debugging1stSyntaxError.js index 365af5a964..f35a8c49d2 100644 --- a/errors-and-debugging/exercises/Debugging1stSyntaxError.js +++ b/errors-and-debugging/exercises/Debugging1stSyntaxError.js @@ -4,7 +4,7 @@ let launchReady = false; let fuelLevel = 17000; -if (fuelLevel >= 20000 { +if (fuelLevel >= 20000) { console.log('Fuel level cleared.'); launchReady = true; } else { diff --git a/errors-and-debugging/exercises/DebuggingLogicErrors1.js b/errors-and-debugging/exercises/DebuggingLogicErrors1.js index 1ad473f08d..9b40824f8f 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors1.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors1.js @@ -3,6 +3,8 @@ // Did it? // Do not worry about fixing the code yet, we will do that in the next series of exercises. +// The shuttle should NOT have launched, but it did launch. + let launchReady = false; let fuelLevel = 17000; let crewStatus = true; diff --git a/errors-and-debugging/exercises/DebuggingLogicErrors2.js b/errors-and-debugging/exercises/DebuggingLogicErrors2.js index 160a0c2cd0..0390f01452 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors2.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors2.js @@ -4,6 +4,8 @@ //Given the fuelLevel value, should launchReady be true or false after the check? Is the program behaving as expected? +// launchReady should be false after the check. Program is running as expected. + let launchReady = false; let fuelLevel = 17000; // let crewStatus = true; @@ -17,6 +19,8 @@ if (fuelLevel >= 20000) { launchReady = false; } +console.log(launchReady); + // if (crewStatus && computerStatus === 'green'){ // console.log('Crew & computer cleared.'); // launchReady = true; diff --git a/errors-and-debugging/exercises/DebuggingLogicErrors3.js b/errors-and-debugging/exercises/DebuggingLogicErrors3.js index 023f2ab07d..fa7338d897 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors3.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors3.js @@ -5,6 +5,9 @@ // Given the values for crewStatus and computerStatus, should launchReady be true or false after the check? // Is the program behaving as expected? +// Given the values for crewStatus and computerStatus, launchReady will be true. +// Without fuelLevel in mind, the program is behaving as expected. + let launchReady = false; // let fuelLevel = 17000; let crewStatus = true; @@ -26,6 +29,8 @@ if (crewStatus && computerStatus === 'green'){ launchReady = false; } +console.log(launchReady); + // if (launchReady) { // console.log('10, 9, 8, 7, 6, 5, 4, 3, 2, 1...'); // console.log('Liftoff!'); diff --git a/errors-and-debugging/exercises/DebuggingLogicErrors4.js b/errors-and-debugging/exercises/DebuggingLogicErrors4.js index dc9ac0af9d..6e8de640e0 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors4.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors4.js @@ -4,6 +4,9 @@ // Given the values for fuelLevel, crewStatus and computerStatus, should launchReady be true or false? // Is the program behaving as expected? +// After checking fuelLevel, crewStatus, and computerStatus, the variable launchReady will be true. +// Program will run as told. If we want both if-statements to be be true, then program will not run as expected. + let launchReady = false; let fuelLevel = 17000; let crewStatus = true; diff --git a/errors-and-debugging/exercises/DebuggingLogicErrors5.js b/errors-and-debugging/exercises/DebuggingLogicErrors5.js index 7eb908e769..88260b3ba5 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors5.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors5.js @@ -3,6 +3,7 @@ // Refactor the code to do this. Verify that your change works by updating the console.log statements. let launchReady = false; +let launchReady2 = false; let fuelLevel = 17000; let crewStatus = true; let computerStatus = 'green'; @@ -19,10 +20,17 @@ console.log("launchReady = ", launchReady); if (crewStatus && computerStatus === 'green'){ console.log('Crew & computer cleared.'); - launchReady = true; + launchReady2 = true; } else { console.log('WARNING: Crew or computer not ready!'); - launchReady = false; + launchReady2 = false; } -console.log("launchReady = ", launchReady); \ No newline at end of file +console.log("launchReady2 = ", launchReady2); + +if (launchReady && launchReady2) { + console.log('10, 9, 8, 7, 6, 5, 4, 3, 2, 1...'); + console.log('Liftoff!'); +} else { + console.log('Launch scrubbed.'); +} \ No newline at end of file diff --git a/errors-and-debugging/exercises/DebuggingRuntimeErrors1.js b/errors-and-debugging/exercises/DebuggingRuntimeErrors1.js index e66e494a30..7bbf7ebb82 100644 --- a/errors-and-debugging/exercises/DebuggingRuntimeErrors1.js +++ b/errors-and-debugging/exercises/DebuggingRuntimeErrors1.js @@ -4,7 +4,7 @@ let launchReady = false; let fuelLevel = 17000; -if (fuellevel >= 20000) { +if (fuelLevel >= 20000) { console.log('Fuel level cleared.'); launchReady = true; } else { diff --git a/errors-and-debugging/exercises/DebuggingRuntimeErrors2.js b/errors-and-debugging/exercises/DebuggingRuntimeErrors2.js index a656080d25..703a0d61c4 100644 --- a/errors-and-debugging/exercises/DebuggingRuntimeErrors2.js +++ b/errors-and-debugging/exercises/DebuggingRuntimeErrors2.js @@ -14,7 +14,7 @@ if (launchReady) { console.log("Fed parrot..."); console.log("6, 5, 4..."); console.log("Ignition..."); - consoul.log("3, 2, 1..."); + console.log("3, 2, 1..."); console.log("Liftoff!"); } else { console.log("Launch scrubbed."); diff --git a/errors-and-debugging/exercises/DebuggingSyntaxErrors2.js b/errors-and-debugging/exercises/DebuggingSyntaxErrors2.js index b600339254..daf36e5da5 100644 --- a/errors-and-debugging/exercises/DebuggingSyntaxErrors2.js +++ b/errors-and-debugging/exercises/DebuggingSyntaxErrors2.js @@ -8,7 +8,7 @@ let launchReady = false; let crewStatus = true; let computerStatus = 'green'; -if (crewStatus &&& computerStatus === 'green'){ +if (crewStatus && computerStatus === 'green'){ console.log('Crew & computer cleared.'); launchReady = true; } else { @@ -17,7 +17,7 @@ if (crewStatus &&& computerStatus === 'green'){ } if (launchReady) { - console.log(("10, 9, 8, 7, 6, 5, 4, 3, 2, 1..."); + console.log("10, 9, 8, 7, 6, 5, 4, 3, 2, 1..."); console.log("Fed parrot..."); console.log("Ignition..."); console.log("Liftoff!"); diff --git a/exceptions/exercises/divide.js b/exceptions/exercises/divide.js index 06fc889862..c47172ba0f 100644 --- a/exceptions/exercises/divide.js +++ b/exceptions/exercises/divide.js @@ -5,3 +5,13 @@ // However, if the denominator is zero you should throw the error, "Attempted to divide by zero." // Code your divide function here: + +let divide = (numerator, denominator) => { + if (denominator === 0) { + throw Error("Attempted to divide by zerio."); + } + + return numerator / denominator; +} + +console.log(divide(5,0)); \ No newline at end of file diff --git a/exceptions/exercises/test-student-labs.js b/exceptions/exercises/test-student-labs.js index cfe5bfe175..f8f6ffbac3 100644 --- a/exceptions/exercises/test-student-labs.js +++ b/exceptions/exercises/test-student-labs.js @@ -1,7 +1,12 @@ function gradeLabs(labs) { - for (let i=0; i < labs.length; i++) { + for (let i = 0; i < labs.length; i++) { let lab = labs[i]; - let result = lab.runLab(3); + let result; + try { + result = lab.runLab(3); + } catch (err) { + result = "Error thrown"; + } console.log(`${lab.student} code worked: ${result === 27}`); } } @@ -10,15 +15,38 @@ let studentLabs = [ { student: 'Carly', runLab: function (num) { - return Math.pow(num, num); + return Math.pow(num, num); } }, { student: 'Erica', runLab: function (num) { - return num * num; + return num * num; } } ]; gradeLabs(studentLabs); + +let studentLabs2 = [ + { + student: 'Blake', + myCode: function (num) { + return Math.pow(num, num); + } + }, + { + student: 'Jessica', + runLab: function (num) { + return Math.pow(num, num); + } + }, + { + student: 'Mya', + runLab: function (num) { + return num * num; + } + } +]; + +gradeLabs(studentLabs2); \ No newline at end of file diff --git a/fetch/exercises/fetch_planets.html b/fetch/exercises/fetch_planets.html new file mode 100644 index 0000000000..3e1e3d67da --- /dev/null +++ b/fetch/exercises/fetch_planets.html @@ -0,0 +1,43 @@ + + + + + Fetch Planets + + + + +

    Destination

    +
    +

    Planet

    +
    + + + \ No newline at end of file diff --git a/fetch/exercises/json_exercises.js b/fetch/exercises/json_exercises.js new file mode 100644 index 0000000000..2a9faceaba --- /dev/null +++ b/fetch/exercises/json_exercises.js @@ -0,0 +1,80 @@ +//! Which of the following three code snippets is correct JSON syntax? Why are the other two options incorrect? + +// a. + +{ + type: "dog", + name: "Bernie", + age: 3 +} + +// b. + +{ + "type": "dog", + "name": "Bernie", + "age": 3 +} + +// c. + +{ + "type": 'dog', + "name": 'Bernie', + "age": 3 +} + +// ANSWER: b is the correct answer because the key and value pairs are both in double quotation marks for string. Keys must have double quotation marks, so a cannot be the answer. Values must have double quation marks, so c cannot be the answer. + +//! Which of the following three code snippets is correct JSON? Why are the other two options incorrect? + +// a. + +{ + "animals": [ + { + "type": "dog", + "name": "Bernie", + "age": 3 + }, + { + "type": "cat", + "name": "Draco", + "age": 2 + } + ] +} + +// b. + +{ + [ + { + "type": "dog", + "name": "Bernie", + "age": 3 + }, + { + "type": "cat", + "name": "Draco", + "age": 2 + } + ] +} + +// c. + +[ + { + "type": "dog", + "name": "Bernie", + "age": 3 + }, + { + "type": "cat", + "name": "Draco", + "age": 2 + } +] + +// The answer is a because it has everything required. A key of animals (in double quotes) with a value of an array. Inside the array, everything matches, both key and values (of strings) are in double quotes. The answer cannot be b because there is no key for the array. And the answer cannot be c because it also needs a key. \ No newline at end of file diff --git a/fetch/studio/script.js b/fetch/studio/script.js index 591ec836a7..7597c4078f 100644 --- a/fetch/studio/script.js +++ b/fetch/studio/script.js @@ -1 +1,43 @@ //TODO: Add Your Code Below + +window.addEventListener("load", () => { + + let fetchData = async () => { + let response = await fetch("http://github.com/service/https://handlers.education.launchcode.org/static/astronauts.json"); + let data = await response.json(); + + let sortData = data.sort((a, b) => b.hoursInSpace - a.hoursInSpace); + + const container = document.getElementById("container"); + + for (let i = 0; i < sortData.length; i++) { + let skills = sortData[i].skills.join(", "); + let active = sortData[i].active; + let activeColor = ""; + + if (active) { + activeColor = "color: green"; + } + + container.innerHTML += ` +
    +
    +

    ${i+1}. ${sortData[i].firstName} ${sortData[i].lastName}

    +
      +
    • Hours in space: ${sortData[i].hoursInSpace}
    • +
    • Active: ${sortData[i].active}
    • +
    • Skills: ${skills}
    • +
    +
    + +
    + `; + } + + container.innerHTML += `Total number of astronauts: ${sortData.length}`; + + } + + fetchData(); + +}) \ No newline at end of file diff --git a/functions/functions-exercise.js b/functions/functions-exercise.js new file mode 100644 index 0000000000..659b6451aa --- /dev/null +++ b/functions/functions-exercise.js @@ -0,0 +1,238 @@ +//! Rectangles + +// makeLine(size) function + +function makeLine(size) { + let line = ''; + for (let i = 0; i < size; i++) { + line += '#'; + } + + return line; +} + +console.log(makeLine(5)); +console.log(''); + +// makeSquare(size) function + +function makeSquare(size) { + let row = makeLine(size); + let square = ''; + + for (let i = 0; i < size; i++) { + square += row; + + if (i !== size - 1) { + square += '\n'; + } + } + + return square; +} + +console.log(makeSquare(5)); +console.log(''); + +// makeRectangle(width, height) function + +function makeRectangle(width, height) { + let row = makeLine(width); + let n = height; + let rectangle = ''; + + for (let i = 0; i < n; i++) { + rectangle += row; + + if (i !== n - 1) { + rectangle += '\n'; + } + } + + return rectangle; +} + +console.log(makeRectangle(5, 3)); +console.log(''); + +// Now, go back and rewrite makeSquare to use makeRectangle. + +function makeSquare2(size) { + return makeRectangle(size, size); +} + +console.log(makeSquare2(5)); +console.log(''); + +//! Triangles + +// makeDownwardStairs(height) function + +function makeDownwardStairs(height) { + let stairs = ''; + + for (let i = 1; i <= height; i++) { + stairs += makeLine(i); + + if (i !== height) { + stairs += '\n'; + } + } + + return stairs; +} + +console.log(makeDownwardStairs(5)); +console.log(''); + +// makeSpaceLine(numSpaces, numChars) function + +function makeSpaceLine(numSpaces, numChars) { + let spaces = ''; + let lines = makeLine(numChars); + + for (let i = 0; i < numSpaces; i++) { + spaces += ' '; + } + + return spaces + lines + spaces; +} + +console.log(makeSpaceLine(3, 5)); +console.log(''); + +// makeIsoscelesTriangle(height) function + +function makeIsoscelesTriangle(height) { + let triangle = ''; + + for (let i = 0; i < height; i++) { + triangle += makeSpaceLine(height - i - 1, 2 * i + 1) + '\n'; + } + + return triangle.slice(0, -1); +} + +console.log(makeIsoscelesTriangle(5)); +console.log(''); + +//! Diamond + +// makeDiamond(height) function + +function makeDiamond(height) { + return makeIsoscelesTriangle(height) + '\n' + makeIsoscelesTriangle(height).split('').reverse().join(''); +} + +console.log(makeDiamond(5)); +console.log(''); + +//! Bonus Mission + +// Refactor your functions so that they take a single character as a parameter, and draw the shapes with that character instead of always using '#'. Make the new parameter optional, with default value '#'. + +function makeLineRefactor(size, char = '#') { + let line = ''; + for (let i = 0; i < size; i++) { + line += char; + } + + return line; +} + +console.log(makeLineRefactor(5, '*')); +console.log(''); + +function makeSquareRefactor(size, char = '#') { + let row = makeLineRefactor(size, char); + let square = ''; + + for (let i = 0; i < size; i++) { + square += row; + + if (i !== size - 1) { + square += '\n'; + } + } + + return square; +} + +console.log(makeSquareRefactor(5, "@")); +console.log(''); + +function makeRectangleRefactor(width, height, char = '#') { + let row = makeLineRefactor(width, char); + let n = height; + let rectangle = ''; + + for (let i = 0; i < n; i++) { + rectangle += row; + + if (i !== n - 1) { + rectangle += '\n'; + } + } + + return rectangle; +} + +console.log(makeRectangleRefactor(5, 3, '$')); +console.log(''); + +function makeSquareRefactor2(size, char = '#') { + return makeRectangleRefactor(size, size, char); +} + +console.log(makeSquareRefactor2(5, '%')); +console.log(''); + +function makeDownwardStairsRefactor(height, char = '#') { + let stairs = ''; + + for (let i = 1; i <= height; i++) { + stairs += makeLineRefactor(i, char); + + if (i !== height) { + stairs += '\n'; + } + } + + return stairs; +} + +console.log(makeDownwardStairsRefactor(5, '&')); +console.log(''); + +function makeSpaceLineRefactor(numSpaces, numChars, char = '#') { + let spaces = ''; + let lines = makeLineRefactor(numChars, char); + + for (let i = 0; i < numSpaces; i++) { + spaces += ' '; + } + + return spaces + lines + spaces; +} + +console.log(makeSpaceLineRefactor(3, 5, '+')); +console.log(''); + +function makeIsoscelesTriangleRefactor(height, char = '#') { + let triangle = ''; + + for (let i = 0; i < height; i++) { + triangle += makeSpaceLineRefactor(height - i - 1, 2 * i + 1, char) + '\n'; + } + + return triangle.slice(0, -1); +} + +console.log(makeIsoscelesTriangleRefactor(5, '-')); +console.log(''); + +function makeDiamondRefactor(height, char = '#') { + return makeIsoscelesTriangleRefactor(height, char) + '\n' + makeIsoscelesTriangleRefactor(height, char).split('').reverse().join(''); +} + +console.log(makeDiamondRefactor(5, '3')); \ No newline at end of file diff --git a/functions/studio/studio-functions.js b/functions/studio/studio-functions.js index 175fc7f439..91e54f1537 100644 --- a/functions/studio/studio-functions.js +++ b/functions/studio/studio-functions.js @@ -9,6 +9,20 @@ // 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) { + if (typeof str === 'string') { + return str.split("").reverse().join(""); + } + + if (typeof str === 'number') { + return Number(String(str).split("").reverse().join("")); + } +} + +let myStr = 'radar'; + +console.log(reverseCharacters(myStr)); + // Part Two: Reverse Digits // 1. Add an if statement to reverseCharacters to check the typeof the parameter. @@ -30,6 +44,20 @@ let arrayTest1 = ['apple', 'potato', 'Capitalized Words']; let arrayTest2 = [123, 8897, 42, 1168, 8675309]; let arrayTest3 = ['hello', 'world', 123, 'orange']; +function completeReversal(arr) { + let reverseArr = []; + + for (let i = 0; i < arr.length; i++) { + reverseArr.push(reverseCharacters(arr[i])); + } + + return reverseArr.reverse(); +} + +console.log(completeReversal(arrayTest1)); +console.log(completeReversal(arrayTest2)); +console.log(completeReversal(arrayTest3)); + // Bonus Missions // 1. Have a clear, descriptive name like funPhrase. @@ -37,6 +65,25 @@ let arrayTest3 = ['hello', 'world', 123, 'orange']; // 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(str) { + let phrase = ''; + let arr = str.split(" "); + + for (let i = 0; i < arr.length; i++) { + if (arr[i].length <= 3) { + phrase += arr[i].slice(-1); + } else { + phrase += arr[i].slice(0, 3); + } + } + + return phrase; +} + +let funStr = 'Math is fun'; + +console.log(`We put the '${funPhrase(funStr)}' in '${funStr}'.`); + // Test Function // 1. Outside of the function, define the variable str and initialize it with a string (e.g. 'Functions rock!'). @@ -49,3 +96,11 @@ 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.” + +function areaOfRectangle(length, width = length) { + let area = length * width; + + return area; +} + +console.log(`The area is ${areaOfRectangle(20)} cm^2.`); \ No newline at end of file diff --git a/html/exercises/index.html b/html/exercises/index.html index 80f716a800..a0b3b85ec0 100644 --- a/html/exercises/index.html +++ b/html/exercises/index.html @@ -9,8 +9,19 @@ +

    Why I Love Web Development

    +

    It is:

    +
      +
    1. FUN
    2. +
    3. CHALLENGING
    4. +
    5. REWARDING
    6. +
    + Page to EXERCISES: HTML +

    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eaque, ut minima. Assumenda excepturi repudiandae voluptates libero sed fugiat quam odit earum blanditiis? Sint sapiente nihil officiis illo dolorum quibusdam dicta! Lorem ipsum dolor sit, amet consectetur adipisicing elit. Deserunt officia sint incidunt eum quis atque voluptates sit consequatur nihil, perspiciatis tempore autem dicta officiis voluptatum, laboriosam delectus dolorem aperiam accusantium. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nemo eum quibusdam nisi esse, soluta explicabo eveniet ad molestias modi nulla natus dolores sapiente expedita! Enim maiores et sed ipsum temporibus! Lorem, ipsum dolor sit amet consectetur adipisicing elit. Neque voluptatum reiciendis quidem similique nulla facilis dolorum consectetur? Repudiandae, temporibus? Qui, placeat? Vitae repellendus earum saepe velit, expedita nemo enim. Enim. Lorem ipsum dolor sit amet consectetur adipisicing elit. Rem facilis, maiores, sint amet ut odio aliquam fugiat nam debitis accusamus beatae. Alias unde quidem totam quaerat, quas ab laudantium magni?

    +

    Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime, impedit quas molestiae quo repudiandae dolorem dignissimos, quisquam adipisci maiores fuga distinctio incidunt ex, tenetur earum asperiores quae provident quidem veniam? Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ex tempora sed temporibus qui illum mollitia amet ducimus aliquam, minus voluptas ipsam dicta delectus. Similique sed, veritatis nulla natus consequuntur ullam? Lorem ipsum dolor sit amet consectetur adipisicing elit. Incidunt officiis, repellendus vitae soluta dolor voluptatibus earum exercitationem perferendis architecto odit eos consequuntur maiores ipsum! Aliquid incidunt reiciendis quaerat consectetur impedit? Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, voluptatem dignissimos inventore pariatur sapiente nisi consequatur facere soluta, incidunt nam asperiores? Libero illo impedit aut obcaecati, odit excepturi tempora! Dolorem? Lorem ipsum dolor sit amet consectetur adipisicing elit. Sit eius eveniet tempora blanditiis quibusdam nihil aperiam fugiat minima. Ipsam quis quisquam natus accusantium assumenda voluptatum itaque, deleniti dolores nemo molestias?

    +

    Lorem ipsum dolor sit, amet consectetur adipisicing elit. At ad quod aut obcaecati nam laborum repellendus aperiam repudiandae excepturi rem voluptate nobis perferendis, atque illum nisi deleniti esse dolores autem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eos autem placeat aperiam dicta temporibus, sunt expedita, vel deserunt libero vitae ipsa quasi vero deleniti voluptatum perspiciatis consectetur molestias veritatis! Corrupti? Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, sunt perferendis sint doloribus eius sequi similique. Adipisci distinctio atque dolorem officiis voluptatibus, repellat sit maiores consequuntur molestias corporis at numquam? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, exercitationem explicabo saepe temporibus aspernatur cumque est corporis eligendi obcaecati tempora et assumenda repellat natus? Autem voluptas repudiandae explicabo doloremque qui. Lorem ipsum dolor sit amet consectetur adipisicing elit. Quae fugit voluptatibus ratione error nostrum libero atque illum natus mollitia asperiores. Necessitatibus corrupti error nihil veniam aliquid, alias pariatur quod facere!

    \ No newline at end of file diff --git a/loops/exercises/for-Loop-Exercises.js b/loops/exercises/for-Loop-Exercises.js index c659c50852..17b737606b 100644 --- a/loops/exercises/for-Loop-Exercises.js +++ b/loops/exercises/for-Loop-Exercises.js @@ -4,8 +4,27 @@ c. Print the EVEN numbers 12 to -14 in descending order, one number per line. d. Challenge - Print the numbers 50 - 20 in descending order, but only if the numbers are multiples of 3. (Your code should work even if you replace 50 or 20 with other numbers). */ +// a +for (let i = 0; i < 21; i++) { + console.log(i); +} +// b +for (let i = 3; i < 30; i+=2) { + console.log(i); +} +// c +for (let i = 12; i > -15; i-=2) { + console.log(i); +} + +// d +for (let i = 50; i >= 20; i--) { + if (i % 3 === 0) { + console.log(i); + } +} /*Exercise #2: Initialize two variables to hold the string “LaunchCode” and the array [1, 5, ‘LC101’, ‘blue’, 42]. @@ -15,10 +34,35 @@ Construct ``for`` loops to accomplish the following tasks: a. Print each element of the array to a new line. b. Print each character of the string - in reverse order - to a new line. */ +let str = "LaunchCode"; +let arr = [1, 5, 'LC101', 'blue', 42]; +// a. +for (let i = 0; i < arr.length; i++) { + console.log(arr[i]); +} - +for (let i = str.length - 1; i >= 0; i--) { + console.log(str[i]); +} /*Exercise #3:Construct a for loop that sorts the array [2, 3, 13, 18, -5, 38, -10, 11, 0, 104] into two new arrays: a. One array contains the even numbers, and the other holds the odds. - b. Print the arrays to confirm the results. */ \ No newline at end of file + b. Print the arrays to confirm the results. */ + +// a. +let numArr = [2, 3, 13, 18, -5, 38, -10, 11, 0, 104]; +let evenArr = []; +let oddArr = []; + +for (let i = 0; i < numArr.length; i++) { + if (numArr[i] % 2 === 0) { + evenArr.push(numArr[i]); + } else { + oddArr.push(numArr[i]); + } +} + +// b. +console.log(evenArr); +console.log(oddArr); \ No newline at end of file diff --git a/loops/exercises/while-Loop-Exercises.js b/loops/exercises/while-Loop-Exercises.js index 53a8ce1250..2fc9bd9003 100644 --- a/loops/exercises/while-Loop-Exercises.js +++ b/loops/exercises/while-Loop-Exercises.js @@ -1,25 +1,42 @@ -//Define three variables for the LaunchCode shuttle - one for the starting fuel level, another for the number of astronauts aboard, and the third for the altitude the shuttle reaches. +const input = require('readline-sync'); +//Define three variables for the LaunchCode shuttle - one for the starting fuel level, another for the number of astronauts aboard, and the third for the altitude the shuttle reaches. +let startingFuelLevel = 0, numberOfAstronauts = 0, shuttleAltitude = 0; /*Exercise #4: Construct while loops to do the following: a. Query the user for the starting fuel level. Validate that the user enters a positive, integer value greater than 5000 but less than 30000. */ - +while (startingFuelLevel <= 5000 || startingFuelLevel >= 30000 || isNaN(startingFuelLevel)) { + startingFuelLevel = input.question("Enter the starting fuel level: "); +} //b. Use a second loop to query the user for the number of astronauts (up to a maximum of 7). Validate the entry. - +while (numberOfAstronauts > 7 || numberOfAstronauts <= 0 || isNaN(numberOfAstronauts)) { + numberOfAstronauts = input.question("Enter the number of astronauts: "); +} //c. Use a final loop to monitor the fuel status and the altitude of the shuttle. Each iteration, decrease the fuel level by 100 units for each astronaut aboard. Also, increase the altitude by 50 kilometers. - +while (startingFuelLevel > numberOfAstronauts * 100) { + startingFuelLevel -= numberOfAstronauts * 100; + shuttleAltitude += 50; +} /*Exercise #5: Output the result with the phrase, “The shuttle gained an altitude of ___ km.” If the altitude is 2000 km or higher, add “Orbit achieved!” Otherwise add, “Failed to reach orbit.”*/ + +console.log(`The shuttle gained an altitude of ${shuttleAltitude} km.`); + +if (shuttleAltitude >= 2000) { + console.log("Orbit achieved!"); +} else { + console.log("Failed to reach orbit."); +} \ No newline at end of file diff --git a/loops/studio/package.json b/loops/studio/package.json deleted file mode 100644 index 7fa1050817..0000000000 --- a/loops/studio/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "loops", - "version": "1.0.0", - "description": "", - "main": "solution.js", - "scripts": { - "test": "jest" - }, - "author": "", - "license": "ISC", - "dependencies": { - "readline-sync": "^1.4.10" - }, - "devDependencies": { - "jest": "^29.7.0" - } -} diff --git a/loops/studio/solution.js b/loops/studio/solution.js index 4e21a9caa5..2b7ba5e845 100644 --- a/loops/studio/solution.js +++ b/loops/studio/solution.js @@ -2,11 +2,11 @@ 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) { @@ -15,16 +15,26 @@ function mealAssembly(protein, grains, veggies, beverages, desserts, numMeals) { /// 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 plate = []; + for (let j = 0; j < pantry.length; j++) { + plate.push(pantry[j][i]); + } + meals.push(plate); + } return meals; } function askForNumber() { - numMeals = input.question("How many meals would you like to make?"); + numMeals = input.question("How many meals would you like to make? (1-6) "); /// CODE YOUR SOLUTION TO PART B here /// + while (numMeals < 1 || numMeals > 6 || isNaN(numMeals)) { + numMeals = input.question("How many meals would you like to make? (1-6) "); + } return numMeals; } @@ -35,6 +45,18 @@ function generatePassword(string1, string2) { /// Code your Bonus Mission Solution here /// + let min = 0; + + if (string1.length > string2.length) { + min = string2.length; + } else { + min = string1.length; + } + + for (let i = 0; i < min; i++) { + code = code + string1[i] + string2[i]; + } + return code; } @@ -45,24 +67,24 @@ function runProgram() { /// 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) + 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 /// - // let mealsForX = mealAssembly(protein, grains, veggies, beverages, desserts, askForNumber()); - // console.log(mealsForX); + let mealsForX = mealAssembly(protein, grains, veggies, beverages, desserts, askForNumber()); + console.log(mealsForX); /// 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 = ''; - // let password2 = ''; - // console.log("Time to run the password generator so we can update the menu tomorrow.") - // console.log(`The new password is: ${generatePassword(password1, password2)}`); + let password1 = '1234'; + let password2 = '5678'; + console.log("Time to run the password generator so we can update the menu tomorrow.") + console.log(`The new password is: ${generatePassword(password1, password2)}`); } module.exports = { diff --git a/modules/exercises/ScoreCalcs/averages.js b/modules/exercises/ScoreCalcs/averages.js index a109b6cfb7..17eb532253 100644 --- a/modules/exercises/ScoreCalcs/averages.js +++ b/modules/exercises/ScoreCalcs/averages.js @@ -17,3 +17,7 @@ function averageForTest(testIndex,scores){ } //TODO: Export all functions within an object. +module.exports = { + averageForStudent: averageForStudent, + averageForTest: averageForTest +} \ No newline at end of file diff --git a/modules/exercises/display.js b/modules/exercises/display.js index 6bd5f81248..aa8d7e4109 100644 --- a/modules/exercises/display.js +++ b/modules/exercises/display.js @@ -34,3 +34,5 @@ function printTestScores(index,test,students,scores){ } return; } + +module.exports = printAll; \ No newline at end of file diff --git a/modules/exercises/index.js b/modules/exercises/index.js index 5f0209a528..35a110dbd1 100644 --- a/modules/exercises/index.js +++ b/modules/exercises/index.js @@ -1,8 +1,8 @@ //Import modules: -const input = //Import readline-sync. -const averages = //Import functions from averages.js. -const printAll = //Import function from display.js. -const randomSelect = //Import function from randomSelect.js. +const input = require('readline-sync'); //Import readline-sync. +const averages = require('./ScoreCalcs/averages.js'); //Import functions from averages.js. +const printAll = require('./display.js'); //Import function from display.js. +const randomSelect = require('./randomSelect.js'); //Import function from randomSelect.js. //Candidate data: let astronauts = ['Fox','Turtle','Cat','Hippo','Dog']; @@ -19,18 +19,19 @@ for (let i = 0; i { + if (typeof input === 'number') { + return input * 3; + } else if (typeof input === 'string') { + return 'ARRR!'; + } else { + return input; + } +} + +console.log(anonymousFunction(true)); + /* Add to your code! Use your fuction and the map method to change an array as follows: a) Triple any the numbers. b) Replace any strings with “ARRR!” @@ -13,3 +25,9 @@ c) Print the new array to confirm your work. */ let arr = ['Elocution', 21, 'Clean teeth', 100]; + +let newArr = arr.map(e => { + return anonymousFunction(e); +}); + +console.log(newArr); \ No newline at end of file diff --git a/more-on-functions/exercises/raid-a-shuttle.js b/more-on-functions/exercises/raid-a-shuttle.js index db663e4177..61031e7e9f 100644 --- a/more-on-functions/exercises/raid-a-shuttle.js +++ b/more-on-functions/exercises/raid-a-shuttle.js @@ -35,6 +35,20 @@ console.log("Hold status: " + holdStatus(cargoHold)); //d). Decide where to best place your function call to gather our new fuel. +let normalFunction = (a) => { + if (checkFuel(a) === 'green') { + return a - 100001; + } else if (checkFuel(a) === 'yellow') { + return a - 50001; + } else { + return a; + } +} + +let normalTank = normalFunction(fuelLevel); + +console.log(normalTank); + /* Next, liberate some of that glorious cargo. */ @@ -46,6 +60,24 @@ console.log("Hold status: " + holdStatus(cargoHold)); //d). Don’t get hasty, matey! Remember to test your function. +let normalBox = (arr) => { + let myArr = []; + + for (let i = 0; i < arr.length; i++) { + if (arr[i].includes("gold") || arr[i].includes("AE-35 unit")) { + myArr.push(arr[i]); + arr[i] = 'dirt'; + } + } + + return myArr; +} + +// let meLoot = normalBox(cargoHold); + +// console.log(meLoot); +// console.log(cargoHold); + /* Finally, you need to print a receipt for the accountant. Don’t laugh! That genius knows MATH and saves us more gold than you can imagine. */ @@ -53,4 +85,11 @@ console.log("Hold status: " + holdStatus(cargoHold)); //b). Call your anonymous fuel and cargo functions from within irs. -//c). Use a template literal to return, "Raided _____ kg of fuel from the tanks, and stole ____ and ____ from the cargo hold." \ No newline at end of file +//c). Use a template literal to return, "Raided _____ kg of fuel from the tanks, and stole ____ and ____ from the cargo hold." + +let irs = (fuel, cargo) => { + let arr = normalBox(cargo); + return `Raided ${normalFunction(fuel)} kg of fuel from the tanks, and stole ${arr[0]} and ${arr[1]} from the cargo hold.`; +} + +console.log(irs(fuelLevel, cargoHold)); \ No newline at end of file diff --git a/more-on-functions/studio/part-one-find-minimum-value.js b/more-on-functions/studio/part-one-find-minimum-value.js index 4fa8c129d0..ee0e0e05c7 100644 --- a/more-on-functions/studio/part-one-find-minimum-value.js +++ b/more-on-functions/studio/part-one-find-minimum-value.js @@ -5,6 +5,20 @@ let nums1 = [5, 10, 2, 42]; let nums2 = [-2, 0, -10, -44, 5, 3, 0, 3]; let nums3 = [200, 5, 4, 10, 8, 5, -3.3, 4.4, 0]; +let minNum = (arr) => { + let min = arr[0]; + + for (let i = 0; i < arr.length; i++) { + if (min > arr[i]) { + min = arr[i]; + } + } + + return min; +} + //Using one of the test arrays as the argument, call your function inside the console.log statement below. -console.log(/* your code here */); +console.log(minNum(nums1)); +console.log(minNum(nums2)); +console.log(minNum(nums3)); diff --git a/more-on-functions/studio/part-three-number-sorting-easy-way.js b/more-on-functions/studio/part-three-number-sorting-easy-way.js index bfa9748a32..e1e1665445 100644 --- a/more-on-functions/studio/part-three-number-sorting-easy-way.js +++ b/more-on-functions/studio/part-three-number-sorting-easy-way.js @@ -5,4 +5,15 @@ let nums3 = [200, 5, 4, 10, 8, 5, -3.3, 4.4, 0]; //Sort each array in ascending order. +console.log(nums1.sort((a, b) => a - b)); +console.log(nums2.sort((a, b) => a - b)); +console.log(nums3.sort((a, b) => a - b)); + //Sort each array in descending order. + +console.log(nums1.sort((a, b) => b - a)); +console.log(nums2.sort((a, b) => b - a)); +console.log(nums3.sort((a, b) => b - a)); + +// Yes. The sort method will alter the original array. +// Yes. The sorting function from part 2/B altered the original array. \ No newline at end of file diff --git a/more-on-functions/studio/part-two-create-sorted-array.js b/more-on-functions/studio/part-two-create-sorted-array.js index bc362a3101..ad5bf09f7e 100644 --- a/more-on-functions/studio/part-two-create-sorted-array.js +++ b/more-on-functions/studio/part-two-create-sorted-array.js @@ -20,10 +20,50 @@ function findMinValue(arr){ //Your function here... +let sortNums = (arr) => { + let sortedArr = []; + let i = 0; + let n = arr.length; + + while (i < n) { + let min = findMinValue(arr); + sortedArr.push(min); + arr.splice(arr.indexOf(min), 1); + i++; + } + + return sortedArr; +} + /* BONUS MISSION: Refactor your sorting function to use recursion below: */ +let sortNumsRecursion = (arr) => { + let myArr = []; + + if (arr.length === 0) { + return myArr; + } else { + let min = findMinValue(arr); + myArr.push(min); + arr.splice(arr.indexOf(min), 1); + return myArr.concat(sortNumsRecursion(arr)); + } +} + //Sample arrays for testing: let nums1 = [5, 10, 2, 42]; let nums2 = [-2, 0, -10, -44, 5, 3, 0, 3]; let nums3 = [200, 5, 4, 10, 8, 5, -3.3, 4.4, 0]; + +console.log(sortNums(nums1)); +console.log(sortNums(nums2)); +console.log(sortNums(nums3)); + +let nums1recursion = [5, 10, 2, 42]; +let nums2recursion = [-2, 0, -10, -44, 5, 3, 0, 3]; +let nums3recursion = [200, 5, 4, 10, 8, 5, -3.3, 4.4, 0]; + +console.log(sortNumsRecursion(nums1recursion)); +console.log(sortNumsRecursion(nums2recursion)); +console.log(sortNumsRecursion(nums3recursion)); \ No newline at end of file diff --git a/objects-and-math/exercises/ObjectExercises.js b/objects-and-math/exercises/ObjectExercises.js index 9a50cbdecc..c017b65ede 100644 --- a/objects-and-math/exercises/ObjectExercises.js +++ b/objects-and-math/exercises/ObjectExercises.js @@ -2,23 +2,105 @@ let superChimpOne = { name: "Chad", species: "Chimpanzee", mass: 9, - age: 6 + age: 6, + astronautID: 1, + move: function () {return Math.floor(Math.random()*11)} }; let salamander = { name: "Lacey", species: "Axolotl Salamander", mass: 0.1, - age: 5 + age: 5, + astronautID: 2, + move: function () {return Math.floor(Math.random()*11)} }; +let chimpanzee = { + name: "Brad", + species: "Chimpanzee", + mass: 11, + age: 6, + astronautID: 3, + move: function () {return Math.floor(Math.random()*11)} +}; + +let beagle = { + name: "Leroy", + species: "Beagle", + mass: 14, + age: 5, + astronautID: 4, + move: function () {return Math.floor(Math.random()*11)} +}; + +let tardigrade = { + name: "Almina", + species: "Tardigrade", + mass: 0.0000000001, + age: 1, + astronautID: 5, + move: function () {return Math.floor(Math.random()*11)} +} // After you have created the other object literals, add the astronautID property to each one. +// superChimpOne.astronautID = 1; +// salamander.astronautID = 2; +// chimpanzee.astronautID = 3; +// beagle.astronautID = 4; +// tardigrade.astronautID = 5; + // Add a move method to each animal object +// superChimpOne.move = Math.floor(Math.random() * 11); + +// salamander.move = Math.floor(Math.random() * 11); + +// chimpanzee.move = Math.floor(Math.random() * 11); + +// beagle.move = Math.floor(Math.random() * 11); + +// tardigrade.move = Math.floor(Math.random() * 11); + // Create an array to hold the animal objects. +let crew = [superChimpOne, salamander, chimpanzee, beagle, tardigrade]; + // Print out the relevant information about each animal. +let crewReports = (animal) => { + return `${animal.name} is a ${animal.species}. They are ${animal.age} years old and ${animal.mass} kilograms. Their ID is ${animal.astronautID}.` +} + +console.log(crewReports(superChimpOne)); +console.log(crewReports(salamander)); +console.log(crewReports(chimpanzee)); +console.log(crewReports(beagle)); +console.log(crewReports(tardigrade)); + // Start an animal race! + +let fitnessTest = (arr) => { + let stepArr = []; + + for (let i = 0; i < arr.length; i++) { + let turn = 0; + let steps = 0; + + while (steps < 20) { + steps += arr[i].move(); + turn++; + } + + let str = `${arr[i].name} took ${turn} turns to take 20 steps.`; + + stepArr[i] = str; + } + + return stepArr; +} + +for (animal of fitnessTest(crew)) { + console.log(animal); +} \ No newline at end of file diff --git a/stringing-characters-together/exercises/part-one.js b/stringing-characters-together/exercises/part-one.js index 9295e4dd9f..014bf702a9 100644 --- a/stringing-characters-together/exercises/part-one.js +++ b/stringing-characters-together/exercises/part-one.js @@ -5,6 +5,17 @@ console.log(num.length); //Use type conversion to print the length (number of digits) of an integer. +console.log(String(num).length); + //Follow up: Print the number of digits in a DECIMAL value (e.g. num = 123.45 has 5 digits but a length of 6). +let dec = 123.45 +console.log(String(dec).length - 1); + //Experiment! What if num could be EITHER an integer or a decimal? Add an if/else statement so your code can handle both cases. + +if (String(num).includes(".")) { + console.log(String(num).length - 1); +} else { + console.log(String(num).length); +} \ No newline at end of file diff --git a/stringing-characters-together/exercises/part-three.js b/stringing-characters-together/exercises/part-three.js index 8c310f1445..cad6d31fc9 100644 --- a/stringing-characters-together/exercises/part-three.js +++ b/stringing-characters-together/exercises/part-three.js @@ -4,14 +4,30 @@ let language = 'JavaScript'; //1. Use string concatenation and two slice() methods to print 'JS' from 'JavaScript' +console.log(language.slice(0, 1) + language.slice(4, 5)); + //2. Without using slice(), use method chaining to accomplish the same thing. +console.log(language.charAt(0) + language.charAt(4)); +console.log(language.split("")[0] + language.split("")[4]); + //3. Use bracket notation and a template literal to print, "The abbreviation for 'JavaScript' is 'JS'." +let abrv = language.charAt(0) + language.charAt(4); + +console.log(`The abbreviation for 'JavaScript is '${abrv}'.`); + //4. Just for fun, try chaining 3 or more methods together, and then print the result. +let chain = abrv.replace("S", "ava").concat(" is cool!").toUpperCase(); + +console.log(chain); + //Part Three section Two //1. Use the string methods you know to print 'Title Case' from the string 'title case'. let notTitleCase = 'title case'; + +notTitleCase = notTitleCase.replace('t', 'T').replace('c', 'C'); +console.log(notTitleCase); \ No newline at end of file diff --git a/stringing-characters-together/exercises/part-two.js b/stringing-characters-together/exercises/part-two.js index a06e9094dc..575626b385 100644 --- a/stringing-characters-together/exercises/part-two.js +++ b/stringing-characters-together/exercises/part-two.js @@ -4,17 +4,20 @@ let dna = " TCG-TAC-gaC-TAC-CGT-CAG-ACT-TAa-CcA-GTC-cAt-AGA-GCT "; // First, print out the dna strand in it's current state. +console.log(dna); + //1) Use the .trim() method to remove the leading and trailing whitespace, then print the result. -console.log(/* Your code here. */); +console.log(dna.trim()); //2) Change all of the letters in the dna string to UPPERCASE, then print the result. -console.log(); +console.log(dna.trim().toUpperCase()); //3) Note that after applying the methods above, the original, flawed string is still stored in dna. To fix this, we need to reassign the changes to back to dna. //Apply these fixes to your code so that console.log(dna) prints the DNA strand in UPPERCASE with no whitespace. +dna = dna.trim().toUpperCase(); console.log(dna); //Part Two Section Two @@ -23,10 +26,32 @@ let dnaTwo = "TCG-TAC-GAC-TAC-CGT-CAG-ACT-TAA-CCA-GTC-CAT-AGA-GCT"; //1) Replace the gene "GCT" with "AGG", and then print the altered strand. +dnaTwo = dnaTwo.replace("GCT", "AGG"); +console.log(dnaTwo); + //2) Look for the gene "CAT" with ``indexOf()``. If found print, "CAT gene found", otherwise print, "CAT gene NOT found". +catGene = dnaTwo.indexOf("CAT"); + +if (catGene !== -1) { + console.log("CAT gene found"); +} else { + console.log("CAT NOT found"); +} + //3) Use .slice() to print out the fifth gene (set of 3 characters) from the DNA strand. +console.log(dnaTwo.slice(16, 19)); + //4) Use a template literal to print, "The DNA strand is ___ characters long." +let dnaTwoLength = dnaTwo.length; + +console.log(`The DNA strand is ${dnaTwoLength} characters long.`); + //5) Just for fun, apply methods to ``dna`` and use another template literal to print, 'taco cat'. + +let tacWord = dnaTwo.slice(4, 7); +let catWord = dnaTwo.slice(40, 43); + +console.log(`${tacWord}o ${catWord}`.toLowerCase()); \ No newline at end of file diff --git a/unit-testing/chapter-examples/palindrome-example/tests/palindrome.test.js b/unit-testing/chapter-examples/palindrome-example/tests/palindrome.test.js new file mode 100644 index 0000000000..bc614b8828 --- /dev/null +++ b/unit-testing/chapter-examples/palindrome-example/tests/palindrome.test.js @@ -0,0 +1,41 @@ +const isPalindrome = require("../palindrome.js"); + +describe("testing isPalindrome", function(){ + + test("should return true for a single letter", function() { + expect(isPalindrome("a")).toBe(true); + }) + + test("should return true for a single letter repeated", function() { + expect(isPalindrome("aaa")).toBe(true); + }) + + test("should return true for a simple palindrome", function() { + expect(isPalindrome("aba")).toBe(true); + }) + + test("should return true for a longer palindrome", function() { + expect(isPalindrome("racecar")).toBe(true); + }) + + test("should return false for a longer non-palindrome", function() { + expect(isPalindrome("launchcode")).toBe(false); + }) + + test("should return false for a simple non-palindrome", function() { + expect(isPalindrome("ab")).toBe(false); + }) + + test("should be case-sensitive", function() { + expect(isPalindrome("abA")).toBe(false); + }) + + test("should consider whitespace", function() { + expect(isPalindrome("so many dynamos")).toBe(false); + }) + + test("should consider the empty string a palindrome", function() { + expect(isPalindrome("")).toBe(true); + }) + +}) \ No newline at end of file diff --git a/unit-testing/chapter-examples/transmission-processor/processor.js b/unit-testing/chapter-examples/transmission-processor/processor.js new file mode 100644 index 0000000000..e27176a6ba --- /dev/null +++ b/unit-testing/chapter-examples/transmission-processor/processor.js @@ -0,0 +1,31 @@ +function processor(transmission) { + transmission = transmission.trim(); + + if (transmission.indexOf("::") < 0) { + // Data is invalid + return -1; + } + + let parts = transmission.split("::"); + + if (parts.length !== 2) { + return -1; + } + + let rawData = parts[1]; + + if (isNaN(Number(parts[0]))) { + return -1; + } + + if (rawData[0] !== "<" || rawData[rawData.length - 1] !== ">" || rawData.slice(1, -1).includes("<") || rawData.slice(1, -1).includes(">")) { + rawData = -1; + } + + return { + id: Number(parts[0]), + rawData: rawData + }; +} + +module.exports = processor; \ No newline at end of file diff --git a/unit-testing/chapter-examples/transmission-processor/tests/processor.test.js b/unit-testing/chapter-examples/transmission-processor/tests/processor.test.js index 1068db895f..e650bec936 100644 --- a/unit-testing/chapter-examples/transmission-processor/tests/processor.test.js +++ b/unit-testing/chapter-examples/transmission-processor/tests/processor.test.js @@ -1,5 +1,88 @@ -describe("transmission processor", function() { +const processor = require("../processor.js"); - // TODO: put tests here - - }); \ No newline at end of file +describe("transmission processor", function () { + + // TODO: put tests here + + test("takes a string returns an object", function() { + let result = processor("9701::<489584872710>"); + expect(typeof result).toBe("object"); + }) + + test("returns -1 if '::' not found", function() { + let result = processor("9701<489584872710>"); + expect(result).toBe(-1); + }) + + test("returns id in object", function() { + let result = processor("9701::<489584872710>"); + expect(result.id).not.toBeUndefined(); + }) + + test("converts id to a number", function() { + let result = processor("9701::<489584872710>"); + expect(result.id).toBe(9701); + }) + + test("returns rawData in object", () => { + let result = processor("9701::<487297403495720912>"); + expect(result.rawData).not.toBeUndefined(); + }) + + test("returns -1 for rawData if missing < at position 0", function() { + let result = processor("9701::487297403495720912>"); + expect(result.rawData).toBe(-1); + }) + + test("returns -1 for rawData if missing < at position 0 and > at wrong position", function() { + let result = processor("9701::8729740349572>0912"); + expect(result.rawData).toBe(-1); + }) + + test("returns -1 for rawData if missing < at position 0 but is elsewhere and missing > at last position", function() { + let result = processor("9701::4872<97403495720912"); + expect(result.rawData).toBe(-1); + }) + + test("returns -1 for rawData if missing < at position 0 and > at last position", function() { + let result = processor("9701::487297403495720912"); + expect(result.rawData).toBe(-1); + }) + + test("returns -1 for rawData with < in wrong place", function() { + let result = processor("9701::<487297403495<720912>"); + expect(result.rawData).toBe(-1); + }) + + test("returns -1 for rawData if missing > at last position", function() { + let result = processor("9701::<487297403495720912"); + expect(result.rawData).toBe(-1); + }) + + test("returns -1 for rawData with > in wrong place", function() { + let result = processor("9701::<487297403495>720912>"); + expect(result.rawData).toBe(-1); + }) + + test("leading and trailing whitespaces should be trimmed", function() { + let whitespaceResult = processor(" 9701::<489584872710> "); + let result = processor("9701::<489584872710>"); + expect(whitespaceResult.id).toBe(result.id); + }) + + test("returns -1 if id cannot be converted to a number", function() { + let result = processor("97d01::<489584872710>"); + expect(result).toBe(-1); + }) + + test("returns -1 if more than one '::' is found", function() { + let result = processor("97::01::<489584872710>"); + expect(result).toBe(-1); + }) + + test("rawData does not include < and > symbols", function() { + let result = processor("9701::<489584872710>"); + expect(result.rawData).toBe("489584872710"); + }) + +}); \ No newline at end of file diff --git a/unit-testing/exercises/RPS.js b/unit-testing/exercises/RPS.js index 6c1b3bad8d..f5b2ac0a0f 100644 --- a/unit-testing/exercises/RPS.js +++ b/unit-testing/exercises/RPS.js @@ -1,20 +1,27 @@ -function whoWon(player1,player2){ +function whoWon(player1, player2) { + if ((player1 === 'rock' || player1 === 'paper' || player1 === 'scissors') && (player2 === 'rock' || player2 === 'paper' || player2 === 'scissors')) { + if (player1 === player2) { + return 'TIE!'; + } - if (player1 === player2){ - return 'TIE!'; - } - - if (player1 === 'rock' && player2 === 'paper'){ - return 'Player 2 wins!'; - } - - if (player1 === 'paper' && player2 === 'scissors'){ - return 'Player 2 wins!'; - } - - if (player1 === 'scissors' && player2 === 'rock '){ - return 'Player 2 wins!'; - } - - return 'Player 1 wins!'; - } \ No newline at end of file + if (player1 === 'rock' && player2 === 'paper') { + return 'Player 2 wins!'; + } + + if (player1 === 'paper' && player2 === 'scissors') { + return 'Player 2 wins!'; + } + + if (player1 === 'scissors' && player2 === 'rock') { + return 'Player 2 wins!'; + } + + return 'Player 1 wins!'; + + } else { + return 'Invalid play.'; + } + +} + +module.exports = whoWon; \ No newline at end of file diff --git a/unit-testing/exercises/checkFive.js b/unit-testing/exercises/checkFive.js index 315da7b46b..248fcd89f1 100644 --- a/unit-testing/exercises/checkFive.js +++ b/unit-testing/exercises/checkFive.js @@ -1,11 +1,13 @@ -function checkFive(num){ - let result = ''; - if (num < 5){ - result = num + " is less than 5."; - } else if (num === 5){ - result = num + " is equal to 5."; - } else { - result = num + " is greater than 5."; - } - return result; - } \ No newline at end of file +function checkFive(num) { + let result = ''; + if (num < 5) { + result = num + " is less than 5."; + } else if (num === 5) { + result = num + " is equal to 5."; + } else { + result = num + " is greater than 5."; + } + return result; +} + +module.exports = checkFive; \ No newline at end of file diff --git a/unit-testing/exercises/tests/RPS.test.js b/unit-testing/exercises/tests/RPS.test.js index e69de29bb2..6eb991c08f 100644 --- a/unit-testing/exercises/tests/RPS.test.js +++ b/unit-testing/exercises/tests/RPS.test.js @@ -0,0 +1,60 @@ +const whoWon = require("../RPS.js"); + +describe("RPG", function() { + + test("should expect the game to be tied if both players play rock", function() { + let result = whoWon("paper", "paper"); + expect(result).toEqual("TIE!"); + }) + + test("should expect the game to be tied if both players play paper", function() { + let result = whoWon("scissors", "scissors"); + expect(result).toEqual("TIE!"); + }) + + test("should expect the game to be tied if both players play scissors", function() { + let result = whoWon("rock", "rock"); + expect(result).toEqual("TIE!"); + }) + + test("should expect player 2 paper to beat player 1 rock", function() { + let result = whoWon("rock", "paper"); + expect(result).toEqual("Player 2 wins!"); + }) + + test("should expect player 2 scissors to beat player 1 paper", function() { + let result = whoWon("paper", "scissors"); + expect(result).toEqual("Player 2 wins!"); + }) + + test("should expect player 2 rock to beat player 1 scissors", function() { + let result = whoWon("scissors", "rock"); + expect(result).toEqual("Player 2 wins!"); + }) + + test("should expect player 1 paper to beat player 2 rock", function() { + let result = whoWon("paper", "rock"); + expect(result).toEqual("Player 1 wins!"); + }) + + test("should expect player 1 scissors to beat player 2 paper", function() { + let result = whoWon("scissors", "paper"); + expect(result).toEqual("Player 1 wins!"); + }) + + test("should expect player 1 rock to beat player 2 scissors", function() { + let result = whoWon("rock", "scissors"); + expect(result).toEqual("Player 1 wins!"); + }) + + test("should return invalid if player 1 does not play rock paper or scissors", function() { + let result = whoWon("dock", "rock"); + expect(result).toEqual("Invalid play."); + }) + + test("should return invalid if player 2 does not player rock paper or scissors", function() { + let result = whoWon("rock", "dock"); + expect(result).toEqual("Invalid play."); + }) + +}) \ No newline at end of file diff --git a/unit-testing/exercises/tests/checkFive.test.js b/unit-testing/exercises/tests/checkFive.test.js index e69de29bb2..b6ddf971c5 100644 --- a/unit-testing/exercises/tests/checkFive.test.js +++ b/unit-testing/exercises/tests/checkFive.test.js @@ -0,0 +1,20 @@ +const checkFive = require("../checkFive.js"); + +describe("checkFive", function() { + + test("should expect to result less than 5 if 2 is passed in", function() { + let output = checkFive(2); + expect(output).toEqual("2 is less than 5."); + }) + + test("should expect to result greater than 5 if 7 is passed in", function() { + let output = checkFive(7); + expect(output).toEqual("7 is greater than 5."); + }) + + test("should expect result to be equivalent if 5 is passed in", function() { + let output = checkFive(5); + expect(output).toEqual("5 is equal to 5."); + }) + +}) \ No newline at end of file diff --git a/user-input-with-forms/exercises/index.html b/user-input-with-forms/exercises/index.html index 00a01b39ed..51c37e8d0d 100644 --- a/user-input-with-forms/exercises/index.html +++ b/user-input-with-forms/exercises/index.html @@ -9,6 +9,19 @@ +

    Rocket Simulation

    +
    + + + + + Wind Rating: + + + + + +
    diff --git a/user-input-with-forms/exercises/script.js b/user-input-with-forms/exercises/script.js index 8e41e69915..8503ff4d08 100644 --- a/user-input-with-forms/exercises/script.js +++ b/user-input-with-forms/exercises/script.js @@ -1 +1,15 @@ //Code Your Solution Below + +window.addEventListener("load", () => { + + let form = document.querySelector("form"); + form.addEventListener("submit", e => { + const testName = document.getElementById("testName"); + const testDate = document.getElementById("testDate"); + const boosterCount = document.getElementById("boosterCount"); + if (testName === "" || testDate === "" || boosterCount === "") { + e.preventDefault(); + } + }) + +}) \ No newline at end of file