From f8259f52cc7df22f395d8cf66aea82d341e24c58 Mon Sep 17 00:00:00 2001 From: Halid Besic Date: Fri, 14 Jun 2024 00:28:12 -0500 Subject: [PATCH 01/12] finished assignment --- .../exercises/data-and-variables-exercises.js | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/data-and-variables/exercises/data-and-variables-exercises.js b/data-and-variables/exercises/data-and-variables-exercises.js index 6433bcd641..53c3fd9621 100644 --- a/data-and-variables/exercises/data-and-variables-exercises.js +++ b/data-and-variables/exercises/data-and-variables-exercises.js @@ -1,11 +1,25 @@ // Declare and assign the variables below +let shuttleName = 'Determination'; +let shuttleSpeedMph = 17500; +let distanceToMarsKm = 225000000; +let distanceToMoonKm = 38400; +const milesPerKm = 0.621; // Use console.log to print the 'typeof' each variable. Print one item per line. - +console.log(typeof(shuttleName)); +console.log(typeof(shuttleSpeedMph)); +console.log(typeof(distanceToMarsKm)); +console.log(typeof(distanceToMoonKm)); +console.log(typeof(milesPerKm)); // Calculate a space mission below - +let milesToMars = distanceToMarsKm * milesPerKm; +let hoursToMars = milesToMars / shuttleSpeedMph; +let daysToMars = hoursToMars / 24; // Print the results of the space mission calculations below - +console.log(shuttleName + " will take " + daysToMars + " days to reach the 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 = distanceToMoonKm * milesPerKm; +let hoursToMoon = milesToMoon / shuttleSpeedMph; +let daysToMoon = hoursToMoon / 24; +// Print the results of the trip to the moon below +console.log(shuttleName + " will take " + daysToMoon + " days to reach the Moon."); \ No newline at end of file From b1dacb3f9e6f8a9a080949e188958ed0fd58b69c Mon Sep 17 00:00:00 2001 From: Halid Besic Date: Mon, 17 Jun 2024 20:46:09 -0500 Subject: [PATCH 02/12] completed studio --- .../studio/data-variables-conditionals.js | 65 +++++++++++++++++-- 1 file changed, 58 insertions(+), 7 deletions(-) diff --git a/booleans-and-conditionals/studio/data-variables-conditionals.js b/booleans-and-conditionals/studio/data-variables-conditionals.js index 6a15e146f4..9c18eb51be 100644 --- a/booleans-and-conditionals/studio/data-variables-conditionals.js +++ b/booleans-and-conditionals/studio/data-variables-conditionals.js @@ -1,15 +1,66 @@ // 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 - +if (astronautCount < 7) { + preparedForLiftOff = false; + console.log("Security Alert! Kick off " + (astronautCount - 7) + " astronauts off to launch!"); +} // add logic below to verify all astronauts are ready - +if (astronautStatus !== "ready") { + preparedForLiftOff = false; + console.log("Somehow, one or more astronauts is not ready?????"); +} // add logic below to verify the total mass does not exceed the maximum limit of 850000 - +if (totalmassKg > maximumMassLimit) { + console.log("Mass exceeds maximum mass limit!"); + preparedForLiftOff = false; +} // add logic below to verify the fuel temperature is within the appropriate range of -150 and -300 - +if (fuelTempCelsius < minimumFuelTemp || fuelTempCelsius > maximumFuelTemp) { + console.log("Fuel temperature not in range - DO NOT LAUNCH!"); + preparedForLiftOff = false; +} // add logic below to verify the fuel level is at 100% - +if (fuelLevel !== "100%") { + console.log("Please refuel before launch."); + preparedForLiftOff = "false"; +} // add logic below to verify the weather status is clear - +if (weatherStatus !== "clear") { + console.log("Weather is not clear, DO NOT LAUNCH!"); + preparedForLiftOff = "false"; +} // Verify shuttle launch can proceed based on above conditions +if (!preparedForLiftOff) { + console.log("Abort Mission!"); +} else { + console.log(` + All systems are a go! Initiating space shuttle launch sequence. + --------------------------------------------------------------- + Date: ${date} + Time: ${time} + Astronaut Count: ${astronautCount} + Crew Mass: ${crewMassKg} kg + Fuel Mass: ${fuelMassKg} kg + Shuttle Mass: ${shuttleMassKg} kg + Total Mass: ${totalmassKg} kg + Fuel Temperature: ${fuelTempCelsius} C + Weather Status: ${weatherStatus} + --------------------------------------------------------------- + Have a safe trip astronauts!`); +} \ No newline at end of file From 0a85e9d7f4624d318c29e9f2834b01b8da6c21f0 Mon Sep 17 00:00:00 2001 From: Halid Besic Date: Mon, 17 Jun 2024 21:55:22 -0500 Subject: [PATCH 03/12] completed --- booleans-and-conditionals/exercises/part-1.js | 7 +++++- booleans-and-conditionals/exercises/part-2.js | 25 +++++++++++++++---- booleans-and-conditionals/exercises/part-3.js | 25 ++++++++++++++++++- 3 files changed, 50 insertions(+), 7 deletions(-) diff --git a/booleans-and-conditionals/exercises/part-1.js b/booleans-and-conditionals/exercises/part-1.js index b829140a07..f762a9521f 100644 --- a/booleans-and-conditionals/exercises/part-1.js +++ b/booleans-and-conditionals/exercises/part-1.js @@ -1,5 +1,10 @@ // 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..c48650faf0 100644 --- a/booleans-and-conditionals/exercises/part-2.js +++ b/booleans-and-conditionals/exercises/part-2.js @@ -8,14 +8,29 @@ let shuttleSpeed = 15000; // 3) Write conditional expressions to satisfy the following safety rules: // 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("ALERT: Computer offline!"); +} 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..ea0f73d2c8 100644 --- a/booleans-and-conditionals/exercises/part-3.js +++ b/booleans-and-conditionals/exercises/part-3.js @@ -17,8 +17,31 @@ e) If fuelLevel is below 1000 OR engineTemperature is above 3500 OR engineIndica 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. +const commandOverride = true || false; +if (!commandOverride == false){ + console.log("Launch only if the fuel and engine check are OK."); + } else if (commandOverride == true){ + console.log("Shuttle will 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 || commandOverride === true) { + console.log("Cleared to Launch!"); + } else { + console.log("Launch scrubbed!"); + } \ No newline at end of file From f1b6dde82627cc6ba618fb5424788e8a1891ae55 Mon Sep 17 00:00:00 2001 From: Halid Besic Date: Mon, 17 Jun 2024 22:17:49 -0500 Subject: [PATCH 04/12] completed --- .../exercises/Debugging1stSyntaxError.js | 2 +- .../exercises/DebuggingLogicErrors2.js | 1 + .../exercises/DebuggingLogicErrors3.js | 2 +- .../exercises/DebuggingLogicErrors5.js | 19 +++++++++++++++---- .../exercises/DebuggingRuntimeErrors1.js | 2 +- .../exercises/DebuggingRuntimeErrors2.js | 2 +- .../exercises/DebuggingSyntaxErrors2.js | 4 ++-- 7 files changed, 22 insertions(+), 10 deletions(-) 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/DebuggingLogicErrors2.js b/errors-and-debugging/exercises/DebuggingLogicErrors2.js index 160a0c2cd0..b7b59c7682 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors2.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors2.js @@ -16,6 +16,7 @@ if (fuelLevel >= 20000) { console.log('WARNING: Insufficient fuel!'); launchReady = false; } +console.log(launchReady); // if (crewStatus && computerStatus === 'green'){ // console.log('Crew & computer cleared.'); diff --git a/errors-and-debugging/exercises/DebuggingLogicErrors3.js b/errors-and-debugging/exercises/DebuggingLogicErrors3.js index 023f2ab07d..517d14c2d5 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors3.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors3.js @@ -25,7 +25,7 @@ if (crewStatus && computerStatus === 'green'){ console.log('WARNING: Crew or computer not ready!'); 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/DebuggingLogicErrors5.js b/errors-and-debugging/exercises/DebuggingLogicErrors5.js index 7eb908e769..92fc4ad5ef 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 crewReady = false; let fuelLevel = 17000; let crewStatus = true; let computerStatus = 'green'; @@ -14,15 +15,25 @@ if (fuelLevel >= 20000) { console.log('WARNING: Insufficient fuel!'); launchReady = false; } - console.log("launchReady = ", launchReady); + if (crewStatus && computerStatus === 'green'){ console.log('Crew & computer cleared.'); - launchReady = true; + crewReady = true; } else { console.log('WARNING: Crew or computer not ready!'); - launchReady = false; + crewReady = false; } +console.log("crewReady = ", crewReady); -console.log("launchReady = ", launchReady); \ No newline at end of file +if (crewReady && launchReady === true) { + console.log("10, 9, 8..."); + console.log("Fed parrot..."); + console.log("6, 5, 4..."); + console.log("Ignition..."); + consoul.log("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..1129d9fb8e 100644 --- a/errors-and-debugging/exercises/DebuggingRuntimeErrors2.js +++ b/errors-and-debugging/exercises/DebuggingRuntimeErrors2.js @@ -9,7 +9,7 @@ if (fuelLevel >= 20000) { launchReady = false; } -if (launchReady) { +if (launchReady = false) { console.log("10, 9, 8..."); console.log("Fed parrot..."); console.log("6, 5, 4..."); 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!"); From 74fd25118b66627555390020a5d31f06357d5393 Mon Sep 17 00:00:00 2001 From: Halid Besic Date: Sun, 23 Jun 2024 22:54:17 -0500 Subject: [PATCH 05/12] 2 completed --- .../array-string-conversion/array-testing.js | 45 +++++++++++++------ arrays/studio/multi-dimensional-arrays.js | 15 +++++-- arrays/studio/string-modification.js | 21 +++++++++ 3 files changed, 64 insertions(+), 17 deletions(-) diff --git a/arrays/studio/array-string-conversion/array-testing.js b/arrays/studio/array-string-conversion/array-testing.js index c4d5899385..cf5cd931e2 100644 --- a/arrays/studio/array-string-conversion/array-testing.js +++ b/arrays/studio/array-string-conversion/array-testing.js @@ -8,42 +8,61 @@ strings = [protoArray1, protoArray2, protoArray3, protoArray4]; //2) function reverseCommas() { //TODO: 1. create and instantiate your variables. - let check; - let output; + let check = strings[0]; + let output = []; //TODO: 2. write the code required for this step - + if (check.includes(',')) { + output = check.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 { }. + console.log(output); return output; } +reverseCommas(); + //3) function semiDash() { - let check; - let output; + let check = strings[1]; + let output = []; //TODO: write the code required for this step - - + if (check.includes(';')) { + output = check.split(';').sort().join('-'); + } + console.log(output); return output; } +semiDash(); + //4) function reverseSpaces() { - let check; + let check = strings[2]; let output; //TODO: write the code required for this step - - return output; + if (check.includes(' ')) { + output = (check.split(' ').sort().reverse().join(' ')); +} +console.log(output); +return output; } +reverseSpaces(); + //5) function commaSpace() { - let check; - let output; + let check = strings[3]; + let output = []; //TODO: write the code required for this step - + if (check.includes(', ')) { + output = check.split(', ').reverse().join(','); + } + console.log(output); return output; } +commaSpace(); + // NOTE: Don't add or modify any code below this line or your program might not run as expected. module.exports = { strings : strings, diff --git a/arrays/studio/multi-dimensional-arrays.js b/arrays/studio/multi-dimensional-arrays.js index 18761a8934..e61d51341f 100644 --- a/arrays/studio/multi-dimensional-arrays.js +++ b/arrays/studio/multi-dimensional-arrays.js @@ -2,13 +2,20 @@ 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"; let sleepAids = "blankets,pillows,eyepatches,alarm clocks"; - //1) Use split to convert the strings into four cabinet arrays. Alphabetize the contents of each cabinet. - +cabinetOne = food.split(',').sort(); +cabinetTwo = equipment.split(',').sort(); +cabinetThree = pets.split(',').sort(); +cabinetFour = sleepAids.split(',').sort(); //2) Initialize a cargoHold array and add the cabinet arrays to it. Print cargoHold to verify its structure. - +let cargoHold = [cabinetOne, cabinetTwo, cabinetThree, cabinetFour]; +for (let i = 0; i < cargoHold.length; i++) { + console.log(cargoHold[i]); +} //3) Query the user to select a cabinet (0 - 3) in the cargoHold. +let userInput = prompt("Please select a cabinet (0 - 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. +//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. +//let cargoOutput = "" //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 ____.” diff --git a/arrays/studio/string-modification.js b/arrays/studio/string-modification.js index 45991b15fc..631d0e5f5d 100644 --- a/arrays/studio/string-modification.js +++ b/arrays/studio/string-modification.js @@ -4,8 +4,29 @@ 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 newString = str.slice(3) + str.slice(0,3); + + //Use a template literal to print the original and modified string in a descriptive phrase. + +//console.log(` 'We change ${str} into ${newString} using string methods'`); + + //2) Modify your code to accept user input. Query the user to enter the number of letters that will be relocated. +let numLetters = Number(input.question("How many letters will be location? ")); + +let newString = str.slice(numLetters) + str.slice(0, numLetters); + +console.log(newString); + //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 (numLetters > str.length){ + console.log("Input exceeded length of the word."); + let defaultString = str.slice(3) + str.slice(0,3); + console.log(` 'We change ${str} into ${defaultString} using string methods'`); +} else { + console.log(` 'We change ${str} into ${newString} using string methods'`); +} \ No newline at end of file From 46c81aee3fd0e673c35d0a8923041eebf016b19b Mon Sep 17 00:00:00 2001 From: Halid Besic Date: Mon, 24 Jun 2024 19:04:22 -0500 Subject: [PATCH 06/12] Completed exercise. --- .../exercises/part-one.js | 12 ++++++++--- .../exercises/part-three.js | 10 ++++++---- .../exercises/part-two.js | 20 +++++++++++++------ 3 files changed, 29 insertions(+), 13 deletions(-) diff --git a/stringing-characters-together/exercises/part-one.js b/stringing-characters-together/exercises/part-one.js index 9295e4dd9f..bae361ab0b 100644 --- a/stringing-characters-together/exercises/part-one.js +++ b/stringing-characters-together/exercises/part-one.js @@ -1,10 +1,16 @@ -let num = 1001; +let num = 123.45; //Returns 'undefined'. 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). - +console.log(String(num).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..1c201079aa 100644 --- a/stringing-characters-together/exercises/part-three.js +++ b/stringing-characters-together/exercises/part-three.js @@ -3,15 +3,17 @@ 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)); //3. Use bracket notation and a template literal to print, "The abbreviation for 'JavaScript' is 'JS'." - +console.log(`The abbreviation for '${language}' is '${language.slice(0,1)+language.slice(4,5)}'.`) //4. Just for fun, try chaining 3 or more methods together, and then print the result. - +console.log(language.replace('a', 4).trim().toUpperCase()); //Part Three section Two //1. Use the string methods you know to print 'Title Case' from the string 'title case'. let notTitleCase = 'title case'; +let titleCase = notTitleCase[0].toUpperCase() + notTitleCase.slice(1, 5) + " " + notTitleCase[6].toUpperCase() + notTitleCase.slice(7); +console.log(titleCase); \ 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..f632d51a05 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.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 @@ -22,11 +25,16 @@ console.log(dna); 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. - +console.log(dnaTwo.replace('GCT', 'AGG')); //2) Look for the gene "CAT" with ``indexOf()``. If found print, "CAT gene found", otherwise print, "CAT gene NOT found". - +if (dnaTwo.indexOf('CAT')) { + console.log("CAT gene found"); +} else { + console.log("CAT gene 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." - +console.log(`The DNA strand is ${dnaTwo.length} characters long.`) //5) Just for fun, apply methods to ``dna`` and use another template literal to print, 'taco cat'. +console.log(`${dna.slice(4,7).toLowerCase()}o ${dna.slice(dna.indexOf('CAT'),dna.indexOf('CAT')+3).toLowerCase()}`); From 8315c054efb8fedb118d83c3f19ee54093e00ca3 Mon Sep 17 00:00:00 2001 From: Halid Besic Date: Mon, 24 Jun 2024 19:05:44 -0500 Subject: [PATCH 07/12] Completed the exercise. --- arrays/exercises/part-five-arrays.js | 13 ++++++++--- arrays/exercises/part-four-arrays.js | 12 +++++++++-- arrays/exercises/part-one-arrays.js | 8 ++++++- arrays/exercises/part-six-arrays.js | 31 +++++++++++++++++++++++---- arrays/exercises/part-three-arrays.js | 7 ++++-- arrays/exercises/part-two-arrays.js | 13 ++++++++--- 6 files changed, 69 insertions(+), 15 deletions(-) diff --git a/arrays/exercises/part-five-arrays.js b/arrays/exercises/part-five-arrays.js index 4cdf1bba41..ca5e4fd37c 100644 --- a/arrays/exercises/part-five-arrays.js +++ b/arrays/exercises/part-five-arrays.js @@ -2,10 +2,17 @@ let str = 'In space, no one can hear you code.'; 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()); +console.log(str.split('e')); +console.log(str.split(' ')); +console.log(str.split('')); //2) Use the join method on the array to identify the purpose of the parameter inside the (). - +console.log(arr.join()); +console.log(arr.join('a')); +console.log(arr.join(' ')); +console.log(arr.join('')); //3) Do split or join change the original string/array? - +console.log(str.split(',') + arr.join(',')); //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..473b4f8dc9 100644 --- a/arrays/exercises/part-four-arrays.js +++ b/arrays/exercises/part-four-arrays.js @@ -4,7 +4,15 @@ let holdCabinet2 = ['orange drink', 'nerf toys', 'camera', 42, 'parsnip']; //Explore the methods concat, slice, reverse, and sort to determine which ones alter the original array. //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. - +console.log(holdCabinet1.concat(holdCabinet2)); +console.log(holdCabinet1); //2) Print a slice of two elements from each array. Does slice alter the original arrays? - +holdCabinet1.slice(2); +console.log(holdCabinet1); +holdCabinet2.slice(3); +console.log(holdCabinet2); //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(); +holdCabinet2.sort(); +console.log(holdCabinet1); +console.log(holdCabinet2); \ No newline at end of file diff --git a/arrays/exercises/part-one-arrays.js b/arrays/exercises/part-one-arrays.js index 92f4e45170..cc58194ff8 100644 --- a/arrays/exercises/part-one-arrays.js +++ b/arrays/exercises/part-one-arrays.js @@ -1,5 +1,11 @@ //Create an array called practiceFile with the following entry: 273.15 - +let practiceFile = [273.15]; //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.push(42); +console.log(practiceFile); +practiceFile.push("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..ace12cf0b5 100644 --- a/arrays/exercises/part-six-arrays.js +++ b/arrays/exercises/part-six-arrays.js @@ -1,11 +1,34 @@ //Arrays can hold different data types, even other arrays! A multi-dimensional array is one with entries that are themselves arrays. //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); +table.push(element2); +table.push(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[1]); +console.log(table[1][1]); //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(table[0][2]); +console.log(table[1][0]); +console.log(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 threeDimensialArr = + [ + [ ['a', 'b','c'], + + ['d', 'e','f'], + ], + [ + ['g', 'h','i'], + + ['j', 'k','l'] ] + ]; + console.log(threeDimensialArr[0]); + console.log(threeDimensialArr[0][1]); + console.log(threeDimensialArr[0][1][2]); \ No newline at end of file diff --git a/arrays/exercises/part-three-arrays.js b/arrays/exercises/part-three-arrays.js index d43918a702..e5a038136d 100644 --- a/arrays/exercises/part-three-arrays.js +++ b/arrays/exercises/part-three-arrays.js @@ -3,7 +3,10 @@ let cargoHold = [1138, 'space suits', 'parrot', 'instruction manual', 'meal pack //Use splice to make the following changes to the cargoHold array. Be sure to print the array after each step to confirm your updates. //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(3); //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..a1d3202fab 100644 --- a/arrays/exercises/part-two-arrays.js +++ b/arrays/exercises/part-two-arrays.js @@ -1,11 +1,18 @@ let cargoHold = ['oxygen tanks', 'space suits', 'parrot', 'instruction manual', 'meal packs', 'slinky', 'security blanket']; //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. - +cargoHold.pop('security blanket'); +console.log(cargoHold); //3) Remove the first item from the array with shift. Print the element removed and the updated array. - +console.log(cargoHold.shift()); +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(`The array ${cargoHold} has a length of ${cargoHold.length}.`); \ No newline at end of file From 784f7025db47325798995f2e6b043a72ea7c7ae7 Mon Sep 17 00:00:00 2001 From: Halid Besic Date: Mon, 24 Jun 2024 20:33:22 -0500 Subject: [PATCH 08/12] completed studios --- loops/studio/solution.js | 53 +++++++++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/loops/studio/solution.js b/loops/studio/solution.js index 4e21a9caa5..3a4de4c5fc 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,26 +15,45 @@ 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 meal = []; + for (let item of pantry ) { + meal.push(item[i]); + } + meals.push(meal); + } 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? "); /// CODE YOUR SOLUTION TO PART B here /// - + while (numMeals < 1 || numMeals > 6 || numMeals === NaN) { + numMeals = input.question("Invalid input, please enter a number between 1 through 6: "); + } return numMeals; } function generatePassword(string1, string2) { let code = ''; + let maxLength = string1.length; + if (maxLength < string2.length) { + maxLength = string2.length; + } /// Code your Bonus Mission Solution here /// - + for (let i = 0; i < maxLength; i++) { + if (i < string1.length) { + code += string1[i]; + } + if (i < string2.length) { + code += string2[i]; + } + } return code; } @@ -45,24 +64,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 = '12345'; + 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 = { From 06372cea431250987583c0b12db6ea1c30659dc4 Mon Sep 17 00:00:00 2001 From: Halid Besic Date: Mon, 15 Jul 2024 20:36:16 -0500 Subject: [PATCH 09/12] Completed studio --- unit-testing/studio/index.js | 25 ++++++++- unit-testing/studio/tests/launchcode.test.js | 57 ++++++++++++++++++++ 2 files changed, 81 insertions(+), 1 deletion(-) diff --git a/unit-testing/studio/index.js b/unit-testing/studio/index.js index 2ba56cb9bd..bd58c77a48 100644 --- a/unit-testing/studio/index.js +++ b/unit-testing/studio/index.js @@ -1,6 +1,29 @@ let launchcode = { - + organization:'nonprofit', + executiveDirector:'Jeff', + percentageCoolEmployees:100, + programsOffered: ['Web Development', 'Data Analysis', 'Liftoff'], + launchOutput: function(numVal) { + if((numVal % 2 === 0) && (numVal % 3 === 0) && (numVal % 5 === 0)) { + return "LaunchCode Rocks!"; + } else if ((numVal % 2 === 0) && (numVal % 3 === 0)) { + return "LaunchCode!" + } else if ((numVal % 3 === 0) && (numVal % 5 === 0)){ + return "Code Rocks!"; + } else if ((numVal % 2 === 0) && (numVal % 5 === 0)){ + return "Launch Rocks!" + } else if ((numVal % 2 === 0)) { + return "Launch!"; + } else if ((numVal % 3 === 0)) { + return "Code!"; + } else if ((numVal % 5 === 0)) { + return "Rocks!"; + } else { + return "Rutabagas! That doesn't work."; + } + return string; +} } module.exports = launchcode; diff --git a/unit-testing/studio/tests/launchcode.test.js b/unit-testing/studio/tests/launchcode.test.js index f535305e3b..b79fd6b663 100644 --- a/unit-testing/studio/tests/launchcode.test.js +++ b/unit-testing/studio/tests/launchcode.test.js @@ -4,5 +4,62 @@ const launchcode = require('../index.js'); describe("Testing launchcode", function(){ // Write your unit tests here! + test ("should have property named organization with value of nonprofit", function(){ + expect(launchcode.organization).toBe('nonprofit'); + }); + + test ("should have property named executiveDirector with value of Jeff", function(){ + expect(launchcode.executiveDirector).toBe('Jeff'); + }); + + test ("should have property named percentageCoolEmployees with value of 100", function(){ + expect(launchcode.percentageCoolEmployees).toBe(100); + }); + + test("should contain key 'programsOffered' with array values 'Web Development, Data Analysis, Liftoff'.", function () { + expect(launchcode.programsOffered[0]).toBe('Web Development'); + expect(launchcode.programsOffered[1]).toBe('Data Analysis'); + expect(launchcode.programsOffered[2]).toBe('Liftoff'); + expect(launchcode.programsOffered.length).toBe(3); + }); + + test('should pass a number that is ONLY divisible by 2', function() { + let output = launchcode.launchOutput(2); + expect(output).toBe('Launch!'); + }); + + test('should pass a number that is ONLY divisible by 3', function() { + let output = launchcode.launchOutput(3); + expect(output).toBe('Code!'); + }); + test('should pass a number that is ONLY divisible by 5', function() { + let output = launchcode.launchOutput(5); + expect(output).toBe('Rocks!'); + }); + + test('should pass a number that is divisible by 2 and 3' , function() { + let output = launchcode.launchOutput(6); + expect(output).toBe('LaunchCode!'); + }); + + test('should pass a number that is divisible by 3 and 5', function() { + let output = launchcode.launchOutput(15); + expect(output).toBe('Code Rocks!'); + }); + + test('should pass a number that is divisible by 2 and 5', function() { + let output = launchcode.launchOutput(10); + expect(output).toBe('Launch Rocks!'); + }); + + test('should pass a number that is divisible by 2, 3, and 5', function() { + let output = launchcode.launchOutput(30); + expect(output).toBe('LaunchCode Rocks!'); + }); + + test('should pass a number that is NOT divisible by 2, 3, or 5', function() { + let output = launchcode.launchOutput(); + expect(output).toBe("Rutabagas! That doesn't work."); + }); }); \ No newline at end of file From 4788aadfb4e874c9d19d6c0b3c21b2154fb2b1d6 Mon Sep 17 00:00:00 2001 From: Halid Besic Date: Mon, 22 Jul 2024 20:28:17 -0500 Subject: [PATCH 10/12] Completed Studio --- classes/studio/ClassStudio.js | 43 ++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/classes/studio/ClassStudio.js b/classes/studio/ClassStudio.js index c3a6152140..3cf3818be8 100644 --- a/classes/studio/ClassStudio.js +++ b/classes/studio/ClassStudio.js @@ -1,9 +1,50 @@ //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() { + let sum = 0; + for (let i = 0; i < this.scores.length; i++) { + sum += this.scores[i]; + } + let avg = sum/this.scores.length; + return Math.round(avg*10)/10; + } + status() { + let status; + let avgScore = this.average(); + if (avgScore >= 90) { + status = "Accepted"; + } else if (avgScore >= 80 && avgScore < 90) { + status = "Reserve"; + } else if (avgScore >= 70 && avgScore < 80) { + status = "Probationary"; + } else { + status = "Rejected"; + } + return status; + } +} +let bubbaBear = new CrewCandidate('Bubba Bear', 135, [88,85,90]); +let merryMaltese = new CrewCandidate('Merry Maltese', 1.5, [93,88,97]); +let gladGator = new CrewCandidate('Glad Gator', 225, [75,78,62]); + + +console.log(`${bubbaBear.name} earned an average test score of ${bubbaBear.average()}% and has a status of ${bubbaBear.status()}.`); +console.log(`${merryMaltese.name} earned an average test score of ${merryMaltese.average()}% and has a status of ${merryMaltese.status()}.`); +console.log(`${gladGator.name} earned an 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. -//Part 4 - Use the methods to boost Glad Gator’s status to Reserve or higher. How many tests will it take to reach Reserve status? How many to reach Accepted? Remember, scores cannot exceed 100%. \ No newline at end of file +//Part 4 - Use the methods to boost Glad Gator’s status to Reserve or higher. How many tests will it take to reach Reserve status? How many to reach Accepted? Remember, scores cannot exceed 100%. + From 38378147fa3f9e6ea8eeaa257ffcee99962f308b Mon Sep 17 00:00:00 2001 From: Halid Besic Date: Sat, 27 Jul 2024 17:55:37 -0500 Subject: [PATCH 11/12] completed --- loops/exercises/for-Loop-Exercises.js | 44 +++++++++++++++++++++++-- loops/exercises/while-Loop-Exercises.js | 25 +++++++++++--- 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/loops/exercises/for-Loop-Exercises.js b/loops/exercises/for-Loop-Exercises.js index c659c50852..f8f1297cba 100644 --- a/loops/exercises/for-Loop-Exercises.js +++ b/loops/exercises/for-Loop-Exercises.js @@ -3,7 +3,25 @@ b. Print only the ODD values from 3 - 29, one number per line. 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 <= 20; i++) { + console.log(i); + } + //b + for (let i = 3; i <= 29; i += 2) { + console.log(i); + } + //c + for (let i = 12; i >= -14; i -= 2) { + console.log(i); + } + //d + for (let i = 50; i >= 20; i--) { + if (i % 3 === 0) { + console.log(i); + } + } + */ @@ -14,11 +32,33 @@ Initialize two variables to hold the string “LaunchCode” and the array [1, 5 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]; + for (let i = 0; i < arr.length; i++) { + console.log(arr[i]); + } + let reversedStr = str.split("").reverse().join(""); +for (let i = 0; i < reversedStr.length; i++) { + console.log(reversedStr[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. */ +let longArr = [2, 3, 13, 18, -5, 38, -10, 11, 0, 104]; +let evens = []; +let odds = []; + +for (let i = 0; i < longArr.length; i++) { + if (longArr[i] % 2 === 0) { + evens.push(longArr[i]); + } else { + odds.push(longArr[i]); + } +} + console.log(evens); + console.log(odds); \ No newline at end of file diff --git a/loops/exercises/while-Loop-Exercises.js b/loops/exercises/while-Loop-Exercises.js index 53a8ce1250..7f650bf9ac 100644 --- a/loops/exercises/while-Loop-Exercises.js +++ b/loops/exercises/while-Loop-Exercises.js @@ -1,4 +1,7 @@ //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'); + +let fuelLevel = 0, numAstronauts = 0, altitude = 0; @@ -6,20 +9,34 @@ /*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 (fuelLevel <=5000 || fuelLevel > 30000 || isNaN(fuelLevel)) { + fuelLevel = 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 (numAstronauts < 1 || numAstronauts > 7 || isNaN(numAstronauts)) { + numAstronauts = input.question("Enter the number of astronauts (1 - 7): "); +} //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 (fuelLevel-100*numAstronauts >= 0) { + altitude += 50; + fuelLevel -= 100*numAstronauts; + } /*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.”*/ +let output = `The shuttle gained an altitude of ${altitude} km.`; + +if (altitude >= 2000) { +output += " Orbit achieved!"; +} else if (altitude < 2000){ + output = "Failed to reach orbit."; +} +console.log(output); From 6d867189e4faca33348738f0bfb92be114aaa2d1 Mon Sep 17 00:00:00 2001 From: Halid Besic Date: Sat, 27 Jul 2024 18:29:24 -0500 Subject: [PATCH 12/12] completed exercise --- functions/function-exercises | 63 ++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 functions/function-exercises diff --git a/functions/function-exercises b/functions/function-exercises new file mode 100644 index 0000000000..147e61a4d6 --- /dev/null +++ b/functions/function-exercises @@ -0,0 +1,63 @@ +function makeLine(size) { + let line = ''; + for (let i = 0; i < size; i++) { + line += '#'; + } + return line; +} +//console.log(makeLine(5)); + +function makeSquare(width, height) { +let square = ''; +for (let i = 0; i < height; i++) { + square += (makeLine(width) + '\n'); + } + return square.slice(0, -1); +} +//console.log(makeSquare(5,5)); + +function makeRectangle(width, height) { + let rectangle = ''; + for (let i = 0; i < height; i++) { + rectangle += (makeLine(width) + '\n'); + } + return rectangle.slice(0, -1); + } +console.log(makeRectangle(5,3)); + +function makeDownwardStairs(height) { + let stairs = ''; + for (let i = 0; i < height; i++) { + stairs += (makeLine(i+1) + '\n'); + } + return stairs.slice(0,-1); +} +console.log(makeDownwardStairs(5)); + +function makeSpaceLine(numSpaces, numChars) { + let spaces = ' '.repeat(numSpaces); + let hashes = '#'.repeat(numChars); + return spaces + hashes + spaces; +} +console.log(makeSpaceLine(3,5)); + +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)); + +function makeDiamond(height) { + let diamond = ''; + for (let i = 0; i < height; i++) { + diamond += (makeSpaceLine(height - i - 1, 2*i + 1) + '\n'); + } + for (let i = height - 2; i >= 0; i--) { + diamond += makeSpaceLine(height - i - 1, 2 * i + 1) + '\n'; + } + return diamond; +} +console.log(makeDiamond(5)); \ No newline at end of file