From 8ad2edb6fdd248ff763bbabf5ca6b6370dcfa8ce Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Mon, 17 Jun 2024 20:15:39 -0500 Subject: [PATCH 01/32] 1 --- booleans-and-conditionals/exercises/part-1.js | 7 ++- .../studio/data-variables-conditionals.js | 48 ++++++++++++++++--- 2 files changed, 47 insertions(+), 8 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/studio/data-variables-conditionals.js b/booleans-and-conditionals/studio/data-variables-conditionals.js index 6a15e146f4..9f7b35e224 100644 --- a/booleans-and-conditionals/studio/data-variables-conditionals.js +++ b/booleans-and-conditionals/studio/data-variables-conditionals.js @@ -1,15 +1,49 @@ // 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 && // add logic below to verify all astronauts are ready - +astronautStatus === "ready" && // add logic below to verify the total mass does not exceed the maximum limit of 850000 - +totalMassKg < maximumMassLimit && // add logic below to verify the fuel temperature is within the appropriate range of -150 and -300 - +fuelTempCelsius >= -300 && fuelTempCelsius <= -150 && // add logic below to verify the fuel level is at 100% - +fuelLevel === "100%" && // add logic below to verify the weather status is clear - +weatherStatus === "clear") { // Verify shuttle launch can proceed based on above conditions +console.log("Date:", date); +console.log("Time:", time); +console.log("Astronaut Count:", astronautCount); +console.log("Crew Mass (kg):", crewMassKg); +console.log("Fuel Mass (kg):", fuelMassKg); +console.log("Shuttle Mass (kg):", shuttleMassKg); +console.log("Total Mass (kg):", totalMassKg); +console.log("Fuel Temperature (Celsius):", fuelTempCelsius + "°C"); +console.log("Fuel Temperature (Celsius): ${fuelTempCelsius} °C"); +console.log("Weather Status:", weatherStatus); + + + // Wish astronauts a safe flight! + console.log("Have a safe flight!"); + +} else { + // If conditions are not met, shutdown launch + console.log("Launch conditions are not met. ABORT LAUNCH!"); +} \ No newline at end of file From c35ee943e94d2ed17a7d25d4549d2a6790a471d1 Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Mon, 17 Jun 2024 21:32:13 -0500 Subject: [PATCH 02/32] update to cel line --- booleans-and-conditionals/studio/data-variables-conditionals.js | 1 - 1 file changed, 1 deletion(-) diff --git a/booleans-and-conditionals/studio/data-variables-conditionals.js b/booleans-and-conditionals/studio/data-variables-conditionals.js index 9f7b35e224..2fc6484b21 100644 --- a/booleans-and-conditionals/studio/data-variables-conditionals.js +++ b/booleans-and-conditionals/studio/data-variables-conditionals.js @@ -36,7 +36,6 @@ console.log("Fuel Mass (kg):", fuelMassKg); console.log("Shuttle Mass (kg):", shuttleMassKg); console.log("Total Mass (kg):", totalMassKg); console.log("Fuel Temperature (Celsius):", fuelTempCelsius + "°C"); -console.log("Fuel Temperature (Celsius): ${fuelTempCelsius} °C"); console.log("Weather Status:", weatherStatus); From 57aeae5ec094bef978d64bc68edec661f78a4ae3 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Mon, 17 Jun 2024 21:49:37 -0500 Subject: [PATCH 03/32] fixing assignment 1 --- .../exercises/data-and-variables-exercises.js | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/data-and-variables/exercises/data-and-variables-exercises.js b/data-and-variables/exercises/data-and-variables-exercises.js index 6433bcd641..6c57ce726b 100644 --- a/data-and-variables/exercises/data-and-variables-exercises.js +++ b/data-and-variables/exercises/data-and-variables-exercises.js @@ -1,11 +1,30 @@ // Declare and assign the variables below +let shuttleName = 'Determination'; +let shuttleSpeed = 17500; +let distanceToMars = 225000000 +let disntanceToMoon = 384400 +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 shuttleSpeed); +console.log(typeof distanceToMars); +console.log(typeof disntanceToMoon); +console.log(typeof milesPerKm); // Calculate a space mission below +let milesToMars = distanceToMars * milesPerKm; +let hoursToMars = milesToMars / shuttleSpeed; +let daysToMars = hoursToMars / 24; // Print the results of the space mission calculations below +console.log(shuttleName, "will take", daysToMars, "days to reach Mars."); // Calculate a trip to the moon below +let milesToMoon = disntanceToMoon * milesPerKm; +let hoursToMoon = milesToMoon / shuttleSpeed; +let daysToMoon = hoursToMoon / 24; -// Print the results of the trip to the moon below \ No newline at end of file +// 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 4a1523e46ff637ba9e44e838695ee0782bda3f83 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Mon, 17 Jun 2024 21:54:29 -0500 Subject: [PATCH 04/32] test 2 --- data-and-variables/exercises/data-and-variables-exercises.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data-and-variables/exercises/data-and-variables-exercises.js b/data-and-variables/exercises/data-and-variables-exercises.js index 6c57ce726b..f86387dc6e 100644 --- a/data-and-variables/exercises/data-and-variables-exercises.js +++ b/data-and-variables/exercises/data-and-variables-exercises.js @@ -27,4 +27,4 @@ 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 +console.log(shuttleName, "will take", daysToMoon, "days to reach the Moon."); \ No newline at end of file From d7d62dbbac8b04467249307063c4dd43636f1c9e Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Mon, 17 Jun 2024 21:55:38 -0500 Subject: [PATCH 05/32] test 3 from laptop --- .../exercises/data-and-variables-exercises.js | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/data-and-variables/exercises/data-and-variables-exercises.js b/data-and-variables/exercises/data-and-variables-exercises.js index 6433bcd641..f86387dc6e 100644 --- a/data-and-variables/exercises/data-and-variables-exercises.js +++ b/data-and-variables/exercises/data-and-variables-exercises.js @@ -1,11 +1,30 @@ // Declare and assign the variables below +let shuttleName = 'Determination'; +let shuttleSpeed = 17500; +let distanceToMars = 225000000 +let disntanceToMoon = 384400 +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 shuttleSpeed); +console.log(typeof distanceToMars); +console.log(typeof disntanceToMoon); +console.log(typeof milesPerKm); // Calculate a space mission below +let milesToMars = distanceToMars * milesPerKm; +let hoursToMars = milesToMars / shuttleSpeed; +let daysToMars = hoursToMars / 24; // Print the results of the space mission calculations below +console.log(shuttleName, "will take", daysToMars, "days to reach Mars."); // Calculate a trip to the moon below +let milesToMoon = disntanceToMoon * milesPerKm; +let hoursToMoon = milesToMoon / shuttleSpeed; +let daysToMoon = hoursToMoon / 24; -// Print the results of the trip to the moon below \ No newline at end of file +// 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 c9f9188d3d44e7b4f7c039e0792f8c6a1c82caec Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Mon, 17 Jun 2024 22:39:33 -0500 Subject: [PATCH 06/32] all part commit 1.0 --- booleans-and-conditionals/exercises/part-1.js | 2 +- booleans-and-conditionals/exercises/part-2.js | 22 ++++++++++++++++--- booleans-and-conditionals/exercises/part-3.js | 18 +++++++++++++-- 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/booleans-and-conditionals/exercises/part-1.js b/booleans-and-conditionals/exercises/part-1.js index f762a9521f..a8beefdb3a 100644 --- a/booleans-and-conditionals/exercises/part-1.js +++ b/booleans-and-conditionals/exercises/part-1.js @@ -5,7 +5,7 @@ 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: +// BEFORE running the code, predict what will be printed to the console by the following statements: engines are off will print if (engineIndicatorLight === "green") { console.log("engines have started"); diff --git a/booleans-and-conditionals/exercises/part-2.js b/booleans-and-conditionals/exercises/part-2.js index ff11fbab8a..dd6fb5bf05 100644 --- a/booleans-and-conditionals/exercises/part-2.js +++ b/booleans-and-conditionals/exercises/part-2.js @@ -8,13 +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) { + 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("Success! 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? diff --git a/booleans-and-conditionals/exercises/part-3.js b/booleans-and-conditionals/exercises/part-3.js index 9ed686d097..bf8938b695 100644 --- a/booleans-and-conditionals/exercises/part-3.js +++ b/booleans-and-conditionals/exercises/part-3.js @@ -1,6 +1,20 @@ let engineIndicatorLight = 'red blinking'; -let fuelLevel = 21000; -let engineTemperature = 1200; +let fuelLevel = 5000; +let engineTemperature = 2600; + +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...") +} /* 5) Implement the following checks using if/else if/else statements: From 95eb7275fd971e0d101339cc8cf9a14dac906a5c Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Mon, 17 Jun 2024 22:45:55 -0500 Subject: [PATCH 07/32] completed part 3 --- booleans-and-conditionals/exercises/part-3.js | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/booleans-and-conditionals/exercises/part-3.js b/booleans-and-conditionals/exercises/part-3.js index bf8938b695..a22e2f7aaf 100644 --- a/booleans-and-conditionals/exercises/part-3.js +++ b/booleans-and-conditionals/exercises/part-3.js @@ -1,19 +1,19 @@ -let engineIndicatorLight = 'red blinking'; -let fuelLevel = 5000; -let engineTemperature = 2600; - -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.") +let engineIndicatorLight = 'not red blinking'; +let fuelLevel = 21000; +let engineTemperature = 1200; + +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...") + console.log("Fuel and engine status pending..."); } /* 5) Implement the following checks using if/else if/else statements: From 509ebf919e3369334178e6ff4c489962ce7ea25b Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Mon, 17 Jun 2024 23:43:43 -0500 Subject: [PATCH 08/32] part 3 completed --- booleans-and-conditionals/exercises/part-3.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/booleans-and-conditionals/exercises/part-3.js b/booleans-and-conditionals/exercises/part-3.js index a22e2f7aaf..17619b32ce 100644 --- a/booleans-and-conditionals/exercises/part-3.js +++ b/booleans-and-conditionals/exercises/part-3.js @@ -1,5 +1,5 @@ let engineIndicatorLight = 'not red blinking'; -let fuelLevel = 21000; +let fuelLevel = 222500; let engineTemperature = 1200; if (fuelLevel < 1000 || engineTemperature > 3500 || engineIndicatorLight === "red blinking"){ @@ -16,6 +16,14 @@ if (fuelLevel < 1000 || engineTemperature > 3500 || engineIndicatorLight === "re console.log("Fuel and engine status pending..."); } +let commandOverride = false; + +if ((fuelLevel > 20000 && engineIndicatorLight !== "red blinking") || commandOverride) { + console.log("Cleared to launch!"); +} else ( + console.log("Launch scrubbed!") +) + /* 5) Implement the following checks using if/else if/else statements: a) If fuelLevel is above 20000 AND engineTemperature is at or below 2500, print "Full tank. Engines good." From 6ccb39f787dccb4487d0337d776d7e2b3edc24f7 Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Thu, 20 Jun 2024 17:05:41 -0500 Subject: [PATCH 09/32] part one and two stage > commit --- .../exercises/part-one.js | 10 ++++++++++ .../exercises/part-two.js | 19 ++++++++++++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/stringing-characters-together/exercises/part-one.js b/stringing-characters-together/exercises/part-one.js index 9295e4dd9f..a22fe74265 100644 --- a/stringing-characters-together/exercises/part-one.js +++ b/stringing-characters-together/exercises/part-one.js @@ -4,7 +4,17 @@ let num = 1001; console.log(num.length); //Use type conversion to print the length (number of digits) of an integer. +let numStr = num.toString(); +let numLength = numStr.length; +console.log(numLength); //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-two.js b/stringing-characters-together/exercises/part-two.js index a06e9094dc..05c60b0b15 100644 --- a/stringing-characters-together/exercises/part-two.js +++ b/stringing-characters-together/exercises/part-two.js @@ -3,18 +3,19 @@ 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 +23,23 @@ 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. +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". +if (dnaTwo.indexOf('CAT') !== -1) { + 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(dna.slice(16, 19)); //4) Use a template literal to print, "The DNA strand is ___ characters long." +console.log("The DNA strand is " + String(dna).length + " characters long." ) //5) Just for fun, apply methods to ``dna`` and use another template literal to print, 'taco cat'. + +console.log(`${dna.slice(6,9).toLowerCase()}, ${dnaTwo.indexOf('AGG')}`); From 9406456a92d092a57abb7733741a09f0ef115260 Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Thu, 20 Jun 2024 17:49:21 -0500 Subject: [PATCH 10/32] part 3 --- stringing-characters-together/exercises/part-three.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/stringing-characters-together/exercises/part-three.js b/stringing-characters-together/exercises/part-three.js index 8c310f1445..ad1fca074c 100644 --- a/stringing-characters-together/exercises/part-three.js +++ b/stringing-characters-together/exercises/part-three.js @@ -3,15 +3,20 @@ 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'." +//3. Use bracket notation and a template literal to print, "The abbreviation for 'aScript' is 'JS'." +console.log('The abbrevation for "JavaScript" is ' + (language.charAt(0)+ language.charAt(4)) + "."); //4. Just for fun, try chaining 3 or more methods together, and then print the result. +console.log('Did you know that ' + language + ' is a programming language? ' + language + " has " + language.length + ' letters in its name!'); //Part Three section Two //1. Use the string methods you know to print 'Title Case' from the string 'title case'. let notTitleCase = 'title case'; +console.log(notTitleCase.replace(/title/, "Title").replace(/case/, "Case")); \ No newline at end of file From 3b34309f4dcec2ffb7d3f9b39ec014b23f5bec8f Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Thu, 20 Jun 2024 23:05:33 -0500 Subject: [PATCH 11/32] 1 --- .../array-string-conversion/array-testing.js | 15 +++++++++++---- arrays/studio/string-modification.js | 15 ++++++++++++++- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/arrays/studio/array-string-conversion/array-testing.js b/arrays/studio/array-string-conversion/array-testing.js index c4d5899385..1d2952ec1f 100644 --- a/arrays/studio/array-string-conversion/array-testing.js +++ b/arrays/studio/array-string-conversion/array-testing.js @@ -8,20 +8,25 @@ strings = [protoArray1, protoArray2, protoArray3, protoArray4]; //2) function reverseCommas() { //TODO: 1. create and instantiate your variables. - let check; + let check = strings[0].includes(','); let output; //TODO: 2. write the code required for this step - + if (check) { + output = strings[0].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; -} +}; +console.log(reverseCommas()); + //3) function semiDash() { - let check; + let check = protoArray1; let output; //TODO: write the code required for this step + return output; } @@ -44,6 +49,8 @@ function commaSpace() { return output; } +console.log(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/string-modification.js b/arrays/studio/string-modification.js index 45991b15fc..93acd13e18 100644 --- a/arrays/studio/string-modification.js +++ b/arrays/studio/string-modification.js @@ -1,11 +1,24 @@ const input = require('readline-sync'); -let str = "LaunchCode"; +let str = input.question("Enter a word: "); //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. +//REMOVED FOR STEP 3: let newStr = str.slice(3) + str.slice(0,3); +let newStr = str //Use a template literal to print the original and modified string in a descriptive phrase. +//REMOVED FOR STEP 3: console.log(`Original STR is ${str} and new STR is ${newStr}.`) //2) Modify your code to accept user input. Query the user to enter the number of letters that will be relocated. +let numLetters = input.question('Enter the number of letters that will be relocated: '); +numLetters = parseInt(numLetters); //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) { + numLetters = 3; + console.log("Error Input. Input not accepted. Defaulting to 3."); +} + +let modifiedStr = str.slice(numLetters) + str.slice(0, numLetters); +console.log(`Original: ${str}, Modified: ${modifiedStr}`); \ No newline at end of file From e45f6d244d8e48da6c9cc7c098c8a9c3f8adf85f Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Thu, 20 Jun 2024 23:08:05 -0500 Subject: [PATCH 12/32] 1 --- arrays/exercises/part-one-arrays.js | 8 ++++++++ arrays/exercises/part-two-arrays.js | 10 ++++++++++ .../code-snippets/method-chaining.js | 2 +- 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/arrays/exercises/part-one-arrays.js b/arrays/exercises/part-one-arrays.js index 92f4e45170..aa2bcbb7f2 100644 --- a/arrays/exercises/part-one-arrays.js +++ b/arrays/exercises/part-one-arrays.js @@ -1,5 +1,13 @@ //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-two-arrays.js b/arrays/exercises/part-two-arrays.js index a940b1d0ff..88c7f677b8 100644 --- a/arrays/exercises/part-two-arrays.js +++ b/arrays/exercises/part-two-arrays.js @@ -1,11 +1,21 @@ 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(); +console.log(cargoHold); //3) Remove the first item from the array with shift. Print the element removed and the updated array. +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(`These items are in the cargo hold: ${cargoHold}. The length of that is ${cargoHold.length} total.`); \ No newline at end of file diff --git a/stringing-characters-together/code-snippets/method-chaining.js b/stringing-characters-together/code-snippets/method-chaining.js index 43fcd55bc7..2a63b599d6 100644 --- a/stringing-characters-together/code-snippets/method-chaining.js +++ b/stringing-characters-together/code-snippets/method-chaining.js @@ -2,7 +2,7 @@ let word = 'JavaScript'; -console.log(word.toUpperCase()); +console.log(word.slice(5).toUpperCase()); //Returns ``JAVASCRIPT`` //What does ``word.slice(4).toUpperCase()`` return? From 3030c59d8508744791f253b248434f8de91013dd Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Thu, 20 Jun 2024 23:10:06 -0500 Subject: [PATCH 13/32] 2 --- arrays/studio/string-modification.js | 1 + 1 file changed, 1 insertion(+) diff --git a/arrays/studio/string-modification.js b/arrays/studio/string-modification.js index 93acd13e18..ddd0263423 100644 --- a/arrays/studio/string-modification.js +++ b/arrays/studio/string-modification.js @@ -20,5 +20,6 @@ if ( numLetters > str.length) { console.log("Error Input. Input not accepted. Defaulting to 3."); } + let modifiedStr = str.slice(numLetters) + str.slice(0, numLetters); console.log(`Original: ${str}, Modified: ${modifiedStr}`); \ No newline at end of file From 73d664a173ec0b46f82fa357d41c8a5b1eedaeeb Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Mon, 24 Jun 2024 17:37:46 -0500 Subject: [PATCH 14/32] loops sync --- loops/chapter-examples/Loop-Variable.js | 12 +- loops/chapter-examples/Reversing-a-String.js | 10 +- .../for-Loop-Practice-With-Arrays.js | 9 + .../for-Loop-Practice-With-Strings.js | 7 +- loops/chapter-examples/package-lock.json | 6 + loops/exercises/for-Loop-Exercises.js | 44 +- .../exercises/node_modules/.package-lock.json | 23 + .../node_modules/read-line/.npmignore | 1 + .../node_modules/read-line/.travis.yml | 6 + .../node_modules/read-line/LICENSE-MIT | 22 + .../node_modules/read-line/README.md | 25 + .../node_modules/read-line/lib/read-line.js | 30 + .../node_modules/read-line/package.json | 35 + .../read-line/test/read-line_test.js | 13 + .../node_modules/read-line/test/test-file.txt | 3 + .../node_modules/readline-sync/LICENSE | 21 + .../readline-sync/README-Deprecated.md | 89 + .../node_modules/readline-sync/README.md | 1836 +++++++++++++++++ .../node_modules/readline-sync/lib/encrypt.js | 24 + .../node_modules/readline-sync/lib/read.cs.js | 123 ++ .../node_modules/readline-sync/lib/read.ps1 | 128 ++ .../node_modules/readline-sync/lib/read.sh | 137 ++ .../readline-sync/lib/readline-sync.js | 1329 ++++++++++++ .../node_modules/readline-sync/package.json | 40 + loops/exercises/package-lock.json | 29 + loops/exercises/package.json | 6 + loops/exercises/while-Loop-Exercises.js | 31 +- 27 files changed, 4022 insertions(+), 17 deletions(-) create mode 100644 loops/chapter-examples/package-lock.json create mode 100644 loops/exercises/node_modules/.package-lock.json create mode 100644 loops/exercises/node_modules/read-line/.npmignore create mode 100644 loops/exercises/node_modules/read-line/.travis.yml create mode 100644 loops/exercises/node_modules/read-line/LICENSE-MIT create mode 100644 loops/exercises/node_modules/read-line/README.md create mode 100644 loops/exercises/node_modules/read-line/lib/read-line.js create mode 100644 loops/exercises/node_modules/read-line/package.json create mode 100644 loops/exercises/node_modules/read-line/test/read-line_test.js create mode 100644 loops/exercises/node_modules/read-line/test/test-file.txt create mode 100644 loops/exercises/node_modules/readline-sync/LICENSE create mode 100644 loops/exercises/node_modules/readline-sync/README-Deprecated.md create mode 100644 loops/exercises/node_modules/readline-sync/README.md create mode 100644 loops/exercises/node_modules/readline-sync/lib/encrypt.js create mode 100644 loops/exercises/node_modules/readline-sync/lib/read.cs.js create mode 100644 loops/exercises/node_modules/readline-sync/lib/read.ps1 create mode 100644 loops/exercises/node_modules/readline-sync/lib/read.sh create mode 100644 loops/exercises/node_modules/readline-sync/lib/readline-sync.js create mode 100644 loops/exercises/node_modules/readline-sync/package.json create mode 100644 loops/exercises/package-lock.json create mode 100644 loops/exercises/package.json diff --git a/loops/chapter-examples/Loop-Variable.js b/loops/chapter-examples/Loop-Variable.js index 3b00ba56c4..75df7a8d7e 100644 --- a/loops/chapter-examples/Loop-Variable.js +++ b/loops/chapter-examples/Loop-Variable.js @@ -1,5 +1,11 @@ // Experiment with this loop by modifying each of the following: the variable initialization, the boolean condition, and the update expression. -for (let i = 0; i < 51; i++) { - console.log(i); - } \ No newline at end of file +//for (let i = 5; i < 42; i++) { + // console.log(i); + //} + + let phrase = "Chili Cook-off"; + +for (let i = 0; i < phrase.length - 1; i = i + 3) { + console.log(phrase[i]); +} \ No newline at end of file diff --git a/loops/chapter-examples/Reversing-a-String.js b/loops/chapter-examples/Reversing-a-String.js index 9044c0293f..726a4aa439 100644 --- a/loops/chapter-examples/Reversing-a-String.js +++ b/loops/chapter-examples/Reversing-a-String.js @@ -1,8 +1,14 @@ -let str = "blue"; +let str = "Purple"; let reversed = ""; for (let i = 0; i < str.length; i++) { reversed = str[i] + reversed; } -console.log(reversed); \ No newline at end of file +console.log(reversed); + +let phrase = "Chili Cook-off"; + +for (let i = 0; i < phrase.length - 1; i = i + 3) { + console.log(phrase[i]); +} \ No newline at end of file diff --git a/loops/chapter-examples/for-Loop-Practice-With-Arrays.js b/loops/chapter-examples/for-Loop-Practice-With-Arrays.js index c463f79138..02bb794350 100644 --- a/loops/chapter-examples/for-Loop-Practice-With-Arrays.js +++ b/loops/chapter-examples/for-Loop-Practice-With-Arrays.js @@ -1,3 +1,12 @@ // create an array variable containing the names +let family = ["Amber", "Tracey", "Tom", "Gerald"]; // write a for loop that prints each name on a different line + +for (let i = 0; i < family.length; i++) { + console.log(family[i]); + } + + for (let i = 0; i > -1; i++) { + console.log("LaunchCode"); + } \ No newline at end of file diff --git a/loops/chapter-examples/for-Loop-Practice-With-Strings.js b/loops/chapter-examples/for-Loop-Practice-With-Strings.js index fc5d5885cc..f675abe5e2 100644 --- a/loops/chapter-examples/for-Loop-Practice-With-Strings.js +++ b/loops/chapter-examples/for-Loop-Practice-With-Strings.js @@ -1,4 +1,9 @@ // Create a string variable containing your name. +let name = "Gavin"; -// Write a for loop that prints each character in your name on a different line. \ No newline at end of file +// Write a for loop that prints each character in your name on a different line. + +for (let i = 0; i < name.length; i++) { + console.log(name[i]); +} diff --git a/loops/chapter-examples/package-lock.json b/loops/chapter-examples/package-lock.json new file mode 100644 index 0000000000..b743c70e60 --- /dev/null +++ b/loops/chapter-examples/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "chapter-examples", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} diff --git a/loops/exercises/for-Loop-Exercises.js b/loops/exercises/for-Loop-Exercises.js index c659c50852..a90b48cad9 100644 --- a/loops/exercises/for-Loop-Exercises.js +++ b/loops/exercises/for-Loop-Exercises.js @@ -4,21 +4,59 @@ 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). */ + for (let i = 0; i < 21; i++){ + console.log([i]); + } + for (let i = 3; i < 29; i = i + 2){ + console.log([i]); + } + for (let i = 12; i > -15 ; i = i - 2){ + console.log([i]); + } + + for (let i = 50; i > 19 ; i = i - 3){ + console.log([i]); +} /*Exercise #2: Initialize two variables to hold the string “LaunchCode” and the array [1, 5, ‘LC101’, ‘blue’, 42]. - 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 name = "LaunchCode"; +let reversed = ""; +let array = [1, 5, 'LC101', 'blue', 42]; +for (let i = 0; i < array.length; i++) { + console.log(array[i]); +} - +for (let i = 0; i < name.length; i++) { + reversed = name[i] + reversed; +} +console.log(reversed); /*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 arr = [2, 3, 13, 18, -5, 38, -10, 11, 0 , 104]; + let evenArray = []; + let oddArray = []; + + for (let i = 0; i < arr.length; i++) { + if (arr[i] % 2 === 0) { + evenArray.push(arr[i]); + } else { + oddArray.push(arr[i]); + } + } + + console.log(`Even numbers: ${evenArray}`); + console.log(`Odd numbers ${oddArray}`); + + \ No newline at end of file diff --git a/loops/exercises/node_modules/.package-lock.json b/loops/exercises/node_modules/.package-lock.json new file mode 100644 index 0000000000..ff29e1ca8d --- /dev/null +++ b/loops/exercises/node_modules/.package-lock.json @@ -0,0 +1,23 @@ +{ + "name": "exercises", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/read-line": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/read-line/-/read-line-0.1.2.tgz", + "integrity": "sha512-nvCGsua+3EIxge4GSGHgF4e8VAtLqic9aQZWe7sra2Xk3p6xmzO2oruoJYleIZMLklDV1PGQ1wztUMaNeM9kVw==", + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/readline-sync": { + "version": "1.4.10", + "resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.10.tgz", + "integrity": "sha512-gNva8/6UAe8QYepIQH/jQ2qn91Qj0B9sYjMBBs3QOB8F2CXcKgLxQaJRP76sWVRQt+QU+8fAkCbCvjjMFu7Ycw==", + "engines": { + "node": ">= 0.8.0" + } + } + } +} diff --git a/loops/exercises/node_modules/read-line/.npmignore b/loops/exercises/node_modules/read-line/.npmignore new file mode 100644 index 0000000000..3c3629e647 --- /dev/null +++ b/loops/exercises/node_modules/read-line/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/loops/exercises/node_modules/read-line/.travis.yml b/loops/exercises/node_modules/read-line/.travis.yml new file mode 100644 index 0000000000..42d430290d --- /dev/null +++ b/loops/exercises/node_modules/read-line/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - 0.8 + - '0.10' +before_script: + - npm install -g grunt-cli diff --git a/loops/exercises/node_modules/read-line/LICENSE-MIT b/loops/exercises/node_modules/read-line/LICENSE-MIT new file mode 100644 index 0000000000..13ad4a3d97 --- /dev/null +++ b/loops/exercises/node_modules/read-line/LICENSE-MIT @@ -0,0 +1,22 @@ +Copyright (c) 2015 Sterling Jordan Calder + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/loops/exercises/node_modules/read-line/README.md b/loops/exercises/node_modules/read-line/README.md new file mode 100644 index 0000000000..b4aa5afcfb --- /dev/null +++ b/loops/exercises/node_modules/read-line/README.md @@ -0,0 +1,25 @@ +# read-line [![Build Status](https://secure.travis-ci.org/jordancalder/read-line.png?branch=master)](http://travis-ci.org/jordancalder/read-line) + +An implementation of readline for Nodejs + +## Getting Started +Install the module with: `npm install read-line` + +```javascript +var read_line = require('read-line') +var fs = require('fs') + +var input = fs.createReadStream(__dirname + '/test-file.txt') +input.pipe(read_line) +read_line.on('readable', function () { + var line + while (line = read_line.read()) { + console.log(line) + } +}) + +``` + +## License +Copyright (c) 2015 Sterling Jordan Calder +Licensed under the MIT license. diff --git a/loops/exercises/node_modules/read-line/lib/read-line.js b/loops/exercises/node_modules/read-line/lib/read-line.js new file mode 100644 index 0000000000..3791df53d7 --- /dev/null +++ b/loops/exercises/node_modules/read-line/lib/read-line.js @@ -0,0 +1,30 @@ +/* + * read-line + * https://github.com/jordancalder/read-line + * + * Copyright (c) 2015 Sterling Jordan Calder + * Licensed under the MIT license. + */ + +'use strict' + +var read_line = require('stream').Transform( { objectMode : true } ) + +read_line._transform = function (chunk, encoding, callback) { + var data = chunk.toString() + if (this._last) data = this._last + data + + var lines = data.split('\n') + this._last = lines.splice(lines.length-1,1)[0] + + lines.forEach(this.push.bind(this)) + callback() +} + +read_line._flush = function (callback) { + if (this._last) this.push(this._last) + this._last = null + callback() +} + +module.exports = read_line \ No newline at end of file diff --git a/loops/exercises/node_modules/read-line/package.json b/loops/exercises/node_modules/read-line/package.json new file mode 100644 index 0000000000..75f9e099d5 --- /dev/null +++ b/loops/exercises/node_modules/read-line/package.json @@ -0,0 +1,35 @@ +{ + "name": "read-line", + "description": "An implementation of readline for Nodejs", + "version": "0.1.2", + "homepage": "https://github.com/jordancalder/read-line", + "author": { + "name": "Sterling Jordan Calder", + "email": "jordancalder@gmail.com", + "url": "http://jordancalder.com/" + }, + "repository": { + "type": "git", + "url": "git://github.com/jordancalder/read-line.git" + }, + "bugs": { + "url": "https://github.com/jordancalder/read-line/issues" + }, + "licenses": [ + { + "type": "MIT", + "url": "https://github.com/jordancalder/read-line/blob/master/LICENSE-MIT" + } + ], + "main": "lib/read-line", + "engines": { + "node": ">= 0.10.0" + }, + "keywords": [ + "readline", + "line", + "read", + "file", + "line-by-line" + ] +} \ No newline at end of file diff --git a/loops/exercises/node_modules/read-line/test/read-line_test.js b/loops/exercises/node_modules/read-line/test/read-line_test.js new file mode 100644 index 0000000000..677b5e4be2 --- /dev/null +++ b/loops/exercises/node_modules/read-line/test/read-line_test.js @@ -0,0 +1,13 @@ +'use strict'; + +var read_line = require('../lib/read-line.js') + +var fs = require('fs') +var input = fs.createReadStream(__dirname + '/test-file.txt') +input.pipe(read_line) +read_line.on('readable', function () { + var line + while (line = read_line.read()) { + console.log(line) + } +}) \ No newline at end of file diff --git a/loops/exercises/node_modules/read-line/test/test-file.txt b/loops/exercises/node_modules/read-line/test/test-file.txt new file mode 100644 index 0000000000..5bdf93e6c3 --- /dev/null +++ b/loops/exercises/node_modules/read-line/test/test-file.txt @@ -0,0 +1,3 @@ +this is a test +will it work? +who knows? \ No newline at end of file diff --git a/loops/exercises/node_modules/readline-sync/LICENSE b/loops/exercises/node_modules/readline-sync/LICENSE new file mode 100644 index 0000000000..0d289d9968 --- /dev/null +++ b/loops/exercises/node_modules/readline-sync/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 anseki + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/loops/exercises/node_modules/readline-sync/README-Deprecated.md b/loops/exercises/node_modules/readline-sync/README-Deprecated.md new file mode 100644 index 0000000000..25128a5c2a --- /dev/null +++ b/loops/exercises/node_modules/readline-sync/README-Deprecated.md @@ -0,0 +1,89 @@ +# readlineSync + +## Deprecated Methods and Options + +The readlineSync current version is fully compatible with older version. +The following methods and options are deprecated. + +### `setPrint` method + +Use the [`print`](README.md#basic_options-print) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({print: value}); +``` + +instead of: + +```js +readlineSync.setPrint(value); +``` + +### `setPrompt` method + +Use the [`prompt`](README.md#basic_options-prompt) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({prompt: value}); +``` + +instead of: + +```js +readlineSync.setPrompt(value); +``` + +### `setEncoding` method + +Use the [`encoding`](README.md#basic_options-encoding) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({encoding: value}); +``` + +instead of: + +```js +readlineSync.setEncoding(value); +``` + +### `setMask` method + +Use the [`mask`](README.md#basic_options-mask) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({mask: value}); +``` + +instead of: + +```js +readlineSync.setMask(value); +``` + +### `setBufferSize` method + +Use the [`bufferSize`](README.md#basic_options-buffersize) option. +For the [Default Options](README.md#basic_options), use: + +```js +readlineSync.setDefaultOptions({bufferSize: value}); +``` + +instead of: + +```js +readlineSync.setBufferSize(value); +``` + +### `noEchoBack` option + +Use [`hideEchoBack`](README.md#basic_options-hideechoback) option instead of it. + +### `noTrim` option + +Use [`keepWhitespace`](README.md#basic_options-keepwhitespace) option instead of it. diff --git a/loops/exercises/node_modules/readline-sync/README.md b/loops/exercises/node_modules/readline-sync/README.md new file mode 100644 index 0000000000..4549a5199b --- /dev/null +++ b/loops/exercises/node_modules/readline-sync/README.md @@ -0,0 +1,1836 @@ +# readlineSync + +[![npm](https://img.shields.io/npm/v/readline-sync.svg)](https://www.npmjs.com/package/readline-sync) [![GitHub issues](https://img.shields.io/github/issues/anseki/readline-sync.svg)](https://github.com/anseki/readline-sync/issues) [![dependencies](https://img.shields.io/badge/dependencies-No%20dependency-brightgreen.svg)](package.json) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE-MIT) + +Synchronous [Readline](http://nodejs.org/api/readline.html) for interactively running to have a conversation with the user via a console(TTY). + +readlineSync tries to let your script have a conversation with the user via a console, even when the input/output stream is redirected like `your-script bar.log`. + + + +
Basic OptionsUtility MethodsPlaceholders
+ +* Simple case: + +```js +var readlineSync = require('readline-sync'); + +// Wait for user's response. +var userName = readlineSync.question('May I have your name? '); +console.log('Hi ' + userName + '!'); + +// Handle the secret text (e.g. password). +var favFood = readlineSync.question('What is your favorite food? ', { + hideEchoBack: true // The typed text on screen is hidden by `*` (default). +}); +console.log('Oh, ' + userName + ' loves ' + favFood + '!'); +``` + +```console +May I have your name? CookieMonster +Hi CookieMonster! +What is your favorite food? **** +Oh, CookieMonster loves tofu! +``` + +* Get the user's response by a single key without the Enter key: + +```js +var readlineSync = require('readline-sync'); +if (readlineSync.keyInYN('Do you want this module?')) { + // 'Y' key was pressed. + console.log('Installing now...'); + // Do something... +} else { + // Another key was pressed. + console.log('Searching another...'); + // Do something... +} +``` + +* Let the user choose an item from a list: + +```js +var readlineSync = require('readline-sync'), + animals = ['Lion', 'Elephant', 'Crocodile', 'Giraffe', 'Hippo'], + index = readlineSync.keyInSelect(animals, 'Which animal?'); +console.log('Ok, ' + animals[index] + ' goes to your room.'); +``` + +```console +[1] Lion +[2] Elephant +[3] Crocodile +[4] Giraffe +[5] Hippo +[0] CANCEL + +Which animal? [1...5 / 0]: 2 +Ok, Elephant goes to your room. +``` + +* An UI like the Range Slider: +(Press `Z` or `X` key to change a value, and Space Bar to exit) + +```js +var readlineSync = require('readline-sync'), + MAX = 60, MIN = 0, value = 30, key; +console.log('\n\n' + (new Array(20)).join(' ') + + '[Z] <- -> [X] FIX: [SPACE]\n'); +while (true) { + console.log('\x1B[1A\x1B[K|' + + (new Array(value + 1)).join('-') + 'O' + + (new Array(MAX - value + 1)).join('-') + '| ' + value); + key = readlineSync.keyIn('', + {hideEchoBack: true, mask: '', limit: 'zx '}); + if (key === 'z') { if (value > MIN) { value--; } } + else if (key === 'x') { if (value < MAX) { value++; } } + else { break; } +} +console.log('\nA value the user requested: ' + value); +``` + +![sample](screen_03.gif) + +* Handle the commands repeatedly, such as the shell interface: + +```js +readlineSync.promptCLLoop({ + add: function(target, into) { + console.log(target + ' is added into ' + into + '.'); + // Do something... + }, + remove: function(target) { + console.log(target + ' is removed.'); + // Do something... + }, + bye: function() { return true; } +}); +console.log('Exited'); +``` + +```console +> add pic01.png archive +pic01.png is added into archive. +> delete pic01.png +Requested command is not available. +> remove pic01.png +pic01.png is removed. +> bye +Exited +``` + +## Installation + +```console +npm install readline-sync +``` + +## Quick Start + +**How does the user input?** + +- [Type a reply to a question, and press the Enter key](#quick_start-a) (A) +- [Type a keyword like a command in prompt, and press the Enter key](#quick_start-b) (B) +- [Press a single key without the Enter key](#quick_start-c) (C) + +**(A) What does the user input?** + +- [E-mail address](#utility_methods-questionemail) +- [New password](#utility_methods-questionnewpassword) +- [Integer number](#utility_methods-questionint) +- [Floating-point number](#utility_methods-questionfloat) +- [Local file/directory path](#utility_methods-questionpath) +- [Others](#basic_methods-question) + +**(B) What does your script do?** + +- [Receive a parsed command-name and arguments](#utility_methods-promptcl) +- [Receive an input repeatedly](#utility_methods-promptloop) +- [Receive a parsed command-name and arguments repeatedly](#utility_methods-promptclloop) +- [Receive an input with prompt that is similar to that of the user's shell](#utility_methods-promptsimshell) +- [Others](#basic_methods-prompt) + +**(C) What does the user do?** + +- [Say "Yes" or "No"](#utility_methods-keyinyn) +- [Say "Yes" or "No" explicitly](#utility_methods-keyinynstrict) +- [Make the running of script continue when ready](#utility_methods-keyinpause) +- [Choose an item from a list](#utility_methods-keyinselect) +- [Others](#basic_methods-keyin) + +## Basic Methods + +These are used to control details of the behavior. It is recommended to use the [Utility Methods](#utility_methods) instead of Basic Methods if it satisfy your request. + +### `question` + +```js +answer = readlineSync.question([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then return the input from the user after it has been typed and the Enter key was pressed. +You can specify an `options` (see [Basic Options](#basic_options)) to control the behavior (e.g. refusing unexpected input, avoiding trimming white spaces, etc.). **If you let the user input the secret text (e.g. password), you should consider [`hideEchoBack`](#basic_options-hideechoback) option.** + +The `query` may be string, or may not be (e.g. number, Date, Object, etc.). It is converted to string (i.e. `toString` method is called) before it is displayed. (see [Note](#note) also) +It can include the [placeholders](#placeholders). + +For example: + +```js +program = readlineSync.question('Which program starts do you want? ', { + defaultInput: 'firefox' +}); +``` + +### `prompt` + +```js +input = readlineSync.prompt([options]) +``` + +Display a prompt-sign (see [`prompt`](#basic_options-prompt) option) to the user, and then return the input from the user after it has been typed and the Enter key was pressed. +You can specify an `options` (see [Basic Options](#basic_options)) to control the behavior (e.g. refusing unexpected input, avoiding trimming white spaces, etc.). + +For example: + +```js +while (true) { + command = readlineSync.prompt(); + // Do something... +} +``` + +### `keyIn` + +```js +pressedKey = readlineSync.keyIn([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then return a character as a key immediately it was pressed by the user, **without pressing the Enter key**. Note that the user has no chance to change the input. +You can specify an `options` (see [Basic Options](#basic_options)) to control the behavior (e.g. ignoring keys except some keys, checking target key, etc.). + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. + +For example: + +```js +menuId = readlineSync.keyIn('Hit 1...5 key: ', {limit: '$<1-5>'}); +``` + +### `setDefaultOptions` + +```js +currentDefaultOptions = readlineSync.setDefaultOptions([newDefaultOptions]) +``` + +Change the [Default Options](#basic_options) to the values of properties of `newDefaultOptions` Object. +All it takes is to specify options that you want change, because unspecified options are not updated. + +## Basic Options + +[`prompt`](#basic_options-prompt), [`hideEchoBack`](#basic_options-hideechoback), [`mask`](#basic_options-mask), [`limit`](#basic_options-limit), [`limitMessage`](#basic_options-limitmessage), [`defaultInput`](#basic_options-defaultinput), [`trueValue`, `falseValue`](#basic_options-truevalue_falsevalue), [`caseSensitive`](#basic_options-casesensitive), [`keepWhitespace`](#basic_options-keepwhitespace), [`encoding`](#basic_options-encoding), [`bufferSize`](#basic_options-buffersize), [`print`](#basic_options-print), [`history`](#basic_options-history), [`cd`](#basic_options-cd) + +An `options` Object can be specified to the methods to control the behavior of readlineSync. The options that were not specified to the methods are got from the Default Options. You can change the Default Options by [`setDefaultOptions`](#basic_methods-setdefaultoptions) method anytime, and it is kept until a current process is exited. +Specify the options that are often used to the Default Options, and specify temporary options to the methods. + +For example: + +```js +readlineSync.setDefaultOptions({limit: ['green', 'yellow', 'red']}); +a1 = readlineSync.question('Which color of signal? '); // Input is limited to 3 things. +a2 = readlineSync.question('Which color of signal? '); // It's limited yet. +a3 = readlineSync.question('What is your favorite color? ', {limit: null}); // It's unlimited temporarily. +a4 = readlineSync.question('Which color of signal? '); // It's limited again. +readlineSync.setDefaultOptions({limit: ['beef', 'chicken']}); +a5 = readlineSync.question('Beef or Chicken? '); // Input is limited to new 2 things. +a6 = readlineSync.question('And you? '); // It's limited to 2 things yet. +``` + +The Object as `options` can have following properties. + +### `prompt` + +_For `prompt*` methods only_ +*Type:* string or others +*Default:* `'> '` + +Set the prompt-sign that is displayed to the user by `prompt*` methods. For example you see `> ` that is Node.js's prompt-sign when you run `node` on the command line. +This may be string, or may not be (e.g. number, Date, Object, etc.). It is converted to string every time (i.e. `toString` method is called) before it is displayed. (see [Note](#note) also) +It can include the [placeholders](#placeholders). + +For example: + +```js +readlineSync.setDefaultOptions({prompt: '$ '}); +``` + +```js +// Display the memory usage always. +readlineSync.setDefaultOptions({ + prompt: { // Simple Object that has toString method. + toString: function() { + var rss = process.memoryUsage().rss; + return '[' + (rss > 1024 ? Math.round(rss / 1024) + 'k' : rss) + 'b]$ '; + } + } +}); +``` + +```console +[13148kb]$ foo +[13160kb]$ bar +[13200kb]$ +``` + +### `hideEchoBack` + +*Type:* boolean +*Default:* `false` + +If `true` is specified, hide the secret text (e.g. password) which is typed by user on screen by the mask characters (see [`mask`](#basic_options-mask) option). + +For example: + +```js +password = readlineSync.question('PASSWORD: ', {hideEchoBack: true}); +console.log('Login ...'); +``` + +```console +PASSWORD: ******** +Login ... +``` + +### `mask` + +*Type:* string +*Default:* `'*'` + +Set the mask characters that are shown instead of the secret text (e.g. password) when `true` is specified to [`hideEchoBack`](#basic_options-hideechoback) option. If you want to show nothing, specify `''`. (But it might be not user friendly in some cases.) +**Note:** In some cases (e.g. when the input stream is redirected on Windows XP), `'*'` or `''` might be used whether other one is specified. + +For example: + +```js +secret = readlineSync.question('Please whisper sweet words: ', { + hideEchoBack: true, + mask: require('chalk').magenta('\u2665') +}); +``` + +![sample](screen_02.gif) + +### `limit` + +Limit the user's input. +The usage differ depending on the method. + +#### For `question*` and `prompt*` methods + +*Type:* string, number, RegExp, function or Array +*Default:* `[]` + +Accept only the input that matches value that is specified to this. If the user input others, display a string that is specified to [`limitMessage`](#basic_options-limitmessage) option, and wait for reinput. + +* The string is compared with the input. It is affected by [`caseSensitive`](#basic_options-casesensitive) option. +* The number is compared with the input that is converted to number by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`. And it interprets `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`. +* The RegExp tests the input. +* The function that returns a boolean to indicate whether it matches is called with the input. + +One of above or an Array that includes multiple things (or Array includes Array) can be specified. + +For example: + +```js +command = readlineSync.prompt({limit: ['add', 'remove', /^clear( all)?$/]}); +// ** But `promptCL` method should be used instead of this. ** +``` + +```js +file = readlineSync.question('Text File: ', {limit: /\.txt$/i}); +// ** But `questionPath` method should be used instead of this. ** +``` + +```js +ip = readlineSync.question('IP Address: ', {limit: function(input) { + return require('net').isIP(input); // Valid IP Address +}}); +``` + +```js +availableActions = []; +if (!blockExists()) { availableActions.push('jump'); } +if (isLarge(place)) { availableActions.push('run'); } +if (isNew(shoes)) { availableActions.push('kick'); } +if (isNearby(enemy)) { availableActions.push('punch'); } +action = readlineSync.prompt({limit: availableActions}); +// ** But `promptCL` method should be used instead of this. ** +``` + +#### For `keyIn*` method + +*Type:* string, number or Array +*Default:* `[]` + +Accept only the key that matches value that is specified to this, ignore others. +Specify the characters as the key. All strings or Array of those are decomposed into single characters. For example, `'abcde'` or `['a', 'bc', ['d', 'e']]` are the same as `['a', 'b', 'c', 'd', 'e']`. +These strings are compared with the input. It is affected by [`caseSensitive`](#basic_options-casesensitive) option. + +The [placeholders](#placeholders) like `'$'` are replaced to an Array that is the character list like `['a', 'b', 'c', 'd', 'e']`. + +For example: + +```js +direction = readlineSync.keyIn('Left or Right? ', {limit: 'lr'}); // 'l' or 'r' +``` + +```js +dice = readlineSync.keyIn('Roll the dice, What will the result be? ', + {limit: '$<1-6>'}); // range of '1' to '6' +``` + +### `limitMessage` + +_For `question*` and `prompt*` methods only_ +*Type:* string +*Default:* `'Input another, please.$<( [)limit(])>'` + +Display this to the user when the [`limit`](#basic_options-limit) option is specified and the user input others. +The [placeholders](#placeholders) can be included. + +For example: + +```js +file = readlineSync.question('Name of Text File: ', { + limit: /\.txt$/i, + limitMessage: 'Sorry, $ is not text file.' +}); +``` + +### `defaultInput` + +_For `question*` and `prompt*` methods only_ +*Type:* string +*Default:* `''` + +If the user input empty text (i.e. pressed the Enter key only), return this. + +For example: + +```js +lang = readlineSync.question('Which language? ', {defaultInput: 'javascript'}); +``` + +### `trueValue`, `falseValue` + +*Type:* string, number, RegExp, function or Array +*Default:* `[]` + +If the input matches `trueValue`, return `true`. If the input matches `falseValue`, return `false`. In any other case, return the input. + +* The string is compared with the input. It is affected by [`caseSensitive`](#basic_options-casesensitive) option. +* The number is compared with the input that is converted to number by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`. And it interprets `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`. Note that in `keyIn*` method, the input is every time one character (i.e. the number that is specified must be an integer within the range of `0` to `9`). +* The RegExp tests the input. +* The function that returns a boolean to indicate whether it matches is called with the input. + +One of above or an Array that includes multiple things (or Array includes Array) can be specified. + +For example: + +```js +answer = readlineSync.question('How do you like it? ', { + trueValue: ['yes', 'yeah', 'yep'], + falseValue: ['no', 'nah', 'nope'] +}); +if (answer === true) { + console.log('Let\'s go!'); +} else if (answer === false) { + console.log('Oh... It\'s ok...'); +} else { + console.log('Sorry. What does "' + answer + '" you said mean?'); +} +``` + +### `caseSensitive` + +*Type:* boolean +*Default:* `false` + +By default, the string comparisons are case-insensitive (i.e. `a` equals `A`). If `true` is specified, it is case-sensitive, the cases are not ignored (i.e. `a` is different from `A`). +It affects: [`limit`](#basic_options-limit), [`trueValue`](#basic_options-truevalue_falsevalue), [`falseValue`](#basic_options-truevalue_falsevalue), some [placeholders](#placeholders), and some [Utility Methods](#utility_methods). + +### `keepWhitespace` + +_For `question*` and `prompt*` methods only_ +*Type:* boolean +*Default:* `false` + +By default, remove the leading and trailing white spaces from the input text. If `true` is specified, don't remove those. + +### `encoding` + +*Type:* string +*Default:* `'utf8'` + +Set the encoding method of the input and output. + +### `bufferSize` + +_For `question*` and `prompt*` methods only_ +*Type:* number +*Default:* `1024` + +When readlineSync reads from a console directly (without [external program](#note-reading_by_external_program)), use a size `bufferSize` buffer. +Even if the input by user exceeds it, it's usually no problem, because the buffer is used repeatedly. But some platforms's (e.g. Windows) console might not accept input that exceeds it. And set an enough size. +Note that this might be limited by [version of Node.js](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_alloc_size_fill_encoding) and environment running your script (Big buffer size is usually not required). (See also: [issue](https://github.com/nodejs/node/issues/4660), [PR](https://github.com/nodejs/node/pull/4682)) + +### `print` + +*Type:* function or `undefined` +*Default:* `undefined` + +Call the specified function with every output. The function is given two arguments, `display` as an output text, and a value of [`encoding`](#basic_options-encoding) option. + +For example: + +* Pass the plain texts to the Logger (e.g. [log4js](https://github.com/nomiddlename/log4js-node)), after clean the colored texts. + +![sample](screen_01.png) + +```js +var readlineSync = require('readline-sync'), + chalk = require('chalk'), + log4js = require('log4js'), + logger, user, pw, command; + +log4js.configure({appenders: [{type: 'file', filename: 'fooApp.log'}]}); +logger = log4js.getLogger('fooApp'); + +readlineSync.setDefaultOptions({ + print: function(display, encoding) + { logger.info(chalk.stripColor(display)); }, // Remove ctrl-chars. + prompt: chalk.red.bold('> ') +}); + +console.log(chalk.black.bold.bgYellow(' Your Account ')); +user = readlineSync.question(chalk.gray.underline(' USER NAME ') + ' : '); +pw = readlineSync.question(chalk.gray.underline(' PASSWORD ') + ' : ', + {hideEchoBack: true}); +// Authorization ... +console.log(chalk.green('Welcome, ' + user + '!')); +command = readlineSync.prompt(); +``` + +* Output a conversation to a file when an output stream is redirected to record those into a file like `your-script >foo.log`. That is, a conversation isn't outputted to `foo.log` without this code. + +```js +readlineSync.setDefaultOptions({ + print: function(display, encoding) + { process.stdout.write(display, encoding); } +}); +var name = readlineSync.question('May I have your name? '); +var loc = readlineSync.question('Hi ' + name + '! Where do you live? '); +``` + +* Let somebody hear our conversation in real time. +It just uses a fifo with above sample code that was named `conv.js`. + +Another terminal: + +```console +mkfifo /tmp/fifo +cat /tmp/fifo +``` + +My terminal: + +```console +node conv.js >/tmp/fifo +``` + +```console +May I have your name? Oz +Hi Oz! Where do you live? Emerald City +``` + +And then, another terminal shows this synchronously: + +```console +May I have your name? Oz +Hi Oz! Where do you live? Emerald City +``` + +### `history` + +_For `question*` and `prompt*` methods only_ +*Type:* boolean +*Default:* `true` + +readlineSync supports a history expansion feature that is similar to that of the shell. If `false` is specified, disable this feature. +*It keeps a previous input only.* That is, only `!!`, `!-1`, `!!:p` and `!-1:p` like bash or zsh etc. are supported. + +* `!!` or `!-1`: Return a previous input. +* `!!:p` or `!-1:p`: Display a previous input but do not return it, and wait for reinput. + +For example: + +```js +while (true) { + input = readlineSync.prompt(); + console.log('-- You said "' + input + '"'); +} +``` + +```console +> hello +-- You said "hello" +> !! +hello +-- You said "hello" +> !!:p +hello +> bye +-- You said "bye" +``` + +### `cd` + +_For `question*` and `prompt*` methods only_ +*Type:* boolean +*Default:* `false` + +readlineSync supports the changing the current working directory feature that is similar to the `cd` and `pwd` commands in the shell. If `true` is specified, enable this feature. +This helps the user when you let the user input the multiple local files or directories. +It supports `cd` and `pwd` commands. + +* `cd `: Change the current working directory to ``. The `` can include `~` as the home directory. +* `pwd`: Display the current working directory. + +When these were input, do not return, and wait for reinput. + +For example: + +```js +while (true) { + file = readlineSync.questionPath('File: '); + console.log('-- Specified file is ' + file); +} +``` + +```console +File: cd foo-dir/bar-dir +File: pwd +/path/to/foo-dir/bar-dir +File: file-a.js +-- Specified file is /path/to/foo-dir/bar-dir/file-a.js +File: file-b.png +-- Specified file is /path/to/foo-dir/bar-dir/file-b.png +File: file-c.html +-- Specified file is /path/to/foo-dir/bar-dir/file-c.html +``` + +## Utility Methods + +[`questionEMail`](#utility_methods-questionemail), [`questionNewPassword`](#utility_methods-questionnewpassword), [`questionInt`](#utility_methods-questionint), [`questionFloat`](#utility_methods-questionfloat), [`questionPath`](#utility_methods-questionpath), [`promptCL`](#utility_methods-promptcl), [`promptLoop`](#utility_methods-promptloop), [`promptCLLoop`](#utility_methods-promptclloop), [`promptSimShell`](#utility_methods-promptsimshell), [`keyInYN`](#utility_methods-keyinyn), [`keyInYNStrict`](#utility_methods-keyinynstrict), [`keyInPause`](#utility_methods-keyinpause), [`keyInSelect`](#utility_methods-keyinselect) + +These are convenient methods that are extended [Basic Methods](#basic_methods) to be used easily. + +### `questionEMail` + +```js +email = readlineSync.questionEMail([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only a valid e-mail address, and then return it after the Enter key was pressed. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Input e-mail address: '`. + +**Note:** The valid e-mail address requirement is a willful violation of [RFC5322](http://tools.ietf.org/html/rfc5322), this is defined in [HTML5](http://www.w3.org/TR/html5/forms.html). This works enough to prevent the user mistaking. If you want to change it, specify [`limit`](#basic_options-limit) option. + +For example: + +```js +email = readlineSync.questionEMail(); +console.log('-- E-mail is ' + email); +``` + +```console +Input e-mail address: abc +Input valid e-mail address, please. +Input e-mail address: mail@example.com +-- E-mail is mail@example.com +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`limit`](#basic_options-limit) | RegExp by [HTML5](http://www.w3.org/TR/html5/forms.html) | +| [`limitMessage`](#basic_options-limitmessage) | `'Input valid e-mail address, please.'` | +| [`trueValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`falseValue`](#basic_options-truevalue_falsevalue) | `null` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
maskdefaultInputcaseSensitiveencodingbufferSize
printhistory
+ +### `questionNewPassword` + +```js +password = readlineSync.questionNewPassword([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only a valid password, and then request same one again, and then return it after the Enter key was pressed. +It's the password, or something that is the secret text like the password. +You can specify the valid password requirement to the options. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Input new password: '`. + +**Note:** Only the form of password is checked. Check it more if you want. For example, [zxcvbn](https://github.com/dropbox/zxcvbn) is password strength estimation library. + +For example: + +```js +password = readlineSync.questionNewPassword(); +console.log('-- Password is ' + password); +``` + +```console +Input new password: ************ +It can include: 0...9, A...Z, a...z, !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ +And the length must be: 12...24 +Input new password: ************* +Reinput a same one to confirm it: ************* +It differs from first one. Hit only the Enter key if you want to retry from first one. +Reinput a same one to confirm it: ************* +-- Password is _my_password_ +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `true` | +| [`mask`](#basic_options-mask) | `'*'` | +| [`limitMessage`](#basic_options-limitmessage) | `'It can include: $\nAnd the length must be: $'` | +| [`trueValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`falseValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`caseSensitive`](#basic_options-casesensitive) | `true` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
defaultInputkeepWhitespaceencodingbufferSizeprint
+ +And the following additional options are available. + +##### `charlist` + +*Type:* string +*Default:* `'$'` + +A string as the characters that can be included in the password. For example, if `'abc123'` is specified, the passwords that include any character other than these 6 characters are refused. +The [placeholders](#placeholders) like `'$'` are replaced to the characters like `'abcde'`. + +For example, let the user input a password that is created with alphabet and some symbols: + +```js +password = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$#$@%'}); +``` + +##### `min`, `max` + +*Type:* number +*Default:* `min`: `12`, `max`: `24` + +`min`: A number as a minimum length of the password. +`max`: A number as a maximum length of the password. + +##### `confirmMessage` + +*Type:* string or others +*Default:* `'Reinput a same one to confirm it: '` + +A message that lets the user input the same password again. +It can include the [placeholders](#placeholders). +If this is not string, it is converted to string (i.e. `toString` method is called). + +##### `unmatchMessage` + +*Type:* string or others +*Default:* `'It differs from first one. Hit only the Enter key if you want to retry from first one.'` + +A warning message that is displayed when the second input did not match first one. +This is converted the same as the [`confirmMessage`](#utility_methods-questionnewpassword-options-confirmmessage) option. + +#### Additional Placeholders + +The following additional [placeholder](#placeholders) parameters are available. + +##### `charlist` + +A current value of [`charlist`](#utility_methods-questionnewpassword-options-charlist) option that is converted to human readable if possible. (e.g. `'A...Z'`) + +##### `length` + +A current value of [`min` and `max`](#utility_methods-questionnewpassword-options-min_max) option that is converted to human readable. (e.g. `'12...24'`) + +### `questionInt` + +```js +numInt = readlineSync.questionInt([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only an input that can be interpreted as an integer, and then return the number (not string) after the Enter key was pressed. +This parses the input as much as possible by `parseInt()`. For example, it interprets `' 5 '`, `'5.6'`, `'005'`, `'5files'`, `'5kb'` and `'5px'` as `5`. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. + +#### Options + +The following option has independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`limitMessage`](#basic_options-limitmessage) | `'Input valid number, please.'` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
hideEchoBackmaskdefaultInputencodingbufferSize
printhistory
+ +### `questionFloat` + +```js +numFloat = readlineSync.questionFloat([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only an input that can be interpreted as a floating-point number, and then return the number (not string) after the Enter key was pressed. +This parses the input as much as possible by `parseFloat()`. For example, it interprets `' 3.14 '`, `'003.1400'`, `'314e-2'` and `'3.14PI'` as `3.14`. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. + +#### Options + +The following option has independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`limitMessage`](#basic_options-limitmessage) | `'Input valid number, please.'` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
hideEchoBackmaskdefaultInputencodingbufferSize
printhistory
+ +### `questionPath` + +```js +path = readlineSync.questionPath([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only a valid local file or directory path, and then return an absolute path after the Enter key was pressed. +The `~` that is input by the user is replaced to the home directory. +You can specify the valid local file or directory path requirement to the options. And you can make it create a new file or directory when it doesn't exist. + +It is recommended to use this method with the [`cd`](#basic_options-cd) option. (Default: `true`) + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Input path (you can "cd" and "pwd"): '`. + +For example: + +```js +sourceFile = readlineSync.questionPath('Read from: ', { + isFile: true +}); +console.log('-- sourceFile: ' + sourceFile); + +saveDir = readlineSync.questionPath('Save to: ', { + isDirectory: true, + exists: null, + create: true +}); +console.log('-- saveDir: ' + saveDir); +``` + +```console +Read from: ~/fileA +No such file or directory: /home/user/fileA +Input valid path, please. +Read from: pwd +/path/to/work +Read from: cd ~/project-1 +Read from: fileA +-- sourceFile: /home/user/project-1/fileA +Save to: ~/deploy/data +-- saveDir: /home/user/deploy/data +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`limitMessage`](#basic_options-limitmessage) | `'$Input valid path, please.$<( Min:)min>$<( Max:)max>'` | +| [`history`](#basic_options-history) | `true` | +| [`cd`](#basic_options-cd) | `true` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
maskdefaultInputencodingbufferSizeprint
+ +And the following additional options are available. + +**Note:** It does not check the coherency about a combination of the options as the path requirement. For example, the `{exists: false, isFile: true}` never check that it is a file because it is limited to the path that does not exist. + +##### `exists` + +*Type:* boolean or others +*Default:* `true` + +If `true` is specified, accept only a file or directory path that exists. If `false` is specified, accept only a file or directory path that does *not* exist. +In any other case, the existence is not checked. + +##### `min`, `max` + +*Type:* number or others +*Default:* `undefined` + +`min`: A number as a minimum size of the file that is accepted. +`max`: A number as a maximum size of the file that is accepted. +If it is not specified or `0` is specified, the size is not checked. (A size of directory is `0`.) + +##### `isFile`, `isDirectory` + +*Type:* boolean +*Default:* `false` + +`isFile`: If `true` is specified, accept only a file path. +`isDirectory`: If `true` is specified, accept only a directory path. + +##### `validate` + +*Type:* function or `undefined` +*Default:* `undefined` + +If a function that returns `true` or an error message is specified, call it with a path that was input, and accept the input when the function returned `true`. +If the function returned a string as an error message, that message is got by the [`error`](#utility_methods-questionpath-additional_placeholders-error) additional [placeholder](#placeholders) parameter. +A path that was input is parsed before it is passed to the function. `~` is replaced to a home directory, and a path is converted to an absolute path. +This is also a return value from this method. + +For example, accept only PNG file or tell it to the user: + +```js +imageFile = readlineSync.questionPath('Image File: ', { + validate: function(path) { return /\.png$/i.test(path) || 'It is not PNG'; } +}); +``` + +##### `create` + +*Type:* boolean +*Default:* `false` + +If `true` is specified, create a file or directory as a path that was input when it doesn't exist. If `true` is specified to the [`isDirectory`](#utility_methods-questionpath-options-isfile_isdirectory) option, create a directory, otherwise a file. +It does not affect the existence check. Therefore, you can get a new file or directory path anytime by specifying: `{exists: false, create: true}` + +#### Additional Placeholders + +The following additional [placeholder](#placeholders) parameters are available. + +##### `error` + +An error message when the input was not accepted. +This value is set by readlineSync, or the function that was specified to [`validate`](#utility_methods-questionpath-options-validate) option. + +##### `min`, `max` + +A current value of [`min` and `max`](#utility_methods-questionpath-options-min_max) option. + +### `promptCL` + +```js +argsArray = readlineSync.promptCL([commandHandler[, options]]) +``` + +Display a prompt-sign (see [`prompt`](#basic_options-prompt) option) to the user, and then consider the input as a command-line and parse it, and then return a result after the Enter key was pressed. +A return value is an Array that includes the tokens that were parsed. It parses the input from the user as the command-line, and it interprets whitespaces, quotes, etc., and it splits it to tokens properly. Usually, a first element of the Array is command-name, and remaining elements are arguments. + +For example: + +```js +argsArray = readlineSync.promptCL(); +console.log(argsArray.join('\n')); +``` + +```console +> command arg "arg" " a r g " "" 'a"r"g' "a""rg" "arg +command +arg +arg + a r g + +a"r"g +arg +arg +``` + +#### `commandHandler` + +By using the `commandHandler` argument, this method will come into its own. Specifying the Object to this argument has the more merit. And it has the more merit for [`promptCLLoop`](#utility_methods-promptclloop) method. + +If a function is specified to `commandHandler` argument, it is just called with a parsed Array as an argument list of the function. And `this` is an original input string, in the function. + +For example, the following 2 codes work same except that `this` is enabled in the second one: + +```js +argsArray = readlineSync.promptCL(); +if (argsArray[0] === 'add') { + console.log(argsArray[1] + ' is added.'); +} else if (argsArray[0] === 'copy') { + console.log(argsArray[1] + ' is copied to ' + argsArray[2] + '.'); +} +``` + +```js +readlineSync.promptCL(function(command, arg1, arg2) { + console.log('You want to: ' + this); // All of command-line. + if (command === 'add') { + console.log(arg1 + ' is added.'); + } else if (command === 'copy') { + console.log(arg1 + ' is copied to ' + arg2 + '.'); + } +}); +``` + +If an Object that has properties named as the command-name is specified, the command-name is interpreted, and a function as the value of matched property is called. A function is chosen properly by handling case of the command-name in accordance with the [`caseSensitive`](#basic_options-casesensitive) option. +The function is called with a parsed Array that excludes a command-name (i.e. first element is removed from the Array) as an argument list of the function. +That is, a structure of the `commandHandler` Object looks like: + +```js +{ + commandA: function(arg) { ... }, // commandA requires one argument. + commandB: function(arg1, arg2) { ... }, // readlineSync doesn't care those. + commandC: function() { ... } // Of course, it can also ignore all. +} +``` + +readlineSync just receives the arguments from the user and passes those to these functions without checking. The functions may have to check whether the required argument was input by the user, and more validate those. + +For example, the following code works same to the above code: + +```js +readlineSync.promptCL({ + add: function(element) { // It's called by also "ADD", "Add", "aDd", etc.. + console.log(element + ' is added.'); + }, + copy: function(from, to) { + console.log(from + ' is copied to ' + to + '.'); + } +}); +``` + +If the matched property is not found in the Object, a `_` property is chosen, and the function as the value of this property is called with a parsed Array as an argument list of the function. Note that this includes a command-name. That is, the function looks like `function(command, arg1, arg2, ...) { ... }`. +And if the Object doesn't have a `_` property, any command that the matched property is not found in the Object is refused. + +For example: + +```js +readlineSync.promptCL({ + copy: function(from, to) { // command-name is not included. + console.log(from + ' is copied to ' + to + '.'); + }, + _: function(command) { // command-name is included. + console.log('Sorry, ' + command + ' is not available.'); + } +}); +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`limitMessage`](#basic_options-limitmessage) | `'Requested command is not available.'` | +| [`caseSensitive`](#basic_options-casesensitive) | `false` | +| [`history`](#basic_options-history) | `true` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
promptmaskdefaultInputencodingbufferSize
printcd
+ +### `promptLoop` + +```js +readlineSync.promptLoop(inputHandler[, options]) +``` + +Display a prompt-sign (see [`prompt`](#basic_options-prompt) option) to the user, and then call `inputHandler` function with the input from the user after it has been typed and the Enter key was pressed. Do these repeatedly until `inputHandler` function returns `true`. + +For example, the following 2 codes work same: + +```js +while (true) { + input = readlineSync.prompt(); + console.log('-- You said "' + input + '"'); + if (input === 'bye') { + break; + } +} +console.log('It\'s exited from loop.'); +``` + +```js +readlineSync.promptLoop(function(input) { + console.log('-- You said "' + input + '"'); + return input === 'bye'; +}); +console.log('It\'s exited from loop.'); +``` + +```console +> hello +-- You said "hello" +> good morning +-- You said "good morning" +> bye +-- You said "bye" +It's exited from loop. +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`trueValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`falseValue`](#basic_options-truevalue_falsevalue) | `null` | +| [`caseSensitive`](#basic_options-casesensitive) | `false` | +| [`history`](#basic_options-history) | `true` | + +The other options work as shown in the [Basic Options](#basic_options) section. + +### `promptCLLoop` + +```js +readlineSync.promptCLLoop([commandHandler[, options]]) +``` + +Execute [`promptCL`](#utility_methods-promptcl) method repeatedly until chosen [`commandHandler`](#utility_methods-promptcl-commandhandler) returns `true`. +The [`commandHandler`](#utility_methods-promptcl-commandhandler) may be a function that is called like: + +```js +exit = allCommands(command, arg1, arg2, ...); +``` + +or an Object that has the functions that are called like: + +```js +exit = foundCommand(arg1, arg2, ...); +``` + +See [`promptCL`](#utility_methods-promptcl) method for details. +This method looks like a combination of [`promptCL`](#utility_methods-promptcl) method and [`promptLoop`](#utility_methods-promptloop) method. + +For example: + +```js +readlineSync.promptCLLoop({ + add: function(element) { + console.log(element + ' is added.'); + }, + copy: function(from, to) { + console.log(from + ' is copied to ' + to + '.'); + }, + bye: function() { return true; } +}); +console.log('It\'s exited from loop.'); +``` + +```console +> add "New Hard Disk" +New Hard Disk is added. +> move filesOnOld "New Hard Disk" +Requested command is not available. +> copy filesOnOld "New Hard Disk" +filesOnOld is copied to New Hard Disk. +> bye +It's exited from loop. +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`limitMessage`](#basic_options-limitmessage) | `'Requested command is not available.'` | +| [`caseSensitive`](#basic_options-casesensitive) | `false` | +| [`history`](#basic_options-history) | `true` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + + +
promptmaskdefaultInputencodingbufferSize
printcd
+ +### `promptSimShell` + +```js +input = readlineSync.promptSimShell([options]) +``` + +Display a prompt-sign that is similar to that of the user's shell to the user, and then return the input from the user after it has been typed and the Enter key was pressed. +This method displays a prompt-sign like: + +On Windows: + +```console +C:\Users\User\Path\To\Directory> +``` + +On others: + +```console +user@host:~/path/to/directory$ +``` + +#### Options + +The following options have independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | +| [`history`](#basic_options-history) | `true` | + +The other options other than [`prompt`](#basic_options-prompt) option work as shown in the [Basic Options](#basic_options) section. + +### `keyInYN` + +```js +boolYesOrEmpty = readlineSync.keyInYN([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then return a boolean or an empty string immediately a key was pressed by the user, **without pressing the Enter key**. Note that the user has no chance to change the input. +This method works like the `window.confirm` method of web browsers. A return value means "Yes" or "No" the user said. It differ depending on the pressed key: + +* `Y`: `true` +* `N`: `false` +* other: `''` + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Are you sure? '`. + +The keys other than `Y` and `N` are also accepted (If you want to know a user's wish explicitly, use [`keyInYNStrict`](#utility_methods-keyinynstrict) method). Therefore, if you let the user make an important decision (e.g. files are removed), check whether the return value is not *falsy*. That is, a default is "No". + +For example: + +```js +if (!readlineSync.keyInYN('Do you want to install this?')) { + // Key that is not `Y` was pressed. + process.exit(); +} +// Do something... +``` + +Or if you let the user stop something that must be done (e.g. something about the security), check whether the return value is `false` explicitly. That is, a default is "Yes". + +For example: + +```js +// Don't use `(!readlineSync.keyInYN())`. +if (readlineSync.keyInYN('Continue virus scan?') === false) { + // `N` key was pressed. + process.exit(); +} +// Continue... +``` + +#### Options + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
encodingprint
+ +And the following additional option is available. + +##### `guide` + +*Type:* boolean +*Default:* `true` + +If `true` is specified, a string `'[y/n]'` as guide for the user is added to `query`. And `':'` is moved to the end of `query`, or it is added. + +For example: + +```js +readlineSync.keyInYN('Do you like me?'); // No colon +readlineSync.keyInYN('Really? :'); // Colon already exists +``` + +```console +Do you like me? [y/n]: y +Really? [y/n]: y +``` + +### `keyInYNStrict` + +```js +boolYes = readlineSync.keyInYNStrict([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then accept only `Y` or `N` key, and then return a boolean immediately it was pressed by the user, **without pressing the Enter key**. Note that the user has no chance to change the input. +This method works like the `window.confirm` method of web browsers. A return value means "Yes" or "No" the user said. It differ depending on the pressed key: + +* `Y`: `true` +* `N`: `false` + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Are you sure? '`. + +A key other than `Y` and `N` is not accepted. That is, a return value has no default. Therefore, the user has to tell an own wish explicitly. If you want to know a user's wish easily, use [`keyInYN`](#utility_methods-keyinyn) method. + +This method works same to [`keyInYN`](#utility_methods-keyinyn) method except that this accept only `Y` or `N` key (Therefore, a return value is boolean every time). The options also work same to [`keyInYN`](#utility_methods-keyinyn) method. + +### `keyInPause` + +```js +readlineSync.keyInPause([query[, options]]) +``` + +Display a `query` to the user if it's specified, and then just wait for a key to be pressed by the user. +This method works like the `window.alert` method of web browsers. This is used to make the running of script pause and show something to the user, or wait for the user to be ready. +By default, any key is accepted (See: [Note](#utility_methods-keyinpause-note)). You can change this behavior by specifying [`limit`](#basic_options-limit) option (e.g. accept only a Space Bar). + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Continue...'`. + +For example: + +```js +// Have made the preparations for something... +console.log('==== Information of Your Computer ===='); +console.log(info); // This can be `query`. +readlineSync.keyInPause(); +console.log('It\'s executing now...'); +// Do something... +``` + +```console +==== Information of Your Computer ==== +FOO: 123456 +BAR: abcdef +Continue... (Hit any key) +It's executing now... +``` + +#### Options + +The following option has independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`limit`](#basic_options-limit) | `null` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
caseSensitiveencodingprint
+ +And the following additional option is available. + +##### `guide` + +*Type:* boolean +*Default:* `true` + +If `true` is specified, a string `'(Hit any key)'` as guide for the user is added to `query`. + +For example: + +```js +readlineSync.keyInPause('It\'s pausing now...'); +``` + +```console +It's pausing now... (Hit any key) +``` + +#### Note + +Control keys including Enter key are not accepted by `keyIn*` methods. +If you want to wait until the user presses Enter key, use `question*` methods instead of `keyIn*` methods. For example: + +```js +readlineSync.question('Hit Enter key to continue.', {hideEchoBack: true, mask: ''}); +``` + +### `keyInSelect` + +```js +index = readlineSync.keyInSelect(items[, query[, options]]) +``` + +Display the list that was created with the `items` Array, and the `query` to the user if it's specified, and then return the number as an index of the `items` Array immediately it was chosen by pressing a key by the user, **without pressing the Enter key**. Note that the user has no chance to change the input. + +The `query` is handled the same as that of the [`question`](#basic_methods-question) method. +The default value of `query` is `'Choose one from list: '`. + +The minimum length of `items` Array is 1 and maximum length is 35. These elements are displayed as item list. A key to let the user choose an item is assigned to each item automatically in sequence like "1, 2, 3 ... 9, A, B, C ...". A number as an index of the `items` Array that corresponds to a chosen item by the user is returned. + +**Note:** Even if the `items` Array has only less than 35 items, a long Array that forces an user to scroll the list may irritate the user. Remember, the user might be in a console environment that doesn't support scrolling the screen. If you want to use a long `items` Array (e.g. more than 10 items), you should consider a "Pagination". (See [example](https://github.com/anseki/readline-sync/issues/60#issuecomment-324533678).) + +For example: + +```js +frameworks = ['Express', 'hapi', 'flatiron', 'MEAN.JS', 'locomotive']; +index = readlineSync.keyInSelect(frameworks, 'Which framework?'); +console.log(frameworks[index] + ' is enabled.'); +``` + +```console +[1] Express +[2] hapi +[3] flatiron +[4] MEAN.JS +[5] locomotive +[0] CANCEL + +Which framework? [1...5 / 0]: 2 +hapi is enabled. +``` + +#### Options + +The following option has independent default value that is not affected by [Default Options](#basic_options). + +| Option Name | Default Value | +|-------------------|---------------| +| [`hideEchoBack`](#basic_options-hideechoback) | `false` | + +The following options work as shown in the [Basic Options](#basic_options) section. + + + +
maskencodingprint
+ +And the following additional options are available. + +##### `guide` + +*Type:* boolean +*Default:* `true` + +If `true` is specified, a string like `'[1...5]'` as guide for the user is added to `query`. And `':'` is moved to the end of `query`, or it is added. This is the key list that corresponds to the item list. + +##### `cancel` + +*Type:* boolean, string or others +*Default:* `'CANCEL'` + +If a value other than `false` is specified, an item to let the user tell "cancel" is added to the item list. "[0] CANCEL" (default) is displayed, and if `0` key is pressed, `-1` is returned. +You can specify a label of this item other than `'CANCEL'`. A string such as `'Go back'` (empty string `''` also), something that is converted to string such as `Date`, a string that includes [placeholder](#placeholders) such as `'Next $ items'` are accepted. + +#### Additional Placeholders + +The following additional [placeholder](#placeholders) parameters are available. + +##### `itemsCount` + +A length of a current `items` Array. + +For example: + +```js +items = ['item-A', 'item-B', 'item-C', 'item-D', 'item-E']; +index = readlineSync.keyInSelect(items, null, + {cancel: 'Show more than $ items'}); +``` + +```console +[1] item-A +[2] item-B +[3] item-C +[4] item-D +[5] item-E +[0] Show more than 5 items +``` + +##### `firstItem` + +A first item in a current `items` Array. + +For example: + +```js +index = readlineSync.keyInSelect(items, 'Choose $ or another: '); +``` + +##### `lastItem` + +A last item in a current `items` Array. + +For example: + +```js +items = ['January', 'February', 'March', 'April', 'May', 'June']; +index = readlineSync.keyInSelect(items, null, + {cancel: 'In after $'}); +``` + +```console +[1] January +[2] February +[3] March +[4] April +[5] May +[6] June +[0] In after June +``` + +## Placeholders + +[`hideEchoBack`, `mask`, `defaultInput`, `caseSensitive`, `keepWhitespace`, `encoding`, `bufferSize`, `history`, `cd`, `limit`, `trueValue`, `falseValue`](#placeholders-parameters-hideechoback_mask_defaultinput_casesensitive_keepwhitespace_encoding_buffersize_history_cd_limit_truevalue_falsevalue), [`limitCount`, `limitCountNotZero`](#placeholders-parameters-limitcount_limitcountnotzero), [`lastInput`](#placeholders-parameters-lastinput), [`history_mN`](#placeholders-parameters-historymn), [`cwd`, `CWD`, `cwdHome`](#placeholders-parameters-cwd_cwd_cwdhome), [`date`, `time`, `localeDate`, `localeTime`](#placeholders-parameters-date_time_localedate_localetime), [`C1-C2`](#placeholders-parameters-c1_c2) + +The placeholders in the text are replaced to another string. + +For example, the [`limitMessage`](#basic_options-limitmessage) option to display a warning message that means that the command the user requested is not available: + +```js +command = readlineSync.prompt({ + limit: ['add', 'remove'], + limitMessage: '$ is not available.' +}); +``` + +```console +> delete +delete is not available. +``` + +The placeholders can be included in: + +* `query` argument +* [`prompt`](#basic_options-prompt) and [`limitMessage`](#basic_options-limitmessage) options +* [`limit` option for `keyIn*` method](#basic_options-limit-for_keyin_method) and [`charlist`](#utility_methods-questionnewpassword-options-charlist) option for [`questionNewPassword`](#utility_methods-questionnewpassword) method ([`C1-C2`](#placeholders-parameters-c1_c2) parameter only) +* And some additional options for the [Utility Methods](#utility_methods). + +### Syntax + +``` +$ +``` + +Or + +``` +$<(text1)parameter(text2)> +``` + +The placeholder is replaced to a string that is got by a `parameter`. +Both the `(text1)` and `(text2)` are optional. +A more added `'$'` at the left of the placeholder is used as an escape character, it disables a placeholder. For example, `'$$'` is replaced to `'$'`. If you want to put a `'$'` which is *not* an escape character at the left of a placeholder, specify it like `'$<($)bufferSize>'`, then it is replaced to `'$1024'`. + +At the each position of `'(text1)'` and `'(text2)'`, `'text1'` and `'text2'` are put when a string that was got by a `parameter` has more than 0 length. If that got string is `''`, a placeholder with or without `'(text1)'` and `'(text2)'` is replaced to `''`. + +For example, a warning message that means that the command the user requested is not available: + +```js +command = readlineSync.prompt({ + limit: ['add', 'remove'], + limitMessage: 'Refused $ you requested. Please input another.' +}); +``` + +```console +> give-me-car +Refused give-me-car you requested. Please input another. +``` + +It looks like no problem. +But when the user input nothing (hit only the Enter key), and then a message is displayed: + +```console +> +Refused you requested. Please input another. +``` + +This goes well: + +```js +command = readlineSync.prompt({ + limit: ['add', 'remove'], + limitMessage: 'Refused $. Please input another.' +}); +``` + +```console +> +Refused . Please input another. +``` + +(May be more better: `'$<(Refused )lastInput( you requested. )>Please input another.'`) + +**Note:** The syntax `${parameter}` of older version is still supported, but this should not be used because it may be confused with template string syntax of ES6. And this will not be supported in due course of time. + +### Parameters + +The following parameters are available. And some additional parameters are available in the [Utility Methods](#utility_methods). + +#### `hideEchoBack`, `mask`, `defaultInput`, `caseSensitive`, `keepWhitespace`, `encoding`, `bufferSize`, `history`, `cd`, `limit`, `trueValue`, `falseValue` + +A current value of each option. +It is converted to human readable if possible. The boolean value is replaced to `'on'` or `'off'`, and the Array is replaced to the list of only string and number elements. +And in the `keyIn*` method, the parts of the list as characters sequence are suppressed. For example, when `['a', 'b', 'c', 'd', 'e']` is specified to the [`limit`](#basic_options-limit) option, `'$'` is replaced to `'a...e'`. If `true` is specified to the [`caseSensitive`](#basic_options-casesensitive) option, the characters are converted to lower case. + +For example: + +```js +input = readlineSync.question( + 'Input something or the Enter key as "$": ', + {defaultInput: 'hello'} +); +``` + +```console +Input something or the Enter key as "hello": +``` + +#### `limitCount`, `limitCountNotZero` + +A length of a current value of the [`limit`](#basic_options-limit) option. +When the value of the [`limit`](#basic_options-limit) option is empty, `'$'` is replaced to `'0'`, `'$'` is replaced to `''`. + +For example: + +```js +action = readlineSync.question( + 'Choose action$<( from )limitCountNotZero( actions)>: ', + {limit: availableActions} +); +``` + +```console +Choose action from 5 actions: +``` + +#### `lastInput` + +A last input from the user. +In any case, this is saved. + +For example: + +```js +command = readlineSync.prompt({ + limit: availableCommands, + limitMessage: '$ is not available.' +}); +``` + +```console +> wrong-command +wrong-command is not available. +``` + +#### `history_mN` + +When the history expansion feature is enabled (see [`history`](#basic_options-history) option), a current command line minus `N`. +*This feature keeps the previous input only.* That is, only `history_m1` is supported. + +For example: + +```js +while (true) { + input = readlineSync.question('Something$<( or "!!" as ")history_m1(")>: '); + console.log('-- You said "' + input + '"'); +} +``` + +```console +Something: hello +-- You said "hello" +Something or "!!" as "hello": !! +hello +-- You said "hello" +``` + +#### `cwd`, `CWD`, `cwdHome` + +A current working directory. + +* `cwd`: A full-path +* `CWD`: A directory name +* `cwdHome`: A path that includes `~` as the home directory + +For example, like bash/zsh: + +```js +command = readlineSync.prompt({prompt: '[$]$ '}); +``` + +```console +[~/foo/bar]$ +``` + +#### `date`, `time`, `localeDate`, `localeTime` + +A string as current date or time. + +* `date`: A date portion +* `time`: A time portion +* `localeDate`: A locality sensitive representation of the date portion based on system settings +* `localeTime`: A locality sensitive representation of the time portion based on system settings + +For example: + +```js +command = readlineSync.prompt({prompt: '[$]> '}); +``` + +```console +[04/21/2015]> +``` + +#### `C1-C2` + +_For [`limit` option for `keyIn*` method](#basic_options-limit-for_keyin_method) and [`charlist`](#utility_methods-questionnewpassword-options-charlist) option for [`questionNewPassword`](#utility_methods-questionnewpassword) method only_ + +A character list. +`C1` and `C2` are each single character as the start and the end. A sequence in ascending or descending order of characters ranging from `C1` to `C2` is created. For example, `'$'` is replaced to `'abcde'`. `'$<5-1>'` is replaced to `'54321'`. + +For example, let the user input a password that is created with alphabet: + +```js +password = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$'}); +``` + +See also [`limit` option for `keyIn*` method](#basic_options-limit-for_keyin_method). + +## Special method `getRawInput` + +```js +rawInput = readlineSync.getRawInput() +``` + +Return a raw input data of last method. +When the input was terminated with no data, a `NULL` is inserted to the data. + +This might contain control-codes (e.g. `LF`, `CR`, `EOF`, etc.), therefore, it might be used to get `^D` that was input. But you should understand each environments for that. Or, **you should not use this** if your script is used in multiple environments. +For example, when the user input `EOF` (`^D` in Unix like system, `^Z` in Windows), `x1A` (`EOF`) is returned in Windows, and `x00` (`NULL`) is returned in Unix like system. And `x04` (`EOT`) is returned in Unix like system with raw-mode. And also, when [external program](#note-reading_by_external_program) is used, nothing is returned. See also [Control characters](#note-control_characters). +You may examine each environment and you must test your script very much, if you want to handle the raw input data. + +## With Task Runner + +The easy way to control a flow of the task runner by the input from the user: + +* [Grunt](http://gruntjs.com/) plugin: [grunt-confirm](https://github.com/anseki/grunt-confirm) +* [gulp](http://gulpjs.com/) plugin: [gulp-confirm](https://github.com/anseki/gulp-confirm) + +If you want to control a flow of the task runner (e.g. [Grunt](http://gruntjs.com/)), call readlineSync in a task callback that is called by the task runner. Then a flow of tasks is paused and it is controlled by the user. + +For example, by using [grunt-task-helper](https://github.com/anseki/grunt-task-helper): + +```console +$ grunt +Running "fileCopy" task +Files already exist: + file-a.png + file-b.js +Overwrite? [y/n]: y +file-a.png copied. +file-b.js copied. +Done. +``` + +`Gruntfile.js` + +```js +grunt.initConfig({ + taskHelper: { + fileCopy: { + options: { + handlerByTask: function() { + // Abort the task if user don't want it. + return readlineSync.keyInYN('Overwrite?'); + }, + filesArray: [] + }, + ... + } + }, + copy: { + fileCopy: { + files: '<%= taskHelper.fileCopy.options.filesArray %>' + } + } +}); +``` + +## Note + +### Platforms + +TTY interfaces are different by the platforms. If the platform doesn't support the interactively reading from TTY, an error is thrown. + +```js +try { + answer = readlineSync.question('What is your favorite food? '); +} catch (e) { + console.error(e); + process.exit(1); +} +``` + +### Control characters + +TTY interfaces are different by the platforms. In some environments, ANSI escape sequences might be ignored. For example, in non-POSIX TTY such as Windows CMD does not support it (that of Windows 8 especially has problems). Since readlineSync does not use Node.js library that emulates POSIX TTY (but that is still incomplete), those characters may be not parsed. Then, using ANSI escape sequences is not recommended if you will support more environments. +Also, control characters user input might be not accepted or parsed. That behavior differs depending on the environment. And current Node.js does not support controlling a readline system library. + +### Reading by external program + +readlineSync tries to read from a console by using the external program if it is needed (e.g. when the input stream is redirected on Windows XP). And if the running Node.js doesn't support the [Synchronous Process Execution](http://nodejs.org/api/child_process.html#child_process_synchronous_process_creation) (i.e. Node.js v0.10-), readlineSync uses "piping via files" for the synchronous execution. +As everyone knows, "piping via files" is no good. It blocks the event loop and a process. It might make the your script be slow. + +Why did I choose it? : + +* Good modules (native addon) for the synchronous execution exist, but node-gyp can't compile those in some platforms or Node.js versions. +* I think that the security is important more than the speed. Some modules have problem about security. Those don't protect the data. I think that the speed is not needed usually, because readlineSync is used while user types keys. + +## Deprecated methods and options + +See [README-Deprecated.md](README-Deprecated.md). diff --git a/loops/exercises/node_modules/readline-sync/lib/encrypt.js b/loops/exercises/node_modules/readline-sync/lib/encrypt.js new file mode 100644 index 0000000000..d732ce6f8e --- /dev/null +++ b/loops/exercises/node_modules/readline-sync/lib/encrypt.js @@ -0,0 +1,24 @@ +/* + * readlineSync + * https://github.com/anseki/readline-sync + * + * Copyright (c) 2019 anseki + * Licensed under the MIT license. + */ + +var cipher = require('crypto').createCipher( + process.argv[2] /*algorithm*/, process.argv[3] /*password*/), + stdin = process.stdin, + stdout = process.stdout, + crypted = ''; + +stdin.resume(); +stdin.setEncoding('utf8'); +stdin.on('data', function(d) { + crypted += cipher.update(d, 'utf8', 'hex'); +}); +stdin.on('end', function() { + stdout.write(crypted + cipher.final('hex'), 'binary', function() { + process.exit(0); + }); +}); diff --git a/loops/exercises/node_modules/readline-sync/lib/read.cs.js b/loops/exercises/node_modules/readline-sync/lib/read.cs.js new file mode 100644 index 0000000000..a789c22b52 --- /dev/null +++ b/loops/exercises/node_modules/readline-sync/lib/read.cs.js @@ -0,0 +1,123 @@ +/* jshint wsh:true */ + +/* + * readlineSync + * https://github.com/anseki/readline-sync + * + * Copyright (c) 2019 anseki + * Licensed under the MIT license. + */ + +var + FSO_ForReading = 1, FSO_ForWriting = 2, + PS_MSG = 'Microsoft Windows PowerShell is required.' + + ' https://technet.microsoft.com/en-us/library/hh847837.aspx', + + input = '', fso, tty, + options = (function(conf) { + var options = {}, arg, args =// Array.prototype.slice.call(WScript.Arguments), + (function() { + var args = [], i, iLen; + for (i = 0, iLen = WScript.Arguments.length; i < iLen; i++) + { args.push(WScript.Arguments(i)); } + return args; + })(), + confLc = {}, key; + + function decodeArg(arg) { + return arg.replace(/#(\d+);/g, function(str, charCode) { + return String.fromCharCode(+charCode); + }); + } + + for (key in conf) { + if (conf.hasOwnProperty(key)) + { confLc[key.toLowerCase()] = {key: key, type: conf[key]}; } + } + + while (typeof(arg = args.shift()) === 'string') { + if (!(arg = (arg.match(/^\-+(.+)$/) || [])[1])) { continue; } + arg = arg.toLowerCase(); + if (confLc[arg]) { + options[confLc[arg].key] = + confLc[arg].type === 'boolean' ? true : + confLc[arg].type === 'string' ? args.shift() : null; + } + } + for (key in conf) { + if (conf.hasOwnProperty(key) && conf[key] === 'string') { + if (typeof options[key] !== 'string') { options[key] = ''; } + else { options[key] = decodeArg(options[key]); } + } + } + return options; + })({ + display: 'string', + displayOnly: 'boolean', + keyIn: 'boolean', + hideEchoBack: 'boolean', + mask: 'string' + }); + +if (!options.hideEchoBack && !options.keyIn) { + if (options.display) { writeTTY(options.display); } + if (!options.displayOnly) { input = readByFSO(); } +} else if (options.hideEchoBack && !options.keyIn && !options.mask) { + if (options.display) { writeTTY(options.display); } + if (!options.displayOnly) { input = readByPW(); } +} else { + WScript.StdErr.WriteLine(PS_MSG); + WScript.Quit(1); +} + +WScript.StdOut.Write('\'' + input + '\''); + +WScript.Quit(); + +function writeTTY(text) { + try { + tty = tty || getFso().OpenTextFile('CONOUT$', FSO_ForWriting, true); + tty.Write(text); + } catch (e) { + WScript.StdErr.WriteLine('TTY Write Error: ' + e.number + + '\n' + e.description + '\n' + PS_MSG); + WScript.Quit(e.number || 1); + } +} + +function readByFSO() { + var text; + try { + text = getFso().OpenTextFile('CONIN$', FSO_ForReading).ReadLine(); + } catch (e) { + WScript.StdErr.WriteLine('TTY Read Error: ' + e.number + + '\n' + e.description + '\n' + PS_MSG); + WScript.Quit(e.number || 1); + } + return text; +} + +// TTY must be STDIN that is not redirected and not piped. +function readByPW() { + var text; + try { + text = WScript.CreateObject('ScriptPW.Password').GetPassword() + // Bug? Illegal data may be returned when user types before initializing. + .replace(/[\u4000-\u40FF]/g, function(chr) { + var charCode = chr.charCodeAt(0); + return charCode >= 0x4020 && charCode <= 0x407F ? + String.fromCharCode(charCode - 0x4000) : ''; + }); + } catch (e) { + WScript.StdErr.WriteLine('ScriptPW.Password Error: ' + e.number + + '\n' + e.description + '\n' + PS_MSG); + WScript.Quit(e.number || 1); + } + writeTTY('\n'); + return text; +} + +function getFso() { + if (!fso) { fso = new ActiveXObject('Scripting.FileSystemObject'); } + return fso; +} diff --git a/loops/exercises/node_modules/readline-sync/lib/read.ps1 b/loops/exercises/node_modules/readline-sync/lib/read.ps1 new file mode 100644 index 0000000000..096cdd107d --- /dev/null +++ b/loops/exercises/node_modules/readline-sync/lib/read.ps1 @@ -0,0 +1,128 @@ +# readlineSync +# https://github.com/anseki/readline-sync +# +# Copyright (c) 2019 anseki +# Licensed under the MIT license. + +Param( + [string] $display, + [switch] $displayOnly, + [switch] $keyIn, + [switch] $hideEchoBack, + [string] $mask, + [string] $limit, + [switch] $caseSensitive +) + +$ErrorActionPreference = 'Stop' # for cmdlet +trap { + # `throw $_` and `Write-Error $_` return exit-code 0 + $Host.UI.WriteErrorLine($_) + exit 1 +} + +function decodeArg ($arg) { + [Regex]::Replace($arg, '#(\d+);', { [char][int] $args[0].Groups[1].Value }) +} + +$options = @{} +foreach ($arg in @('display', 'displayOnly', 'keyIn', 'hideEchoBack', 'mask', 'limit', 'caseSensitive')) { + $options.Add($arg, (Get-Variable $arg -ValueOnly)) +} +$argList = New-Object string[] $options.Keys.Count +$options.Keys.CopyTo($argList, 0) +foreach ($arg in $argList) { + if ($options[$arg] -is [string] -and $options[$arg]) + { $options[$arg] = decodeArg $options[$arg] } +} + +[string] $inputTTY = '' +[bool] $silent = -not $options.display -and + $options.keyIn -and $options.hideEchoBack -and -not $options.mask +[bool] $isCooked = -not $options.hideEchoBack -and -not $options.keyIn + +# Instant method that opens TTY without CreateFile via P/Invoke in .NET Framework +# **NOTE** Don't include special characters of DOS in $command when $getRes is True. +# [string] $cmdPath = $Env:ComSpec +# [string] $psPath = 'powershell.exe' +function execWithTTY ($command, $getRes = $False, $throwError = $False) { + if ($getRes) { + $res = (cmd.exe /C "CON powershell.exe -Command -" + if ($LastExitCode -ne 0) { + if ($throwError) { throw $LastExitCode } + else { exit $LastExitCode } + } + } +} + +function writeTTY ($text) { + execWithTTY ('Write-Host (''' + + (($text -replace '''', '''''') -replace '[\r\n]', '''+"`n"+''') + ''') -NoNewline') +} + +if ($options.display) { + writeTTY $options.display +} +if ($options.displayOnly) { return "''" } + +if (-not $options.keyIn -and $options.hideEchoBack -and $options.mask -eq '*') { + # It fails when it's not ready. + try { + $inputTTY = execWithTTY ('$text = Read-Host -AsSecureString;' + + '$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($text);' + + '[Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)') $True $True + return '''' + $inputTTY + '''' + } catch {} # ignore +} + +if ($options.keyIn) { $reqSize = 1 } + +if ($options.keyIn -and $options.limit) { + $limitPtn = '[^' + $options.limit + ']' +} + +while ($True) { + if (-not $isCooked) { + $chunk = [char][int] (execWithTTY '[int] [Console]::ReadKey($True).KeyChar' $True) + } else { + $chunk = execWithTTY 'Read-Host' $True + $chunk += "`n" + } + + if ($chunk -and $chunk -match '^(.*?)[\r\n]') { + $chunk = $Matches[1] + $atEol = $True + } else { $atEol = $False } + + # other ctrl-chars + if ($chunk) { $chunk = $chunk -replace '[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '' } + if ($chunk -and $limitPtn) { + if ($options.caseSensitive) { $chunk = $chunk -creplace $limitPtn, '' } + else { $chunk = $chunk -ireplace $limitPtn, '' } + } + + if ($chunk) { + if (-not $isCooked) { + if (-not $options.hideEchoBack) { + writeTTY $chunk + } elseif ($options.mask) { + writeTTY ($options.mask * $chunk.Length) + } + } + $inputTTY += $chunk + } + + if ((-not $options.keyIn -and $atEol) -or + ($options.keyIn -and $inputTTY.Length -ge $reqSize)) { break } +} + +if (-not $isCooked -and -not $silent) { execWithTTY 'Write-Host ''''' } # new line + +return "'$inputTTY'" diff --git a/loops/exercises/node_modules/readline-sync/lib/read.sh b/loops/exercises/node_modules/readline-sync/lib/read.sh new file mode 100644 index 0000000000..b41e80c23b --- /dev/null +++ b/loops/exercises/node_modules/readline-sync/lib/read.sh @@ -0,0 +1,137 @@ +# readlineSync +# https://github.com/anseki/readline-sync +# +# Copyright (c) 2019 anseki +# Licensed under the MIT license. + +# Use perl for compatibility of sed/awk of GNU / POSIX, BSD. (and tr) +# Hide "\n" from shell by "\fNL" + +decode_arg() { + printf '%s' "$(printf '%s' "$1" | perl -pe 's/#(\d+);/sprintf("%c", $1)/ge; s/[\r\n]/\fNL/g')" +} + +# getopt(s) +while [ $# -ge 1 ]; do + arg="$(printf '%s' "$1" | grep -E '^-+[^-]+$' | tr '[A-Z]' '[a-z]' | tr -d '-')" + case "$arg" in + 'display') shift; options_display="$(decode_arg "$1")";; + 'displayonly') options_displayOnly=true;; + 'keyin') options_keyIn=true;; + 'hideechoback') options_hideEchoBack=true;; + 'mask') shift; options_mask="$(decode_arg "$1")";; + 'limit') shift; options_limit="$(decode_arg "$1")";; + 'casesensitive') options_caseSensitive=true;; + esac + shift +done + +reset_tty() { + if [ -n "$save_tty" ]; then + stty --file=/dev/tty "$save_tty" 2>/dev/null || \ + stty -F /dev/tty "$save_tty" 2>/dev/null || \ + stty -f /dev/tty "$save_tty" || exit $? + fi +} +trap 'reset_tty' EXIT +save_tty="$(stty --file=/dev/tty -g 2>/dev/null || stty -F /dev/tty -g 2>/dev/null || stty -f /dev/tty -g || exit $?)" + +[ -z "$options_display" ] && [ "$options_keyIn" = true ] && \ + [ "$options_hideEchoBack" = true ] && [ -z "$options_mask" ] && silent=true +[ "$options_hideEchoBack" != true ] && [ "$options_keyIn" != true ] && is_cooked=true + +write_tty() { + # if [ "$2" = true ]; then + # printf '%b' "$1" >/dev/tty + # else + # printf '%s' "$1" >/dev/tty + # fi + printf '%s' "$1" | perl -pe 's/\fNL/\r\n/g' >/dev/tty +} + +replace_allchars() { ( + text='' + for i in $(seq 1 ${#1}) + do + text="$text$2" + done + printf '%s' "$text" +) } + +if [ -n "$options_display" ]; then + write_tty "$options_display" +fi +if [ "$options_displayOnly" = true ]; then + printf "'%s'" '' + exit 0 +fi + +if [ "$is_cooked" = true ]; then + stty --file=/dev/tty cooked 2>/dev/null || \ + stty -F /dev/tty cooked 2>/dev/null || \ + stty -f /dev/tty cooked || exit $? +else + stty --file=/dev/tty raw -echo 2>/dev/null || \ + stty -F /dev/tty raw -echo 2>/dev/null || \ + stty -f /dev/tty raw -echo || exit $? +fi + +[ "$options_keyIn" = true ] && req_size=1 + +if [ "$options_keyIn" = true ] && [ -n "$options_limit" ]; then + if [ "$options_caseSensitive" = true ]; then + limit_ptn="$options_limit" + else + # Safe list + # limit_ptn="$(printf '%s' "$options_limit" | sed 's/\([a-z]\)/\L\1\U\1/ig')" + limit_ptn="$(printf '%s' "$options_limit" | perl -pe 's/([a-z])/lc($1) . uc($1)/ige')" + fi +fi + +while : +do + if [ "$is_cooked" != true ]; then + # chunk="$(dd if=/dev/tty bs=1 count=1 2>/dev/null)" + chunk="$(dd if=/dev/tty bs=1 count=1 2>/dev/null | perl -pe 's/[\r\n]/\fNL/g')" + else + IFS= read -r chunk ', + hideEchoBack: false, + mask: '*', + limit: [], + limitMessage: 'Input another, please.$<( [)limit(])>', + defaultInput: '', + trueValue: [], + falseValue: [], + caseSensitive: false, + keepWhitespace: false, + encoding: 'utf8', + bufferSize: 1024, + print: void 0, + history: true, + cd: false, + phContent: void 0, + preCheck: void 0 + /* eslint-enable key-spacing */ + }, + + fdR = 'none', + isRawMode = false, + salt = 0, + lastInput = '', + inputHistory = [], + _DBG_useExt = false, + _DBG_checkOptions = false, + _DBG_checkMethod = false, + fdW, ttyR, extHostPath, extHostArgs, tempdir, rawInput; + +function getHostArgs(options) { + // Send any text to crazy Windows shell safely. + function encodeArg(arg) { + return arg.replace(/[^\w\u0080-\uFFFF]/g, function(chr) { + return '#' + chr.charCodeAt(0) + ';'; + }); + } + + return extHostArgs.concat((function(conf) { + var args = []; + Object.keys(conf).forEach(function(optionName) { + if (conf[optionName] === 'boolean') { + if (options[optionName]) { args.push('--' + optionName); } + } else if (conf[optionName] === 'string') { + if (options[optionName]) { + args.push('--' + optionName, encodeArg(options[optionName])); + } + } + }); + return args; + })({ + /* eslint-disable key-spacing */ + display: 'string', + displayOnly: 'boolean', + keyIn: 'boolean', + hideEchoBack: 'boolean', + mask: 'string', + limit: 'string', + caseSensitive: 'boolean' + /* eslint-enable key-spacing */ + })); +} + +// piping via files (for Node.js v0.10-) +function _execFileSync(options, execOptions) { + + function getTempfile(name) { + var suffix = '', + filepath, fd; + tempdir = tempdir || require('os').tmpdir(); + + while (true) { + filepath = pathUtil.join(tempdir, name + suffix); + try { + fd = fs.openSync(filepath, 'wx'); + } catch (e) { + if (e.code === 'EEXIST') { + suffix++; + continue; + } else { + throw e; + } + } + fs.closeSync(fd); + break; + } + return filepath; + } + + var res = {}, + pathStdout = getTempfile('readline-sync.stdout'), + pathStderr = getTempfile('readline-sync.stderr'), + pathExit = getTempfile('readline-sync.exit'), + pathDone = getTempfile('readline-sync.done'), + crypto = require('crypto'), + hostArgs, shellPath, shellArgs, exitCode, extMessage, shasum, decipher, password; + + shasum = crypto.createHash(ALGORITHM_HASH); + shasum.update('' + process.pid + (salt++) + Math.random()); + password = shasum.digest('hex'); + decipher = crypto.createDecipher(ALGORITHM_CIPHER, password); + + hostArgs = getHostArgs(options); + if (IS_WIN) { + shellPath = process.env.ComSpec || 'cmd.exe'; + process.env.Q = '"'; // The quote (") that isn't escaped. + // `()` for ignore space by echo + shellArgs = ['/V:ON', '/S', '/C', + '(%Q%' + shellPath + '%Q% /V:ON /S /C %Q%' + /* ESLint bug? */ // eslint-disable-line no-path-concat + '%Q%' + extHostPath + '%Q%' + + hostArgs.map(function(arg) { return ' %Q%' + arg + '%Q%'; }).join('') + + ' & (echo !ERRORLEVEL!)>%Q%' + pathExit + '%Q%%Q%) 2>%Q%' + pathStderr + '%Q%' + + ' |%Q%' + process.execPath + '%Q% %Q%' + __dirname + '\\encrypt.js%Q%' + + ' %Q%' + ALGORITHM_CIPHER + '%Q% %Q%' + password + '%Q%' + + ' >%Q%' + pathStdout + '%Q%' + + ' & (echo 1)>%Q%' + pathDone + '%Q%']; + } else { + shellPath = '/bin/sh'; + shellArgs = ['-c', + // Use `()`, not `{}` for `-c` (text param) + '("' + extHostPath + '"' + /* ESLint bug? */ // eslint-disable-line no-path-concat + hostArgs.map(function(arg) { return " '" + arg.replace(/'/g, "'\\''") + "'"; }).join('') + + '; echo $?>"' + pathExit + '") 2>"' + pathStderr + '"' + + ' |"' + process.execPath + '" "' + __dirname + '/encrypt.js"' + + ' "' + ALGORITHM_CIPHER + '" "' + password + '"' + + ' >"' + pathStdout + '"' + + '; echo 1 >"' + pathDone + '"']; + } + if (_DBG_checkMethod) { _DBG_checkMethod('_execFileSync', hostArgs); } + try { + childProc.spawn(shellPath, shellArgs, execOptions); + } catch (e) { + res.error = new Error(e.message); + res.error.method = '_execFileSync - spawn'; + res.error.program = shellPath; + res.error.args = shellArgs; + } + + while (fs.readFileSync(pathDone, {encoding: options.encoding}).trim() !== '1') {} // eslint-disable-line no-empty + if ((exitCode = + fs.readFileSync(pathExit, {encoding: options.encoding}).trim()) === '0') { + res.input = + decipher.update(fs.readFileSync(pathStdout, {encoding: 'binary'}), + 'hex', options.encoding) + + decipher.final(options.encoding); + } else { + extMessage = fs.readFileSync(pathStderr, {encoding: options.encoding}).trim(); + res.error = new Error(DEFAULT_ERR_MSG + (extMessage ? '\n' + extMessage : '')); + res.error.method = '_execFileSync'; + res.error.program = shellPath; + res.error.args = shellArgs; + res.error.extMessage = extMessage; + res.error.exitCode = +exitCode; + } + + fs.unlinkSync(pathStdout); + fs.unlinkSync(pathStderr); + fs.unlinkSync(pathExit); + fs.unlinkSync(pathDone); + + return res; +} + +function readlineExt(options) { + var res = {}, + execOptions = {env: process.env, encoding: options.encoding}, + hostArgs, extMessage; + + if (!extHostPath) { + if (IS_WIN) { + if (process.env.PSModulePath) { // Windows PowerShell + extHostPath = 'powershell.exe'; + extHostArgs = ['-ExecutionPolicy', 'Bypass', + '-File', __dirname + '\\read.ps1']; // eslint-disable-line no-path-concat + } else { // Windows Script Host + extHostPath = 'cscript.exe'; + extHostArgs = ['//nologo', __dirname + '\\read.cs.js']; // eslint-disable-line no-path-concat + } + } else { + extHostPath = '/bin/sh'; + extHostArgs = [__dirname + '/read.sh']; // eslint-disable-line no-path-concat + } + } + if (IS_WIN && !process.env.PSModulePath) { // Windows Script Host + // ScriptPW (Win XP and Server2003) needs TTY stream as STDIN. + // In this case, If STDIN isn't TTY, an error is thrown. + execOptions.stdio = [process.stdin]; + } + + if (childProc.execFileSync) { + hostArgs = getHostArgs(options); + if (_DBG_checkMethod) { _DBG_checkMethod('execFileSync', hostArgs); } + try { + res.input = childProc.execFileSync(extHostPath, hostArgs, execOptions); + } catch (e) { // non-zero exit code + extMessage = e.stderr ? (e.stderr + '').trim() : ''; + res.error = new Error(DEFAULT_ERR_MSG + (extMessage ? '\n' + extMessage : '')); + res.error.method = 'execFileSync'; + res.error.program = extHostPath; + res.error.args = hostArgs; + res.error.extMessage = extMessage; + res.error.exitCode = e.status; + res.error.code = e.code; + res.error.signal = e.signal; + } + } else { + res = _execFileSync(options, execOptions); + } + if (!res.error) { + res.input = res.input.replace(/^\s*'|'\s*$/g, ''); + options.display = ''; + } + + return res; +} + +/* + display: string + displayOnly: boolean + keyIn: boolean + hideEchoBack: boolean + mask: string + limit: string (pattern) + caseSensitive: boolean + keepWhitespace: boolean + encoding, bufferSize, print +*/ +function _readlineSync(options) { + var input = '', + displaySave = options.display, + silent = !options.display && options.keyIn && options.hideEchoBack && !options.mask; + + function tryExt() { + var res = readlineExt(options); + if (res.error) { throw res.error; } + return res.input; + } + + if (_DBG_checkOptions) { _DBG_checkOptions(options); } + + (function() { // open TTY + var fsB, constants, verNum; + + function getFsB() { + if (!fsB) { + fsB = process.binding('fs'); // For raw device path + constants = process.binding('constants'); + // for v6.3.0+ + constants = constants && constants.fs && typeof constants.fs.O_RDWR === 'number' + ? constants.fs : constants; + } + return fsB; + } + + if (typeof fdR !== 'string') { return; } + fdR = null; + + if (IS_WIN) { + // iojs-v2.3.2+ input stream can't read first line. (#18) + // ** Don't get process.stdin before check! ** + // Fixed v5.1.0 + // Fixed v4.2.4 + // It regressed again in v5.6.0, it is fixed in v6.2.0. + verNum = (function(ver) { // getVerNum + var nums = ver.replace(/^\D+/, '').split('.'); + var verNum = 0; + if ((nums[0] = +nums[0])) { verNum += nums[0] * 10000; } + if ((nums[1] = +nums[1])) { verNum += nums[1] * 100; } + if ((nums[2] = +nums[2])) { verNum += nums[2]; } + return verNum; + })(process.version); + if (!(verNum >= 20302 && verNum < 40204 || verNum >= 50000 && verNum < 50100 || verNum >= 50600 && verNum < 60200) && + process.stdin.isTTY) { + process.stdin.pause(); + fdR = process.stdin.fd; + ttyR = process.stdin._handle; + } else { + try { + // The stream by fs.openSync('\\\\.\\CON', 'r') can't switch to raw mode. + // 'CONIN$' might fail on XP, 2000, 7 (x86). + fdR = getFsB().open('CONIN$', constants.O_RDWR, parseInt('0666', 8)); + ttyR = new TTY(fdR, true); + } catch (e) { /* ignore */ } + } + + if (process.stdout.isTTY) { + fdW = process.stdout.fd; + } else { + try { + fdW = fs.openSync('\\\\.\\CON', 'w'); + } catch (e) { /* ignore */ } + if (typeof fdW !== 'number') { // Retry + try { + fdW = getFsB().open('CONOUT$', constants.O_RDWR, parseInt('0666', 8)); + } catch (e) { /* ignore */ } + } + } + + } else { + if (process.stdin.isTTY) { + process.stdin.pause(); + try { + fdR = fs.openSync('/dev/tty', 'r'); // device file, not process.stdin + ttyR = process.stdin._handle; + } catch (e) { /* ignore */ } + } else { + // Node.js v0.12 read() fails. + try { + fdR = fs.openSync('/dev/tty', 'r'); + ttyR = new TTY(fdR, false); + } catch (e) { /* ignore */ } + } + + if (process.stdout.isTTY) { + fdW = process.stdout.fd; + } else { + try { + fdW = fs.openSync('/dev/tty', 'w'); + } catch (e) { /* ignore */ } + } + } + })(); + + (function() { // try read + var isCooked = !options.hideEchoBack && !options.keyIn, + atEol, limit, buffer, reqSize, readSize, chunk, line; + rawInput = ''; + + // Node.js v0.10- returns an error if same mode is set. + function setRawMode(mode) { + if (mode === isRawMode) { return true; } + if (ttyR.setRawMode(mode) !== 0) { return false; } + isRawMode = mode; + return true; + } + + if (_DBG_useExt || !ttyR || + typeof fdW !== 'number' && (options.display || !isCooked)) { + input = tryExt(); + return; + } + + if (options.display) { + fs.writeSync(fdW, options.display); + options.display = ''; + } + if (options.displayOnly) { return; } + + if (!setRawMode(!isCooked)) { + input = tryExt(); + return; + } + + reqSize = options.keyIn ? 1 : options.bufferSize; + // Check `allocUnsafe` to make sure of the new API. + buffer = Buffer.allocUnsafe && Buffer.alloc ? Buffer.alloc(reqSize) : new Buffer(reqSize); + + if (options.keyIn && options.limit) { + limit = new RegExp('[^' + options.limit + ']', + 'g' + (options.caseSensitive ? '' : 'i')); + } + + while (true) { + readSize = 0; + try { + readSize = fs.readSync(fdR, buffer, 0, reqSize); + } catch (e) { + if (e.code !== 'EOF') { + setRawMode(false); + input += tryExt(); + return; + } + } + if (readSize > 0) { + chunk = buffer.toString(options.encoding, 0, readSize); + rawInput += chunk; + } else { + chunk = '\n'; + rawInput += String.fromCharCode(0); + } + + if (chunk && typeof (line = (chunk.match(/^(.*?)[\r\n]/) || [])[1]) === 'string') { + chunk = line; + atEol = true; + } + + // other ctrl-chars + // eslint-disable-next-line no-control-regex + if (chunk) { chunk = chunk.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, ''); } + if (chunk && limit) { chunk = chunk.replace(limit, ''); } + + if (chunk) { + if (!isCooked) { + if (!options.hideEchoBack) { + fs.writeSync(fdW, chunk); + } else if (options.mask) { + fs.writeSync(fdW, (new Array(chunk.length + 1)).join(options.mask)); + } + } + input += chunk; + } + + if (!options.keyIn && atEol || + options.keyIn && input.length >= reqSize) { break; } + } + + if (!isCooked && !silent) { fs.writeSync(fdW, '\n'); } + setRawMode(false); + })(); + + if (options.print && !silent) { + options.print( + displaySave + ( + options.displayOnly ? '' : ( + options.hideEchoBack ? (new Array(input.length + 1)).join(options.mask) : input + ) + '\n' // must at least write '\n' + ), + options.encoding); + } + + return options.displayOnly ? '' : + (lastInput = options.keepWhitespace || options.keyIn ? input : input.trim()); +} + +function flattenArray(array, validator) { + var flatArray = []; + function _flattenArray(array) { + if (array == null) { return; } + if (Array.isArray(array)) { + array.forEach(_flattenArray); + } else if (!validator || validator(array)) { + flatArray.push(array); + } + } + _flattenArray(array); + return flatArray; +} + +function escapePattern(pattern) { + return pattern.replace(/[\x00-\x7f]/g, // eslint-disable-line no-control-regex + function(s) { return '\\x' + ('00' + s.charCodeAt().toString(16)).substr(-2); }); +} + +// margeOptions(options1, options2 ... ) +// margeOptions(true, options1, options2 ... ) +// arg1=true : Start from defaultOptions and pick elements of that. +function margeOptions() { + var optionsList = Array.prototype.slice.call(arguments), + optionNames, fromDefault; + + if (optionsList.length && typeof optionsList[0] === 'boolean') { + fromDefault = optionsList.shift(); + if (fromDefault) { + optionNames = Object.keys(defaultOptions); + optionsList.unshift(defaultOptions); + } + } + + return optionsList.reduce(function(options, optionsPart) { + if (optionsPart == null) { return options; } + + // ======== DEPRECATED ======== + if (optionsPart.hasOwnProperty('noEchoBack') && + !optionsPart.hasOwnProperty('hideEchoBack')) { + optionsPart.hideEchoBack = optionsPart.noEchoBack; + delete optionsPart.noEchoBack; + } + if (optionsPart.hasOwnProperty('noTrim') && + !optionsPart.hasOwnProperty('keepWhitespace')) { + optionsPart.keepWhitespace = optionsPart.noTrim; + delete optionsPart.noTrim; + } + // ======== /DEPRECATED ======== + + if (!fromDefault) { optionNames = Object.keys(optionsPart); } + optionNames.forEach(function(optionName) { + var value; + if (!optionsPart.hasOwnProperty(optionName)) { return; } + value = optionsPart[optionName]; + /* eslint-disable no-multi-spaces */ + switch (optionName) { + // _readlineSync <- * * -> defaultOptions + // ================ string + case 'mask': // * * + case 'limitMessage': // * + case 'defaultInput': // * + case 'encoding': // * * + value = value != null ? value + '' : ''; + if (value && optionName !== 'limitMessage') { value = value.replace(/[\r\n]/g, ''); } + options[optionName] = value; + break; + // ================ number(int) + case 'bufferSize': // * * + if (!isNaN(value = parseInt(value, 10)) && typeof value === 'number') { + options[optionName] = value; // limited updating (number is needed) + } + break; + // ================ boolean + case 'displayOnly': // * + case 'keyIn': // * + case 'hideEchoBack': // * * + case 'caseSensitive': // * * + case 'keepWhitespace': // * * + case 'history': // * + case 'cd': // * + options[optionName] = !!value; + break; + // ================ array + case 'limit': // * * to string for readlineExt + case 'trueValue': // * + case 'falseValue': // * + options[optionName] = flattenArray(value, function(value) { + var type = typeof value; + return type === 'string' || type === 'number' || + type === 'function' || value instanceof RegExp; + }).map(function(value) { + return typeof value === 'string' ? value.replace(/[\r\n]/g, '') : value; + }); + break; + // ================ function + case 'print': // * * + case 'phContent': // * + case 'preCheck': // * + options[optionName] = typeof value === 'function' ? value : void 0; + break; + // ================ other + case 'prompt': // * + case 'display': // * + options[optionName] = value != null ? value : ''; + break; + // no default + } + /* eslint-enable no-multi-spaces */ + }); + return options; + }, {}); +} + +function isMatched(res, comps, caseSensitive) { + return comps.some(function(comp) { + var type = typeof comp; + return type === 'string' + ? (caseSensitive ? res === comp : res.toLowerCase() === comp.toLowerCase()) : + type === 'number' ? parseFloat(res) === comp : + type === 'function' ? comp(res) : + comp instanceof RegExp ? comp.test(res) : false; + }); +} + +function replaceHomePath(path, expand) { + var homePath = pathUtil.normalize( + IS_WIN ? (process.env.HOMEDRIVE || '') + (process.env.HOMEPATH || '') : + process.env.HOME || '').replace(/[/\\]+$/, ''); + path = pathUtil.normalize(path); + return expand ? path.replace(/^~(?=\/|\\|$)/, homePath) : + path.replace(new RegExp('^' + escapePattern(homePath) + + '(?=\\/|\\\\|$)', IS_WIN ? 'i' : ''), '~'); +} + +function replacePlaceholder(text, generator) { + var PTN_INNER = '(?:\\(([\\s\\S]*?)\\))?(\\w+|.-.)(?:\\(([\\s\\S]*?)\\))?', + rePlaceholder = new RegExp('(\\$)?(\\$<' + PTN_INNER + '>)', 'g'), + rePlaceholderCompat = new RegExp('(\\$)?(\\$\\{' + PTN_INNER + '\\})', 'g'); + + function getPlaceholderText(s, escape, placeholder, pre, param, post) { + var text; + return escape || typeof (text = generator(param)) !== 'string' ? placeholder : + text ? (pre || '') + text + (post || '') : ''; + } + + return text.replace(rePlaceholder, getPlaceholderText) + .replace(rePlaceholderCompat, getPlaceholderText); +} + +function array2charlist(array, caseSensitive, collectSymbols) { + var group = [], + groupClass = -1, + charCode = 0, + symbols = '', + values, suppressed; + function addGroup(groups, group) { + if (group.length > 3) { // ellipsis + groups.push(group[0] + '...' + group[group.length - 1]); + suppressed = true; + } else if (group.length) { + groups = groups.concat(group); + } + return groups; + } + + values = array.reduce(function(chars, value) { + return chars.concat((value + '').split('')); + }, []).reduce(function(groups, curChar) { + var curGroupClass, curCharCode; + if (!caseSensitive) { curChar = curChar.toLowerCase(); } + curGroupClass = /^\d$/.test(curChar) ? 1 : + /^[A-Z]$/.test(curChar) ? 2 : /^[a-z]$/.test(curChar) ? 3 : 0; + if (collectSymbols && curGroupClass === 0) { + symbols += curChar; + } else { + curCharCode = curChar.charCodeAt(0); + if (curGroupClass && curGroupClass === groupClass && + curCharCode === charCode + 1) { + group.push(curChar); + } else { + groups = addGroup(groups, group); + group = [curChar]; + groupClass = curGroupClass; + } + charCode = curCharCode; + } + return groups; + }, []); + values = addGroup(values, group); // last group + if (symbols) { values.push(symbols); suppressed = true; } + return {values: values, suppressed: suppressed}; +} + +function joinChunks(chunks, suppressed) { + return chunks.join(chunks.length > 2 ? ', ' : suppressed ? ' / ' : '/'); +} + +function getPhContent(param, options) { + var resCharlist = {}, + text, values, arg; + if (options.phContent) { + text = options.phContent(param, options); + } + if (typeof text !== 'string') { + switch (param) { + case 'hideEchoBack': + case 'mask': + case 'defaultInput': + case 'caseSensitive': + case 'keepWhitespace': + case 'encoding': + case 'bufferSize': + case 'history': + case 'cd': + text = !options.hasOwnProperty(param) ? '' : + typeof options[param] === 'boolean' ? (options[param] ? 'on' : 'off') : + options[param] + ''; + break; + // case 'prompt': + // case 'query': + // case 'display': + // text = options.hasOwnProperty('displaySrc') ? options.displaySrc + '' : ''; + // break; + case 'limit': + case 'trueValue': + case 'falseValue': + values = options[options.hasOwnProperty(param + 'Src') ? param + 'Src' : param]; + if (options.keyIn) { // suppress + resCharlist = array2charlist(values, options.caseSensitive); + values = resCharlist.values; + } else { + values = values.filter(function(value) { + var type = typeof value; + return type === 'string' || type === 'number'; + }); + } + text = joinChunks(values, resCharlist.suppressed); + break; + case 'limitCount': + case 'limitCountNotZero': + text = options[options.hasOwnProperty('limitSrc') ? 'limitSrc' : 'limit'].length; + text = text || param !== 'limitCountNotZero' ? text + '' : ''; + break; + case 'lastInput': + text = lastInput; + break; + case 'cwd': + case 'CWD': + case 'cwdHome': + text = process.cwd(); + if (param === 'CWD') { + text = pathUtil.basename(text); + } else if (param === 'cwdHome') { + text = replaceHomePath(text); + } + break; + case 'date': + case 'time': + case 'localeDate': + case 'localeTime': + text = (new Date())['to' + + param.replace(/^./, function(str) { return str.toUpperCase(); }) + + 'String'](); + break; + default: // with arg + if (typeof (arg = (param.match(/^history_m(\d+)$/) || [])[1]) === 'string') { + text = inputHistory[inputHistory.length - arg] || ''; + } + } + } + return text; +} + +function getPhCharlist(param) { + var matches = /^(.)-(.)$/.exec(param), + text = '', + from, to, code, step; + if (!matches) { return null; } + from = matches[1].charCodeAt(0); + to = matches[2].charCodeAt(0); + step = from < to ? 1 : -1; + for (code = from; code !== to + step; code += step) { text += String.fromCharCode(code); } + return text; +} + +// cmd "arg" " a r g " "" 'a"r"g' "a""rg" "arg +function parseCl(cl) { + var reToken = new RegExp(/(\s*)(?:("|')(.*?)(?:\2|$)|(\S+))/g), + taken = '', + args = [], + matches, part; + cl = cl.trim(); + while ((matches = reToken.exec(cl))) { + part = matches[3] || matches[4] || ''; + if (matches[1]) { + args.push(taken); + taken = ''; + } + taken += part; + } + if (taken) { args.push(taken); } + return args; +} + +function toBool(res, options) { + return ( + (options.trueValue.length && + isMatched(res, options.trueValue, options.caseSensitive)) ? true : + (options.falseValue.length && + isMatched(res, options.falseValue, options.caseSensitive)) ? false : res); +} + +function getValidLine(options) { + var res, forceNext, limitMessage, + matches, histInput, args, resCheck; + + function _getPhContent(param) { return getPhContent(param, options); } + function addDisplay(text) { options.display += (/[^\r\n]$/.test(options.display) ? '\n' : '') + text; } + + options.limitSrc = options.limit; + options.displaySrc = options.display; + options.limit = ''; // for readlineExt + options.display = replacePlaceholder(options.display + '', _getPhContent); + + while (true) { + res = _readlineSync(options); + forceNext = false; + limitMessage = ''; + + if (options.defaultInput && !res) { res = options.defaultInput; } + + if (options.history) { + if ((matches = /^\s*!(?:!|-1)(:p)?\s*$/.exec(res))) { // `!!` `!-1` +`:p` + histInput = inputHistory[0] || ''; + if (matches[1]) { // only display + forceNext = true; + } else { // replace input + res = histInput; + } + // Show it even if it is empty (NL only). + addDisplay(histInput + '\n'); + if (!forceNext) { // Loop may break + options.displayOnly = true; + _readlineSync(options); + options.displayOnly = false; + } + } else if (res && res !== inputHistory[inputHistory.length - 1]) { + inputHistory = [res]; + } + } + + if (!forceNext && options.cd && res) { + args = parseCl(res); + switch (args[0].toLowerCase()) { + case 'cd': + if (args[1]) { + try { + process.chdir(replaceHomePath(args[1], true)); + } catch (e) { + addDisplay(e + ''); + } + } + forceNext = true; + break; + case 'pwd': + addDisplay(process.cwd()); + forceNext = true; + break; + // no default + } + } + + if (!forceNext && options.preCheck) { + resCheck = options.preCheck(res, options); + res = resCheck.res; + if (resCheck.forceNext) { forceNext = true; } // Don't switch to false. + } + + if (!forceNext) { + if (!options.limitSrc.length || + isMatched(res, options.limitSrc, options.caseSensitive)) { break; } + if (options.limitMessage) { + limitMessage = replacePlaceholder(options.limitMessage, _getPhContent); + } + } + + addDisplay((limitMessage ? limitMessage + '\n' : '') + + replacePlaceholder(options.displaySrc + '', _getPhContent)); + } + return toBool(res, options); +} + +// for dev +exports._DBG_set_useExt = function(val) { _DBG_useExt = val; }; +exports._DBG_set_checkOptions = function(val) { _DBG_checkOptions = val; }; +exports._DBG_set_checkMethod = function(val) { _DBG_checkMethod = val; }; +exports._DBG_clearHistory = function() { lastInput = ''; inputHistory = []; }; + +// ------------------------------------ + +exports.setDefaultOptions = function(options) { + defaultOptions = margeOptions(true, options); + return margeOptions(true); // copy +}; + +exports.question = function(query, options) { + /* eslint-disable key-spacing */ + return getValidLine(margeOptions(margeOptions(true, options), { + display: query + })); + /* eslint-enable key-spacing */ +}; + +exports.prompt = function(options) { + var readOptions = margeOptions(true, options); + readOptions.display = readOptions.prompt; + return getValidLine(readOptions); +}; + +exports.keyIn = function(query, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions(margeOptions(true, options), { + display: query, + keyIn: true, + keepWhitespace: true + }); + /* eslint-enable key-spacing */ + + // char list + readOptions.limitSrc = readOptions.limit.filter(function(value) { + var type = typeof value; + return type === 'string' || type === 'number'; + }).map(function(text) { + return replacePlaceholder(text + '', getPhCharlist); + }); + // pattern + readOptions.limit = escapePattern(readOptions.limitSrc.join('')); + + ['trueValue', 'falseValue'].forEach(function(optionName) { + readOptions[optionName] = readOptions[optionName].reduce(function(comps, comp) { + var type = typeof comp; + if (type === 'string' || type === 'number') { + comps = comps.concat((comp + '').split('')); + } else { comps.push(comp); } + return comps; + }, []); + }); + + readOptions.display = replacePlaceholder(readOptions.display + '', + function(param) { return getPhContent(param, readOptions); }); + + return toBool(_readlineSync(readOptions), readOptions); +}; + +// ------------------------------------ + +exports.questionEMail = function(query, options) { + if (query == null) { query = 'Input e-mail address: '; } + /* eslint-disable key-spacing */ + return exports.question(query, margeOptions({ + // -------- default + hideEchoBack: false, + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address + limit: /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, + limitMessage: 'Input valid e-mail address, please.', + trueValue: null, + falseValue: null + }, options, { + // -------- forced + keepWhitespace: false, + cd: false + })); + /* eslint-enable key-spacing */ +}; + +exports.questionNewPassword = function(query, options) { + /* eslint-disable key-spacing */ + var resCharlist, min, max, + readOptions = margeOptions({ + // -------- default + hideEchoBack: true, + mask: '*', + limitMessage: 'It can include: $\n' + + 'And the length must be: $', + trueValue: null, + falseValue: null, + caseSensitive: true + }, options, { + // -------- forced + history: false, + cd: false, + // limit (by charlist etc.), + phContent: function(param) { + return param === 'charlist' ? resCharlist.text : + param === 'length' ? min + '...' + max : null; + } + }), + // added: charlist, min, max, confirmMessage, unmatchMessage + charlist, confirmMessage, unmatchMessage, + limit, limitMessage, res1, res2; + /* eslint-enable key-spacing */ + options = options || {}; + + charlist = replacePlaceholder( + options.charlist ? options.charlist + '' : '$', getPhCharlist); + if (isNaN(min = parseInt(options.min, 10)) || typeof min !== 'number') { min = 12; } + if (isNaN(max = parseInt(options.max, 10)) || typeof max !== 'number') { max = 24; } + limit = new RegExp('^[' + escapePattern(charlist) + + ']{' + min + ',' + max + '}$'); + resCharlist = array2charlist([charlist], readOptions.caseSensitive, true); + resCharlist.text = joinChunks(resCharlist.values, resCharlist.suppressed); + + confirmMessage = options.confirmMessage != null ? options.confirmMessage : + 'Reinput a same one to confirm it: '; + unmatchMessage = options.unmatchMessage != null ? options.unmatchMessage : + 'It differs from first one.' + + ' Hit only the Enter key if you want to retry from first one.'; + + if (query == null) { query = 'Input new password: '; } + + limitMessage = readOptions.limitMessage; + while (!res2) { + readOptions.limit = limit; + readOptions.limitMessage = limitMessage; + res1 = exports.question(query, readOptions); + + readOptions.limit = [res1, '']; + readOptions.limitMessage = unmatchMessage; + res2 = exports.question(confirmMessage, readOptions); + } + + return res1; +}; + +function _questionNum(query, options, parser) { + var validValue; + function getValidValue(value) { + validValue = parser(value); + return !isNaN(validValue) && typeof validValue === 'number'; + } + /* eslint-disable key-spacing */ + exports.question(query, margeOptions({ + // -------- default + limitMessage: 'Input valid number, please.' + }, options, { + // -------- forced + limit: getValidValue, + cd: false + // trueValue, falseValue, caseSensitive, keepWhitespace don't work. + })); + /* eslint-enable key-spacing */ + return validValue; +} +exports.questionInt = function(query, options) { + return _questionNum(query, options, function(value) { return parseInt(value, 10); }); +}; +exports.questionFloat = function(query, options) { + return _questionNum(query, options, parseFloat); +}; + +exports.questionPath = function(query, options) { + /* eslint-disable key-spacing */ + var error = '', + validPath, // before readOptions + readOptions = margeOptions({ + // -------- default + hideEchoBack: false, + limitMessage: '$Input valid path, please.' + + '$<( Min:)min>$<( Max:)max>', + history: true, + cd: true + }, options, { + // -------- forced + keepWhitespace: false, + limit: function(value) { + var exists, stat, res; + value = replaceHomePath(value, true); + error = ''; // for validate + // mkdir -p + function mkdirParents(dirPath) { + dirPath.split(/\/|\\/).reduce(function(parents, dir) { + var path = pathUtil.resolve((parents += dir + pathUtil.sep)); + if (!fs.existsSync(path)) { + fs.mkdirSync(path); + } else if (!fs.statSync(path).isDirectory()) { + throw new Error('Non directory already exists: ' + path); + } + return parents; + }, ''); + } + + try { + exists = fs.existsSync(value); + validPath = exists ? fs.realpathSync(value) : pathUtil.resolve(value); + // options.exists default: true, not-bool: no-check + if (!options.hasOwnProperty('exists') && !exists || + typeof options.exists === 'boolean' && options.exists !== exists) { + error = (exists ? 'Already exists' : 'No such file or directory') + + ': ' + validPath; + return false; + } + if (!exists && options.create) { + if (options.isDirectory) { + mkdirParents(validPath); + } else { + mkdirParents(pathUtil.dirname(validPath)); + fs.closeSync(fs.openSync(validPath, 'w')); // touch + } + validPath = fs.realpathSync(validPath); + } + if (exists && (options.min || options.max || + options.isFile || options.isDirectory)) { + stat = fs.statSync(validPath); + // type check first (directory has zero size) + if (options.isFile && !stat.isFile()) { + error = 'Not file: ' + validPath; + return false; + } else if (options.isDirectory && !stat.isDirectory()) { + error = 'Not directory: ' + validPath; + return false; + } else if (options.min && stat.size < +options.min || + options.max && stat.size > +options.max) { + error = 'Size ' + stat.size + ' is out of range: ' + validPath; + return false; + } + } + if (typeof options.validate === 'function' && + (res = options.validate(validPath)) !== true) { + if (typeof res === 'string') { error = res; } + return false; + } + } catch (e) { + error = e + ''; + return false; + } + return true; + }, + // trueValue, falseValue, caseSensitive don't work. + phContent: function(param) { + return param === 'error' ? error : + param !== 'min' && param !== 'max' ? null : + options.hasOwnProperty(param) ? options[param] + '' : ''; + } + }); + // added: exists, create, min, max, isFile, isDirectory, validate + /* eslint-enable key-spacing */ + options = options || {}; + + if (query == null) { query = 'Input path (you can "cd" and "pwd"): '; } + + exports.question(query, readOptions); + return validPath; +}; + +// props: preCheck, args, hRes, limit +function getClHandler(commandHandler, options) { + var clHandler = {}, + hIndex = {}; + if (typeof commandHandler === 'object') { + Object.keys(commandHandler).forEach(function(cmd) { + if (typeof commandHandler[cmd] === 'function') { + hIndex[options.caseSensitive ? cmd : cmd.toLowerCase()] = commandHandler[cmd]; + } + }); + clHandler.preCheck = function(res) { + var cmdKey; + clHandler.args = parseCl(res); + cmdKey = clHandler.args[0] || ''; + if (!options.caseSensitive) { cmdKey = cmdKey.toLowerCase(); } + clHandler.hRes = + cmdKey !== '_' && hIndex.hasOwnProperty(cmdKey) + ? hIndex[cmdKey].apply(res, clHandler.args.slice(1)) : + hIndex.hasOwnProperty('_') ? hIndex._.apply(res, clHandler.args) : null; + return {res: res, forceNext: false}; + }; + if (!hIndex.hasOwnProperty('_')) { + clHandler.limit = function() { // It's called after preCheck. + var cmdKey = clHandler.args[0] || ''; + if (!options.caseSensitive) { cmdKey = cmdKey.toLowerCase(); } + return hIndex.hasOwnProperty(cmdKey); + }; + } + } else { + clHandler.preCheck = function(res) { + clHandler.args = parseCl(res); + clHandler.hRes = typeof commandHandler === 'function' + ? commandHandler.apply(res, clHandler.args) : true; // true for break loop + return {res: res, forceNext: false}; + }; + } + return clHandler; +} + +exports.promptCL = function(commandHandler, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions({ + // -------- default + hideEchoBack: false, + limitMessage: 'Requested command is not available.', + caseSensitive: false, + history: true + }, options), + // -------- forced + // trueValue, falseValue, keepWhitespace don't work. + // preCheck, limit (by clHandler) + clHandler = getClHandler(commandHandler, readOptions); + /* eslint-enable key-spacing */ + readOptions.limit = clHandler.limit; + readOptions.preCheck = clHandler.preCheck; + exports.prompt(readOptions); + return clHandler.args; +}; + +exports.promptLoop = function(inputHandler, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions({ + // -------- default + hideEchoBack: false, + trueValue: null, + falseValue: null, + caseSensitive: false, + history: true + }, options); + /* eslint-enable key-spacing */ + while (true) { if (inputHandler(exports.prompt(readOptions))) { break; } } + // return; // nothing is returned +}; + +exports.promptCLLoop = function(commandHandler, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions({ + // -------- default + hideEchoBack: false, + limitMessage: 'Requested command is not available.', + caseSensitive: false, + history: true + }, options), + // -------- forced + // trueValue, falseValue, keepWhitespace don't work. + // preCheck, limit (by clHandler) + clHandler = getClHandler(commandHandler, readOptions); + /* eslint-enable key-spacing */ + readOptions.limit = clHandler.limit; + readOptions.preCheck = clHandler.preCheck; + while (true) { + exports.prompt(readOptions); + if (clHandler.hRes) { break; } + } + // return; // nothing is returned +}; + +exports.promptSimShell = function(options) { + /* eslint-disable key-spacing */ + return exports.prompt(margeOptions({ + // -------- default + hideEchoBack: false, + history: true + }, options, { + // -------- forced + prompt: (function() { + return IS_WIN ? '$>' : + // 'user@host:cwd$ ' + (process.env.USER || '') + + (process.env.HOSTNAME ? '@' + process.env.HOSTNAME.replace(/\..*$/, '') : '') + + ':$$ '; + })() + })); + /* eslint-enable key-spacing */ +}; + +function _keyInYN(query, options, limit) { + var res; + if (query == null) { query = 'Are you sure? '; } + if ((!options || options.guide !== false) && (query += '')) { + query = query.replace(/\s*:?\s*$/, '') + ' [y/n]: '; + } + /* eslint-disable key-spacing */ + res = exports.keyIn(query, margeOptions(options, { + // -------- forced + hideEchoBack: false, + limit: limit, + trueValue: 'y', + falseValue: 'n', + caseSensitive: false + // mask doesn't work. + })); + // added: guide + /* eslint-enable key-spacing */ + return typeof res === 'boolean' ? res : ''; +} +exports.keyInYN = function(query, options) { return _keyInYN(query, options); }; +exports.keyInYNStrict = function(query, options) { return _keyInYN(query, options, 'yn'); }; + +exports.keyInPause = function(query, options) { + if (query == null) { query = 'Continue...'; } + if ((!options || options.guide !== false) && (query += '')) { + query = query.replace(/\s+$/, '') + ' (Hit any key)'; + } + /* eslint-disable key-spacing */ + exports.keyIn(query, margeOptions({ + // -------- default + limit: null + }, options, { + // -------- forced + hideEchoBack: true, + mask: '' + })); + // added: guide + /* eslint-enable key-spacing */ + // return; // nothing is returned +}; + +exports.keyInSelect = function(items, query, options) { + /* eslint-disable key-spacing */ + var readOptions = margeOptions({ + // -------- default + hideEchoBack: false + }, options, { + // -------- forced + trueValue: null, + falseValue: null, + caseSensitive: false, + // limit (by items), + phContent: function(param) { + return param === 'itemsCount' ? items.length + '' : + param === 'firstItem' ? (items[0] + '').trim() : + param === 'lastItem' ? (items[items.length - 1] + '').trim() : null; + } + }), + // added: guide, cancel + keylist = '', + key2i = {}, + charCode = 49 /* '1' */, + display = '\n'; + /* eslint-enable key-spacing */ + if (!Array.isArray(items) || !items.length || items.length > 35) { + throw '`items` must be Array (max length: 35).'; + } + + items.forEach(function(item, i) { + var key = String.fromCharCode(charCode); + keylist += key; + key2i[key] = i; + display += '[' + key + '] ' + (item + '').trim() + '\n'; + charCode = charCode === 57 /* '9' */ ? 97 /* 'a' */ : charCode + 1; + }); + if (!options || options.cancel !== false) { + keylist += '0'; + key2i['0'] = -1; + display += '[0] ' + + (options && options.cancel != null && typeof options.cancel !== 'boolean' + ? (options.cancel + '').trim() : 'CANCEL') + '\n'; + } + readOptions.limit = keylist; + display += '\n'; + + if (query == null) { query = 'Choose one from list: '; } + if ((query += '')) { + if (!options || options.guide !== false) { + query = query.replace(/\s*:?\s*$/, '') + ' [$]: '; + } + display += query; + } + + return key2i[exports.keyIn(display, readOptions).toLowerCase()]; +}; + +exports.getRawInput = function() { return rawInput; }; + +// ======== DEPRECATED ======== +function _setOption(optionName, args) { + var options; + if (args.length) { options = {}; options[optionName] = args[0]; } + return exports.setDefaultOptions(options)[optionName]; +} +exports.setPrint = function() { return _setOption('print', arguments); }; +exports.setPrompt = function() { return _setOption('prompt', arguments); }; +exports.setEncoding = function() { return _setOption('encoding', arguments); }; +exports.setMask = function() { return _setOption('mask', arguments); }; +exports.setBufferSize = function() { return _setOption('bufferSize', arguments); }; diff --git a/loops/exercises/node_modules/readline-sync/package.json b/loops/exercises/node_modules/readline-sync/package.json new file mode 100644 index 0000000000..c832e8e999 --- /dev/null +++ b/loops/exercises/node_modules/readline-sync/package.json @@ -0,0 +1,40 @@ +{ + "name": "readline-sync", + "version": "1.4.10", + "title": "readlineSync", + "description": "Synchronous Readline for interactively running to have a conversation with the user via a console(TTY).", + "keywords": [ + "readline", + "synchronous", + "interactive", + "prompt", + "question", + "password", + "cli", + "tty", + "command", + "repl", + "keyboard", + "wait", + "block" + ], + "main": "./lib/readline-sync.js", + "files": [ + "lib/*.@(js|ps1|sh)", + "README-Deprecated.md" + ], + "engines": { + "node": ">= 0.8.0" + }, + "homepage": "https://github.com/anseki/readline-sync", + "repository": { + "type": "git", + "url": "git://github.com/anseki/readline-sync.git" + }, + "bugs": "https://github.com/anseki/readline-sync/issues", + "license": "MIT", + "author": { + "name": "anseki", + "url": "https://github.com/anseki" + } +} diff --git a/loops/exercises/package-lock.json b/loops/exercises/package-lock.json new file mode 100644 index 0000000000..e43bf10327 --- /dev/null +++ b/loops/exercises/package-lock.json @@ -0,0 +1,29 @@ +{ + "name": "exercises", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "read-line": "^0.1.2", + "readline-sync": "^1.4.10" + } + }, + "node_modules/read-line": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/read-line/-/read-line-0.1.2.tgz", + "integrity": "sha512-nvCGsua+3EIxge4GSGHgF4e8VAtLqic9aQZWe7sra2Xk3p6xmzO2oruoJYleIZMLklDV1PGQ1wztUMaNeM9kVw==", + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/readline-sync": { + "version": "1.4.10", + "resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.10.tgz", + "integrity": "sha512-gNva8/6UAe8QYepIQH/jQ2qn91Qj0B9sYjMBBs3QOB8F2CXcKgLxQaJRP76sWVRQt+QU+8fAkCbCvjjMFu7Ycw==", + "engines": { + "node": ">= 0.8.0" + } + } + } +} diff --git a/loops/exercises/package.json b/loops/exercises/package.json new file mode 100644 index 0000000000..e39306e248 --- /dev/null +++ b/loops/exercises/package.json @@ -0,0 +1,6 @@ +{ + "dependencies": { + "read-line": "^0.1.2", + "readline-sync": "^1.4.10" + } +} diff --git a/loops/exercises/while-Loop-Exercises.js b/loops/exercises/while-Loop-Exercises.js index 53a8ce1250..ead9d0d96e 100644 --- a/loops/exercises/while-Loop-Exercises.js +++ b/loops/exercises/while-Loop-Exercises.js @@ -1,25 +1,40 @@ //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 startFuelLevel = 0 ; +let astronautsAboard = 0 ; +let 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 (startFuelLevel < 5000 || startFuelLevel > 30000 || isNaN(startFuelLevel)) { + startFuelLevel = input.question("Provide the starting fuel level between 5000 and 30000: "); +} - - +console.log("Starting fuel level:", startFuelLevel); //b. Use a second loop to query the user for the number of astronauts (up to a maximum of 7). Validate the entry. +while (astronautsAboard <= 0 || astronautsAboard > 7 || isNaN(astronautsAboard)) { + astronautsAboard = input.question("How many astronauts are onboard?: "); +} - - +console.log(`There are ${astronautsAboard} total astronauts onboard.`); //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 (startFuelLevel-100*astronautsAboard >= 0) { + shuttleAltitude += 50; + startFuelLevel -= 100*astronautsAboard; +} /*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.”*/ + +if (shuttleAltitude >= 2000) { + console.log(`The shuttle gained an altitude of ${shuttleAltitude} km. Orbit achieved!`) +} else { + console.log(`The shuttle gained an altitude of ${shuttleAltitude} km. Failed to reach orbit.`) +} ; + From 49ec0240670c592c4908fcb080b3ddadb88c2c9f Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Mon, 24 Jun 2024 19:43:34 -0500 Subject: [PATCH 15/32] solution for loops studio --- loops/studio/solution.js | 54 ++++++++++++++++++++++++++++------------ 1 file changed, 38 insertions(+), 16 deletions(-) diff --git a/loops/studio/solution.js b/loops/studio/solution.js index 4e21a9caa5..11636fcaf0 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 = { @@ -75,4 +97,4 @@ module.exports = { askForNumber: askForNumber, generatePassword: generatePassword, runProgram: runProgram -}; +}; \ No newline at end of file From 1d243091eb7e41798218492e9b3a0951a4caab30 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Thu, 27 Jun 2024 20:26:04 -0500 Subject: [PATCH 16/32] 1st submit with group --- functions/studio/studio-functions.js | 49 ++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/functions/studio/studio-functions.js b/functions/studio/studio-functions.js index d4c291ed1a..488a5a6043 100644 --- a/functions/studio/studio-functions.js +++ b/functions/studio/studio-functions.js @@ -9,6 +9,13 @@ // 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(toReverse){ +// return toReverse.split('').reverse().join(''); +//} + +//let myString = "This is a string!"; +//console.log(reverseCharacters(myString)); + // Part Two: Reverse Digits // 1. Add an if statement to reverseCharacters to check the typeof the parameter. @@ -17,6 +24,20 @@ // 4. Return the reversed number. // 5. Be sure to print the result returned by the function to verify that your code works for both strings and numbers. Do this before moving on to the next exercise. +function reverseCharacters(toReverse){ + if (typeof toReverse === "string"){ + toReverse = toReverse.split("").reverse().join(""); + return toReverse; + } else if (typeof toReverse === "number"){ + toReverse = toReverse.toString().split("").reverse().join(""); + return toReverse; + } + +} +let myString = "This is a string"; +let myNumber = 123456; +console.log(reverseCharacters(myNumber)); + // Part Three: Complete Reversal // 1. Define and initialize an empty array. @@ -26,9 +47,23 @@ // 5. Return the final, reversed array. // 6. Be sure to print the results from each test case in order to verify your code. +function reverseCharAndArr(inputArray){ + let newCharandArr = []; + for (i = 0; i < inputArray.length; i++){ + newCharandArr = inputArray; + newCharandArr = newCharandArr.toString(','); + newCharandArr = reverseCharacters(newCharandArr); + newCharandArr = newCharandArr.split(','); + + } + return newCharandArr; + } + let arrayTest1 = ['apple', 'potato', 'Capitalized Words']; let arrayTest2 = [123, 8897, 42, 1168, 8675309]; let arrayTest3 = ['hello', 'world', 123, 'orange']; +console.log(reverseCharAndArr(arrayTest3)); + // Bonus Missions @@ -37,6 +72,20 @@ 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. +let phrase = "Emily is so super helpful today!"; +function funPhrase(phrase){ + let empty1 = ""; + let empty2 = ""; + let phraseArray = phrase.split(" "); + for (i = 0; i < phraseArray.length; i++){ + if (phraseArray[i].length <= 3){ + empty1 += phraseArray[i].slice() + } + } + return phraseArray +} +console.log(funPhrase(phrase)); + // Test Function // 1. Outside of the function, define the variable str and initialize it with a string (e.g. 'Functions rock!'). From 9bfcd5da613cf6b8286635741997f3265fa61a28 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Sat, 29 Jun 2024 20:52:59 -0500 Subject: [PATCH 17/32] debug homework --- .../exercises/Debugging1stSyntaxError.js | 2 +- .../exercises/DebuggingLogicErrors1.js | 4 +++- .../exercises/DebuggingLogicErrors2.js | 4 +++- .../exercises/DebuggingLogicErrors3.js | 6 ++++-- .../exercises/DebuggingLogicErrors4.js | 2 ++ .../exercises/DebuggingLogicErrors5.js | 16 ++++++++++++---- .../exercises/DebuggingRuntimeErrors1.js | 2 +- .../exercises/DebuggingRuntimeErrors2.js | 2 +- 8 files changed, 27 insertions(+), 11 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/DebuggingLogicErrors1.js b/errors-and-debugging/exercises/DebuggingLogicErrors1.js index 1ad473f08d..5db3f46a5c 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors1.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors1.js @@ -29,4 +29,6 @@ if (launchReady) { console.log('Liftoff!'); } else { console.log('Launch scrubbed.'); -} \ No newline at end of file +} + +//No, shuttle should not have launched, but launchReady was overwritten as true \ No newline at end of file diff --git a/errors-and-debugging/exercises/DebuggingLogicErrors2.js b/errors-and-debugging/exercises/DebuggingLogicErrors2.js index 160a0c2cd0..6c2411bbf5 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors2.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors2.js @@ -2,7 +2,7 @@ // Consider the first if/else block below. // Add console.log(launchReady) after this block, then run the program. -//Given the fuelLevel value, should launchReady be true or false after the check? Is the program behaving as expected? +//Given the fuelLevel value, should launchReady be true or false after the check? FLASE Is the program behaving as expected? YES let launchReady = false; let fuelLevel = 17000; @@ -17,6 +17,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..182dd6c89e 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors3.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors3.js @@ -2,8 +2,8 @@ // Now consider the second if/else block. // Add another console.log(launchReady) after this block and run the program. -// 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, should launchReady be true or false after the check? TRUE +// Is the program behaving as expected? YES let launchReady = false; // let fuelLevel = 17000; @@ -26,6 +26,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..145904b35a 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors4.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors4.js @@ -29,6 +29,8 @@ if (crewStatus && computerStatus === 'green'){ console.log("launchReady = ", launchReady); +//Not correct again, the 'green' if statement is updating the launchready to true, when it should be false + // 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..6cab4f614c 100644 --- a/errors-and-debugging/exercises/DebuggingLogicErrors5.js +++ b/errors-and-debugging/exercises/DebuggingLogicErrors5.js @@ -3,7 +3,8 @@ // Refactor the code to do this. Verify that your change works by updating the console.log statements. let launchReady = false; -let fuelLevel = 17000; +let crewReady = true; +let fuelLevel = 27000; 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; + crewReady = true; } else { console.log('WARNING: Crew or computer not ready!'); - launchReady = false; + crewReady = false; +} + +if (launchReady && crewReady) { + console.log('10, 9, 8, 7, 6, 5, 4, 3, 2, 1...'); + console.log('Liftoff!'); + } else { + console.log('Launch scrubbed.'); } -console.log("launchReady = ", launchReady); \ No newline at end of file +//console.log("launchReady = ", launchReady); \ 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."); From cb586086a4c82cbdce7fe31d87b9b6e59d304b73 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Sun, 30 Jun 2024 20:56:51 -0500 Subject: [PATCH 18/32] part-one commit --- stringing-characters-together/exercises/part-one.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stringing-characters-together/exercises/part-one.js b/stringing-characters-together/exercises/part-one.js index a22fe74265..92e9d33393 100644 --- a/stringing-characters-together/exercises/part-one.js +++ b/stringing-characters-together/exercises/part-one.js @@ -1,4 +1,4 @@ -let num = 1001; +let num = "apple"; //Returns 'undefined'. console.log(num.length); From db14719f3d5691fbc46b04f990c187334a65ded3 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Mon, 1 Jul 2024 01:34:04 -0500 Subject: [PATCH 19/32] array push 2 --- arrays/exercises/part-five-arrays.js | 12 ++++++++++++ arrays/exercises/part-four-arrays.js | 23 +++++++++++++++++++++++ arrays/exercises/part-six-arrays.js | 6 ++++++ arrays/exercises/part-three-arrays.js | 11 +++++++++++ arrays/exercises/part-two-arrays.js | 2 +- 5 files changed, 53 insertions(+), 1 deletion(-) diff --git a/arrays/exercises/part-five-arrays.js b/arrays/exercises/part-five-arrays.js index 4cdf1bba41..b612601057 100644 --- a/arrays/exercises/part-five-arrays.js +++ b/arrays/exercises/part-five-arrays.js @@ -2,10 +2,22 @@ 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('')); + +//1st joins and adds commas, 2nd adds an a between each array value, 3rd adds a space, 4th removes all spaces //3) Do split or join change the original string/array? +//no - not with console.log //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()); diff --git a/arrays/exercises/part-four-arrays.js b/arrays/exercises/part-four-arrays.js index 498149702e..6821ce806c 100644 --- a/arrays/exercises/part-four-arrays.js +++ b/arrays/exercises/part-four-arrays.js @@ -1,10 +1,33 @@ let holdCabinet1 = ['duct tape', 'gum', 3.14, false, 6.022e23]; let holdCabinet2 = ['orange drink', 'nerf toys', 'camera', 42, 'parsnip']; +let newCabinet = []; //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. +newCabinet = holdCabinet1.concat(holdCabinet2); +//console.log(holdCabinet1.concat(holdCabinet2)); +console.log(newCabinet); +console.log(holdCabinet1); + +//No, the original array is not affected + //2) Print a slice of two elements from each array. Does slice alter the original arrays? +console.log(holdCabinet1.slice(0,2)); +console.log(holdCabinet2.slice(0,2)); + +console.log(holdCabinet1); +console.log(holdCabinet2); + +//No, original arrays not altered //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, original rays not altered \ No newline at end of file diff --git a/arrays/exercises/part-six-arrays.js b/arrays/exercises/part-six-arrays.js index d0a28bed56..53fae57974 100644 --- a/arrays/exercises/part-six-arrays.js +++ b/arrays/exercises/part-six-arrays.js @@ -1,9 +1,15 @@ //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. +element1 = ['hydrogen', 'H', 1.008] +element2 = ['helium', 'He', 4.003] +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 arrTable = []; +element1.push() + //3) Use bracket notation to examine the difference between printing 'table' with one index vs. two indices (table[][]). //4) Using bracket notation and the table array, print the mass of element1, the name for element 2 and the symbol for element26. diff --git a/arrays/exercises/part-three-arrays.js b/arrays/exercises/part-three-arrays.js index d43918a702..f02af371c5 100644 --- a/arrays/exercises/part-three-arrays.js +++ b/arrays/exercises/part-three-arrays.js @@ -4,6 +4,17 @@ 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(2,0,'keys'); + +console.log(cargoHold); + //2) Remove ‘instruction manual’ from the array. (Hint: indexOf is helpful to avoid manually counting an index). +cargoHold.splice(4,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 88c7f677b8..d8a7be9ec7 100644 --- a/arrays/exercises/part-two-arrays.js +++ b/arrays/exercises/part-two-arrays.js @@ -13,7 +13,7 @@ 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"); +cargoHold.unshift(1138) + cargoHold.push(" 20 meters"); console.log(cargoHold); //5) Use a template literal to print the final array and its length. From 41366624c45b8052b502ef58ebed804e84a019f4 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Mon, 1 Jul 2024 02:15:43 -0500 Subject: [PATCH 20/32] part 6 push --- arrays/exercises/part-six-arrays.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/arrays/exercises/part-six-arrays.js b/arrays/exercises/part-six-arrays.js index 53fae57974..ffb74f8b93 100644 --- a/arrays/exercises/part-six-arrays.js +++ b/arrays/exercises/part-six-arrays.js @@ -1,5 +1,7 @@ //Arrays can hold different data types, even other arrays! A multi-dimensional array is one with entries that are themselves arrays. +const { table } = require("console"); + //1) Define and initialize the arrays specified in the exercise to hold the name, chemical symbol and mass for different elements. element1 = ['hydrogen', 'H', 1.008] element2 = ['helium', 'He', 4.003] @@ -8,10 +10,23 @@ 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 arrTable = []; -element1.push() +arrTable.push(element1); +arrTable.push(element2); +arrTable.push(element26); + +console.log(arrTable); //3) Use bracket notation to examine the difference between printing 'table' with one index vs. two indices (table[][]). +console.log(arrTable[1], arrTable[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(arrTable[0][2], arrTable[1][0], arrTable[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. + +console.log("Part 5 here"); +let dimensialArr = [['green','red','blue'],[1,2,3],[2.22,3.33,6.66]]; +console.log(dimensialArr); +console.log(dimensialArr[0][1],dimensialArr[1][1],dimensialArr[2][2]); \ No newline at end of file From 169a2e1d5dfa247d4177c658df155fd04ade3514 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Mon, 1 Jul 2024 20:15:07 -0500 Subject: [PATCH 21/32] studio for class --- .../studio/part-one-find-minimum-value.js | 18 +++++++++- .../part-three-number-sorting-easy-way.js | 7 +++- .../studio/part-two-create-sorted-array.js | 33 ++++++++++++++++--- 3 files changed, 52 insertions(+), 6 deletions(-) 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..92cda4eca0 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,22 @@ 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]; +//function to find lowest num +function findLowestNumber(arr) { +let min = arr[0]; +//loop to iterate array +for (i = 0; i < arr.length; i++) { +//if to find minimum value +if (arr[i] < min) { + min = arr[i]; +//return line +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(findLowestNumber(nums1)); +console.log(findLowestNumber(nums2)); +console.log(findLowestNumber(nums3)); + +//can be repeated for nums 2 and 3 \ No newline at end of file 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 386cde1da8..8bd7db82e6 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 @@ -4,5 +4,10 @@ let nums2 = [-2, 0, -10, -44, 5, 3, 0, 3]; let nums3 = [200, 5, 4, 10, 8, 5, -3.3, 4.4, 0]; //Sort each array in ascending order. - +console.log(nums1.sort(function(a, b){return a-b})); +console.log(nums2.sort(function(a, b){return a-b})); +console.log(nums3.sort(function(a, b){return a-b})); //Sort each array in decending order. +console.log(nums1.sort(function(a, b){return b-a})); +console.log(nums2.sort(function(a, b){return b-a})); +console.log(nums3.sort(function(a, b){return b-a})); \ 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..81d0f63eb7 100644 --- a/more-on-functions/studio/part-two-create-sorted-array.js +++ b/more-on-functions/studio/part-two-create-sorted-array.js @@ -1,3 +1,7 @@ +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]; + function findMinValue(arr){ let min = arr[0]; for (i = 0; i < arr.length; i++){ @@ -10,8 +14,30 @@ function findMinValue(arr){ //Create a function with an array of numbers as its parameter. This function will return a new array with the numbers sorted from least to greatest value. +function sortFuncArr(arr) { + //define new empty array + let sortArr = []; + //loop option - nonrecursion (using while) + while (arr.length > 0) { + //return blank + //use findMinValue to find min value in old array - can we add () to end of function? + let min = findMinValue(arr); + //add min value to new array, remove min value from old array + arr.splice(arr.indexOf(min), 1); + sortArr.push(min); + } + //return line + return sortArr; +}; + +console.log(sortFuncArr(nums1)); +console.log(sortFuncArr(nums2)); +console.log(sortFuncArr(nums3)); + + + /*Within the function: -1) Define a new, empty array to hold the final sorted numbers. +1) Define a new, empty array to hold the final sorted numbers. 2) Use the findMinValue function to find the minimum value in the old array. 3) Add the minimum value to the new array, and remove the minimum value from the old array. 4) Repeat parts b & c until the old array is empty. @@ -23,7 +49,6 @@ function findMinValue(arr){ /* BONUS MISSION: Refactor your sorting function to use recursion below: */ + + //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]; From 3781830d49a476057dca4c1d83b25c1c2feafa2e Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Mon, 8 Jul 2024 21:40:54 -0500 Subject: [PATCH 22/32] 1 and 2 studio --- objects-and-math/studio/ObjectsStudio01.js | 32 ++++- objects-and-math/studio/ObjectsStudio02.js | 140 ++++++++++++--------- 2 files changed, 114 insertions(+), 58 deletions(-) diff --git a/objects-and-math/studio/ObjectsStudio01.js b/objects-and-math/studio/ObjectsStudio01.js index 98dd0cd471..5f9f842b1c 100644 --- a/objects-and-math/studio/ObjectsStudio01.js +++ b/objects-and-math/studio/ObjectsStudio01.js @@ -1,10 +1,37 @@ // Code your selectRandomEntry function here: +function randomSelection(arr){ + let index = Math.floor(Math.random()*arr.length); + return arr[index]; +} +let idNumbers = [291, 414, 503, 599, 796, 890]; +let selectedIds = []; + + +while (selectedIds.length < 3) { +let random = randomSelection(idNumbers); + if (!selectedIds.includes(random)){ + + selectedIds.push(random); + } +} + // Code your buildCrewArray function here: +function buildCrewArray(randomIds, animals){ + let crew = []; + + for (let i = 0; i < animals.length; i++){ + if (randomIds.includes(animals[i].astronautID)){ + crew.push(animals[i].name); + } + + } + return crew; +} + -let idNumbers = [291, 414, 503, 599, 796, 890]; // Here are the candidates and the 'animals' array: let candidateA = { @@ -51,5 +78,8 @@ let candidateF = { }; let animals = [candidateA,candidateB,candidateC,candidateD,candidateE,candidateF]; +let crew2 = buildCrewArray(selectedIds, animals); // Code your template literal and console.log statements: + +console.log(`${crew2[0]}, ${crew2[1]}, and ${crew2[2]} are going to space!`); \ No newline at end of file diff --git a/objects-and-math/studio/ObjectsStudio02.js b/objects-and-math/studio/ObjectsStudio02.js index 987bd46bfe..0178650621 100644 --- a/objects-and-math/studio/ObjectsStudio02.js +++ b/objects-and-math/studio/ObjectsStudio02.js @@ -1,58 +1,84 @@ // Code your orbitCircumference function here: - - -// Code your missionDuration function here: - - -// Copy/paste your selectRandomEntry function here: - - -// Code your oxygenExpended function here: - - -// Candidate data & crew array. -let candidateA = { - 'name':'Gordon Shumway', - 'species':'alf', - 'mass':90, - 'o2Used':function(hrs){return 0.035*hrs}, - 'astronautID':414 - }; - let candidateB = { - 'name':'Lassie', - 'species':'dog', - 'mass':19.1, - 'o2Used':function(hrs){return 0.030*hrs}, - 'astronautID':503 - }; - let candidateC = { - 'name':'Jonsey', - 'species':'cat', - 'mass':3.6, - 'o2Used':function(hrs){return 0.022*hrs}, - 'astronautID':796 - }; - let candidateD = { - 'name':'Paddington', - 'species':'bear', - 'mass':31.8, - 'o2Used':function(hrs){return 0.047*hrs}, - 'astronautID':291 - }; - let candidateE = { - 'name':'Pete', - 'species':'tortoise', - 'mass':417, - 'o2Used':function(hrs){return 0.010*hrs}, - 'astronautID':599 - }; - let candidateF = { - 'name':'Hugs', - 'species':'ball python', - 'mass':2.3, - 'o2Used':function(hrs){return 0.018*hrs}, - 'astronautID':890 - }; - - let crew = [candidateA,candidateC,candidateE]; - \ No newline at end of file +function orbitCircumference(rad){ + let circumference = 2 * Math.PI * rad; + + return Math.round(circumference); + }; + + + // Code your missionDuration function here: + function missionDuration(numOrbits, orbitRadius = 2000, orbitalSpeed = 28000) { + let distance = numOrbits * orbitCircumference(orbitRadius); + let time = Math.round(distance / orbitalSpeed * 100) / 100; + + console.log(`The mission will travel ${distance} km around the planet, and it will take ${time} hours to complete.`); + + return time; + }; + + + // Copy/paste your selectRandomEntry function here: + function randomSelection(arr){ + let index = Math.floor(Math.random()*arr.length); + return arr[index]; + } + + // Code your oxygenExpended function here: + function oxygenExpended(object) { + let time = missionDuration(3); + let oxygen = Math.round(object.o2Used(time) * 1000) / 1000; + + + return `${object.name} will perform the spacewalk, which will last ${time} hours and require ${oxygen} kg of oxygen.`; + } + + + // Candidate data & crew array. + let candidateA = { + 'name':'Gordon Shumway', + 'species':'alf', + 'mass':90, + 'o2Used':function(hrs){return 0.035*hrs}, + 'astronautID':414 + }; + let candidateB = { + 'name':'Lassie', + 'species':'dog', + 'mass':19.1, + 'o2Used':function(hrs){return 0.030*hrs}, + 'astronautID':503 + }; + let candidateC = { + 'name':'Jonsey', + 'species':'cat', + 'mass':3.6, + 'o2Used':function(hrs){return 0.022*hrs}, + 'astronautID':796 + }; + let candidateD = { + 'name':'Paddington', + 'species':'bear', + 'mass':31.8, + 'o2Used':function(hrs){return 0.047*hrs}, + 'astronautID':291 + }; + let candidateE = { + 'name':'Pete', + 'species':'tortoise', + 'mass':417, + 'o2Used':function(hrs){return 0.010*hrs}, + 'astronautID':599 + }; + let candidateF = { + 'name':'Hugs', + 'species':'ball python', + 'mass':2.3, + 'o2Used':function(hrs){return 0.018*hrs}, + 'astronautID':890 + }; + + let crew = [candidateA,candidateC,candidateE]; + let oxygenUsed = oxygenExpended(randomSelection(crew)); + + + console.log(oxygenUsed); \ No newline at end of file From 6e2f9f77c33b366320bc248e78a2838b04f1e337 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Mon, 15 Jul 2024 20:20:05 -0500 Subject: [PATCH 23/32] commit post studio time 1 --- unit-testing/studio/index.js | 31 ++++++++++++++++--- unit-testing/studio/tests/launchcode.test.js | 32 +++++++++++++++++++- 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/unit-testing/studio/index.js b/unit-testing/studio/index.js index 2ba56cb9bd..bf3031a123 100644 --- a/unit-testing/studio/index.js +++ b/unit-testing/studio/index.js @@ -1,7 +1,30 @@ let launchcode = { + organization: "nonprofit", + executiveDirector: "Jeff", + percentageCoolEmployees: 100, + programsOffered: ["Web Development", "Data Analysis", "Liftoff"], + launchOutput : function (input) { + let output = ""; -} - -module.exports = launchcode; - + if (input % 2 === 0 && input % 3 === 0 && input % 5 === 0) { + return output = 'LaunchCode Rocks!'; + }else if (input % 2 === 0 && input % 3 === 0) { + return output = "LaunchCode!"; + }else if (input % 3 === 0 && input % 5 === 0) { + return output = "Code Rocks!"; + } else if (input % 2 === 0 && input % 5 === 0) { + return output = 'Launch Rocks! (CRASH!!!!)'; + } else if (input % 2 === 0) { + return output = 'Launch!'; + } else if (input % 3 === 0) { + return output = 'Code!'; + } else if (input % 5 === 0) { + return output = 'Rocks!'; + } else { + return output = "Rutabagas! That doesn't work."; + } + } + }; + + module.exports = launchcode; \ No newline at end of file diff --git a/unit-testing/studio/tests/launchcode.test.js b/unit-testing/studio/tests/launchcode.test.js index f535305e3b..d45e76b611 100644 --- a/unit-testing/studio/tests/launchcode.test.js +++ b/unit-testing/studio/tests/launchcode.test.js @@ -3,6 +3,36 @@ const launchcode = require('../index.js'); describe("Testing launchcode", function(){ - // Write your unit tests here! + test("organization should contain nonprofit", function() { + expect(launchcode.organization).toBe("nonprofit"); + }); + + test("executive director should contain jeff", function() { + expect(launchcode.executiveDirector).toBe("Jeff"); + }); + + test("percentageCoolEmployees should contain 100", function() { + expect(launchcode.percentageCoolEmployees).toBe(100); + }); + + test("programsOffered should contain ", 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("launchOutput() method meets output", function() { + expect(launchcode.launchOutput(2)).toBe("Launch!"); + expect(launchcode.launchOutput(3)).toBe("Code!"); + expect(launchcode.launchOutput(5)).toBe("Rocks!"); + expect(launchcode.launchOutput(6)).toBe("LaunchCode!"); + expect(launchcode.launchOutput(30)).toBe("LaunchCode Rocks!"); + expect(launchcode.launchOutput(7)).toBe("Rutabagas! That doesn't work."); + expect(launchcode.launchOutput(15)).toBe("Code Rocks!"); + expect(launchcode.launchOutput(10)).toBe("Launch Rocks! (CRASH!!!!)"); + + }); }); \ No newline at end of file From fa7faf5b07e19bac8b73eae621714ba8fb24001b Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Mon, 22 Jul 2024 14:32:10 -0500 Subject: [PATCH 24/32] 1 --- classes/exercises/ClassExercises.js | 57 ++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/classes/exercises/ClassExercises.js b/classes/exercises/ClassExercises.js index 91b9ee5b9d..ad196b283c 100644 --- a/classes/exercises/ClassExercises.js +++ b/classes/exercises/ClassExercises.js @@ -1,10 +1,63 @@ // Define your Book class here: - +class book { + constructor(title, author, copyrightDate, isbn, numberOfPages, timesCheckedOut, isDiscarded){ + this.author = author; + this.copyrightDate = copyrightDate; + this.isbn = isbn; + this.numberOfPages = numberOfPages; + this.timesCheckedOut = timesCheckedOut; + this.isDiscarded = isDiscarded; + } + checkout(uses=1) { + this.timesCheckedOut += uses; + } + } // Define your Manual and Novel classes here: +class Manual extends book { + constructor (title, author, copyrightDate, isbn, numberOfPages, timesCheckedOut, isDiscarded) { + super(title, author, copyrightDate, isbn, numberOfPages, timesCheckedOut, isDiscarded); + //properties + } + dispose(currentYear) { + if (currentYear+this.copyrightDate > 5) { + this.isDiscarded = 'Yes'; + } + } +} +class Novel extends book { + constructor (title, author, copyrightDate, isbn, numberOfPages, timesCheckedOut, isDiscarded) { + super(title, author, copyrightDate, isbn, numberOfPages, timesCheckedOut, isDiscarded); + //properties + } + dispose(){ + if (this.timesCheckedOut > 100) { + this.isDiscarded = 'Yes'; + } + } +} // Declare the objects for exercises 2 and 3 here: +let book1 = new Novel("Pride and Prejudice", "Jane Austen", 1813, "1111111111111", 432, 32, "No"); +let book2 = new Manual("Top Secret Shuttle Building Manual", "Redacted", 2013, "0000000000000", 1147, 1, "No"); + + +// Code exercises 4 & 5 here: +let currentYear = 2024; +//book2.dispose() +book1.checkout(5) +book2.dispose(currentYear); + +console.log(book2); + +//let timesCheckedOut = book1.timesCheckedOut +//book1.timesCheckedOut(timesCheckedOut += 5); + +console.log(book1); + +//function discardBook() { +// let discardBook = novel.dispose(); +//} -// Code exercises 4 & 5 here: \ No newline at end of file From 30dda7c7c2c1b510e13a4f97348ac13992386aa2 Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Mon, 22 Jul 2024 20:36:15 -0500 Subject: [PATCH 25/32] commit 1 --- classes/studio/ClassStudio.js | 59 +++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/classes/studio/ClassStudio.js b/classes/studio/ClassStudio.js index c3a6152140..3514b05161 100644 --- a/classes/studio/ClassStudio.js +++ b/classes/studio/ClassStudio.js @@ -1,6 +1,65 @@ //Declare a class called CrewCandidate with a constructor that takes three parameters—name, mass, and scores. Note that scores will be an array of test results. +class CrewCandidate { + constructor(name, mass, scores) { + this.name = name; + this.mass = mass; + this.scores = scores; + } + addScore(newScore) { + this.scores.push(newScore); + } + + average() { + const sum = this.scores.reduce(function(accumulator, currentValue) { + return accumulator + currentValue; + }, 0); + + return Math.round((sum/this.scores.length)*10)/10; + } + + status() { + let average = this.average(); + if (average >= 90) { + return 'Accepted' + } else if (average >= 80 && average <= 89) { + return 'Reserve' + } else if (average >= 70 && average <= 79) { + return 'Probationary' + } else { + return 'Rejected' + } + + } +} + +let crewCandidate1 = new CrewCandidate ('Bubba Bear', 135, [88, 85, 90]); +let crewCandidate2 = new CrewCandidate ('Merry Maltese', 1.5, [93, 88, 97]); +let crewCandidate3 = new CrewCandidate ('Glad Gator', 225, [75, 78, 62]); + + +console.log(`${crewCandidate1.name} earned an average test score of ${crewCandidate1.average()}% and has a status of ${crewCandidate1.status()}.`); + +let noOfTestsToAccepted = 0; +let noOfTestsToReserved = 0; + +while (crewCandidate3.average() < 80) { + + crewCandidate3.addScore(100); + console.log(crewCandidate3.average()); + noOfTestsToReserved++; +} + +while (crewCandidate3.average() < 90) { + + crewCandidate3.addScore(100); + console.log(crewCandidate3.average()); + noOfTestsToAccepted++; +} + +console.log(crewCandidate3.status()); +console.log(`It took ${crewCandidate3.name} ${noOfTestsToAccepted} tests to get Accepted and ${noOfTestsToReserved} tests to get Reserved.`); //Add methods for adding scores, averaging scores and determining candidate status as described in the studio activity. From fdb3cb8ba3b3ae61a40aa38307b5cc857e25ea18 Mon Sep 17 00:00:00 2001 From: Gavin Kolasa Date: Tue, 23 Jul 2024 20:00:43 -0500 Subject: [PATCH 26/32] commit 1 --- html/exercises/index.html | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/html/exercises/index.html b/html/exercises/index.html index 80f716a800..5a20538170 100644 --- a/html/exercises/index.html +++ b/html/exercises/index.html @@ -9,8 +9,15 @@ +

Why I Love Web Development

+
    Reasons I love Web Development: +
  1. It's really fun!
  2. +
  3. So much space for creativity!
  4. +
+ Click this link, now! +

I believe the first website I'd like to make would be a directory for argumentational information. Info including: common argumentative fallacies, rebuttals for both arguments, sources/links similar to wikipedia, etc.

\ No newline at end of file From 9595446e1f3adbb3932e22bf86be532a745d051f Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Mon, 29 Jul 2024 17:35:06 -0500 Subject: [PATCH 27/32] commit 1 --- css/exercises/index.html | 8 ++++---- css/exercises/styles.css | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/css/exercises/index.html b/css/exercises/index.html index 922e8e3885..be0ddaf758 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..c355c44f00 100644 --- a/css/exercises/styles.css +++ b/css/exercises/styles.css @@ -1 +1,19 @@ /* Start adding your styling below! */ +body { + background-color: yellow; +} +body { + color: green; +} +h1 { + font-size: 36px; +} +.center { + text-align: center; +} +#cool-text { + color: blue; +} +#list-text { + color: pink; +} \ No newline at end of file From b503a6a84f440e099a514824e417c9491c665ea6 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Sun, 4 Aug 2024 23:49:04 -0500 Subject: [PATCH 28/32] script completed - commit 1 --- dom-and-events/exercises/script.js | 31 ++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/dom-and-events/exercises/script.js b/dom-and-events/exercises/script.js index de6b630519..9791c1945a 100644 --- a/dom-and-events/exercises/script.js +++ b/dom-and-events/exercises/script.js @@ -4,7 +4,38 @@ function init () { const paragraph = document.getElementById("statusReport"); // Put your code for the exercises here. + let liftOff = document.getElementById("liftoffButton"); + liftOff.addEventListener("click", function(event) { + document.getElementById("statusReport").textContent = "Houston, we have liftoff!"; + console.log("Houston, we have liftoff!"); + }) + // window.addEventListener("load", function() { + // let redAlert = document.getElementById("abortMission"); + // redAlert.addEventListener("mouseover", function (event) { + // let element = event.target; + // element. + // }) + // }) + + // function changeColor() { + // document.getElementById("abortMission"); + // button.style.backgroundColor = "red"; + // } + abortMission.addEventListener('mouseover', function (event) { + event.target.style.backgroundColor = "red"; + }) + abortMission.addEventListener('mouseout', function (event) { + event.target.style.backgroundColor = ""; + }) + abortMission.addEventListener('click', function (event) { + // window.confirm("Are you sure you want to abort the mission?"); + if (confirm("Are you sure you want to abort the mission?") == true) { + document.getElementById("statusReport").textContent = "Mission aborted! Space shuttle returning home."; + } else { + document.getElementById("statusReport").textContent = "Not aborting! The shuttle is on the ground." + } + }) } window.addEventListener("load", init); From 019baf1c75dfcf01b58533f62e0e8d804644b705 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Mon, 5 Aug 2024 20:18:06 -0500 Subject: [PATCH 29/32] commit 1 studio --- dom-and-events/studio/scripts.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/dom-and-events/studio/scripts.js b/dom-and-events/studio/scripts.js index 45c9b3a9d1..8a888ef4d1 100644 --- a/dom-and-events/studio/scripts.js +++ b/dom-and-events/studio/scripts.js @@ -1,2 +1,27 @@ // Write your JavaScript code here. // Remember to pay attention to page loading! +window.addEventListener("load", function() { + console.log("all elements loaded"); + +const takeOffButton = document.getElementById("takeoff"); +const flightStatusID = document.getElementById("flightStatus"); +const flightDisplayID = document.getElementById("flightDisplay"); +const shuttleBackgroundID = document.getElementById("shuttleBackground"); +const spaceShuttleHeightID = document.getElementById("spaceShuttleHeight"); + +takeOffButton.addEventListener('click', function() { + let takeOffClick = window.confirm("Confirm that the shuttle is ready for takeoff."); + if (takeOffClick === true) { + flightStatusID.innerHTML = "Shuttle in flight."; + shuttleBackgroundID.style.background = "blue"; + spaceShuttleHeightID.innerHTML = "10000"; + } +}) + +///land button +const landButtonID = document.getElementById("landing"); +landButtonID.addEventListener("click", function() { + window.alert("The shuttle is landing. Landing gear engaged"); + + +})}) \ No newline at end of file From 218021f33da3fe5df5dd81ae4f04c2847828d9a4 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Mon, 5 Aug 2024 20:21:07 -0500 Subject: [PATCH 30/32] commit 2 --- dom-and-events/studio/scripts.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/dom-and-events/studio/scripts.js b/dom-and-events/studio/scripts.js index 8a888ef4d1..9efc6003aa 100644 --- a/dom-and-events/studio/scripts.js +++ b/dom-and-events/studio/scripts.js @@ -22,6 +22,11 @@ takeOffButton.addEventListener('click', function() { const landButtonID = document.getElementById("landing"); landButtonID.addEventListener("click", function() { window.alert("The shuttle is landing. Landing gear engaged"); + flightStatusID.innerHTML = "The shuttle has landed."; + shuttleBackgroundID.style.background = "green"; + spaceShuttleHeightID.innerHTML = "0"; +}) + -})}) \ No newline at end of file +}) \ No newline at end of file From c8276e76c57e258f6fb8cfff3deed9789dc6f2a8 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Thu, 8 Aug 2024 22:19:57 -0500 Subject: [PATCH 31/32] commit 1 --- user-input-with-forms/studio/index.html | 60 ++++++++++++++++++------- 1 file changed, 45 insertions(+), 15 deletions(-) diff --git a/user-input-with-forms/studio/index.html b/user-input-with-forms/studio/index.html index e6bf6cb0af..9ef6308848 100644 --- a/user-input-with-forms/studio/index.html +++ b/user-input-with-forms/studio/index.html @@ -1,19 +1,49 @@ - - + - - - + + + - -
    - -
    - - +
    + + + + + + +
    + \ No newline at end of file From 0907948d09cc952a6d6b7b2a01324f3f01af6f66 Mon Sep 17 00:00:00 2001 From: dreadstuff Date: Tue, 13 Aug 2024 18:05:53 -0500 Subject: [PATCH 32/32] commit for studio fetch --- fetch/studio/script.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/fetch/studio/script.js b/fetch/studio/script.js index 591ec836a7..5c6e211275 100644 --- a/fetch/studio/script.js +++ b/fetch/studio/script.js @@ -1 +1,26 @@ //TODO: Add Your Code Below +window.addEventListener("load", function(){ + let container = document.getElementById("container"); + fetch("http://github.com/service/https://handlers.education.launchcode.org/static/astronauts.json").then(function(response){ + response.json().then(function(json){ + console.log(json) + console.log(json[0].firstName) + for (let i = 0; i < json.length; i++){ + container.innerHTML +=// `
    "test"
    ` + ` +
    +
    +

    ${json[i].firstName} ${json[i].lastName}

    +
      +
    • Hours in space: ${json[i].hoursInSpace}
    • +
    • Active: ${json[i].active}
    • +
    • Skills: ${json[i].skills.join(", ")}
    • +
    +
    + +
    + ` + } + }) + }) + }) \ No newline at end of file