diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..8ed575178 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -5,7 +5,8 @@ let lastName = "Johnson"; // Declare a variable called initials that stores the first character of each string. // This should produce the string "CKJ", but you must not write the characters C, K, or J in the code of your solution. -let initials = ``; +const initials = firstName.charAt(0) + middleName.charAt(0) + lastName.charAt(0); +console.log( `acronym = ${initials}`); // https://www.google.com/search?q=get+first+character+of+string+mdn diff --git a/Sprint-1/1-key-exercises/3-paths.js b/Sprint-1/1-key-exercises/3-paths.js index ab90ebb28..02ce853bd 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -12,12 +12,22 @@ const filePath = "/Users/mitch/cyf/Module-JS1/week-1/interpret/file.txt"; const lastSlashIndex = filePath.lastIndexOf("/"); const base = filePath.slice(lastSlashIndex + 1); -console.log(`The base part of ${filePath} is ${base}`); // Create a variable to store the dir part of the filePath variable // Create a variable to store the ext part of the variable -const dir = ; -const ext = ; +const lastDot = filePath.lastIndexOf("."); +console.log(`The indexDot is ${lastDot}`); + +const ext = filePath.slice(lastDot); + +const fileName = filePath.slice(lastSlashIndex + 1, lastDot); +const dir = filePath.slice(1, lastSlashIndex + 1); + + + +console.log(`The dir is -> ${dir}`); +console.log(`The nameFile is -> ${fileName}`); +console.log(`The extension is -> ${ext}`); // https://www.google.com/search?q=slice+mdn \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/4-random.js b/Sprint-1/1-key-exercises/4-random.js index 292f83aab..884b122a3 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -7,3 +7,7 @@ const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; // Try breaking down the expression and using documentation to explain what it means // It will help to think about the order in which expressions are evaluated // Try logging the value of num and running the program several times to build an idea of what the program is doing +Math.floor() //removes decimal part and returns whole number +Math.random() //needs to values between minimum and maximum to generate a random number +console.log(maximum - minimum + 1 ) + minimum; // this is same as 100 - 1 + 1 = 100 +console.log(`The random number is ${num}`); \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/1.js b/Sprint-1/2-mandatory-errors/1.js index 7a43cbea7..dacf65d7a 100644 --- a/Sprint-1/2-mandatory-errors/1.js +++ b/Sprint-1/2-mandatory-errors/1.js @@ -1,4 +1,5 @@ // trying to create an age variable and then reassign the value by 1 -const age = 33; +let age = 33; // I to used 'let' to reassign a variable age = age + 1; +console.log(age); \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/2.js b/Sprint-1/2-mandatory-errors/2.js index e09b89831..5309db424 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/2-mandatory-errors/2.js @@ -1,5 +1,6 @@ // Currently trying to print the string "I was born in Bolton" but it isn't working... // what's the error ? -console.log(`I was born in ${cityOfBirth}`); const cityOfBirth = "Bolton"; +console.log(`I was born in ${cityOfBirth}`); +// The variable cityOfBirth has to be before the console.log statement. diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js index ec101884d..591dfad67 100644 --- a/Sprint-1/2-mandatory-errors/3.js +++ b/Sprint-1/2-mandatory-errors/3.js @@ -1,5 +1,9 @@ const cardNumber = 4533787178994213; -const last4Digits = cardNumber.slice(-4); +const numberString = cardNumber.toString(); // We have to convert the cardNumber to a string first before slicing the last 4 digits. +const last4Digits = numberString.slice(-4); +const num = Number(last4Digits); + +console.log(num); // The last4Digits variable should store the last 4 digits of cardNumber // However, the code isn't working diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js index 21dad8c5d..9f42bf1af 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,7 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +const T12HourClockTime = "20:53"; +const T24hourClockTime = "08:53"; +console.log (T12HourClockTime); +console.log (T24hourClockTime); +/*const 12HourClockTime = "20:53"; +const 24hourClockTime = "08:53"; +JS variable names (identifiers) must not start with a digit only start with a letter*/ \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/1-percentage-change.js b/Sprint-1/3-mandatory-interpret/1-percentage-change.js index e24ecb8e1..9b6cc7d71 100644 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-1/3-mandatory-interpret/1-percentage-change.js @@ -1,8 +1,8 @@ let carPrice = "10,000"; let priceAfterOneYear = "8,543"; -carPrice = Number(carPrice.replaceAll(",", "")); -priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); +carPrice = Number(carPrice.replaceAll(",","")); +priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); const priceDifference = carPrice - priceAfterOneYear; const percentageChange = (priceDifference / carPrice) * 100; @@ -10,13 +10,15 @@ const percentageChange = (priceDifference / carPrice) * 100; console.log(`The percentage change is ${percentageChange}`); // Read the code and then answer the questions below - // a) How many function calls are there in this file? Write down all the lines where a function call is made - +// There are 3 function (lines 4,5, and 10) // b) Run the code and identify the line where the error is coming from - why is this error occurring? How can you fix this problem? - +// line 5, the replaceAll method is missing a comma between its arguments. // c) Identify all the lines that are variable reassignment statements - +// 4 and 5) // d) Identify all the lines that are variable declarations - +// 1, 2, 7, and 8 // e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? +/*The expression Number(carPrice.replaceAll(",", "")) first removes the commas from the string value of carPrice. +After that, it converts the cleaned string into a number. +The purpose is to make sure the value can be used in mathematical calculations.*/ \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/2-time-format.js b/Sprint-1/3-mandatory-interpret/2-time-format.js index 47d239558..ac7de4c6d 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -12,14 +12,16 @@ console.log(result); // For the piece of code above, read the code and then answer the following questions // a) How many variable declarations are there in this program? - +// There are 6 variable // b) How many function calls are there? - +// There is 1 function call in the program: console.log(result) // c) Using documentation, explain what the expression movieLength % 60 represents +// The expression movieLength % 60 calculates the remainder when movieLength is divided by 60. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators // d) Interpret line 4, what does the expression assigned to totalMinutes mean? - +// This line removes the leftover seconds from the total movie length and then divides the result by 60 to convert the remaining time into whole minutes. // e) What do you think the variable result represents? Can you think of a better name for this variable? - +// The variable result stores the movie length formatted // f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer +// The code will work correctly for positive whole numbers representing seconds. \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..80c02a056 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -1,21 +1,24 @@ const penceString = "399p"; - +// initialises a string variable with the value "399p" const penceStringWithoutTrailingP = penceString.substring( 0, penceString.length - 1 ); - +// Removes the final character ("p") from the string, leaving only the numeric part of the price. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); const pounds = paddedPenceNumberString.substring( 0, paddedPenceNumberString.length - 2 ); - +// Ensures the string has at least three characters by adding leading zeros if necessary. const pence = paddedPenceNumberString .substring(paddedPenceNumberString.length - 2) .padEnd(2, "0"); + //Takes the last two digits as the pence part and ensures it is exactly two characters long. + console.log(`£${pounds}.${pence}`); +// Combines the pounds and pence into a formatted currency string and outputs the final result in pounds (£) // This program takes a string representing a price in pence // The program then builds up a string representing the price in pounds diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a0..dab6d63ca 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -1,13 +1,15 @@ // Predict and explain first... -// =============> write your prediction here +// =============> When we call capitalise("hello"), it will throw an error instead of returning "Hello". // call the function capitalise with a string input // interpret the error message and figure out why an error is occurring -function capitalise(str) { - let str = `${str[0].toUpperCase()}${str.slice(1)}`; - return str; +// =============> "str" has already been declared, in JavaScript we can not redeclare a parameter using let inside the same scope. +// =============> + + function capitalise(str) { + + return `${str[0].toUpperCase()}${str.slice(1)}`; } -// =============> write your explanation here -// =============> write your new code here +console.log(capitalise("hello")); diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index f2d56151f..39f29574b 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -1,20 +1,19 @@ // Predict and explain first... // Why will an error occur when this program runs? -// =============> write your prediction here +// =============> An error will occur because console.log(decimalNumber) tries to access a variable that does not exist in the global scope. // Try playing computer with the example to work out what is going on -function convertToPercentage(decimalNumber) { - const decimalNumber = 0.5; - const percentage = `${decimalNumber * 100}%`; - - return percentage; -} -console.log(decimalNumber); -// =============> write your explanation here +// =============> decimalNumber is already a parameter, and JavaScript does not allow redeclaring a parameter woth const. // Finally, correct the code to fix the problem -// =============> write your new code here +// =============> + function convertToPercentage(decimalNumber) { + const percentage = `${decimalNumber * 100}%`; + return percentage; +} + +console.log(convertToPercentage(0.5)); diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index aad57f7cf..173e3d661 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -3,18 +3,19 @@ // this function should square any number but instead we're going to get an error -// =============> write your prediction of the error here +// =============> SyntaxError -function square(3) { - return num * num; -} -// =============> write the error message here +// =============> Unexpected number -// =============> explain this error message here +// =============> function parameters must be variable not values. // Finally, correct the code to fix the problem -// =============> write your new code here +// =============> +function square(num) { + return num * num; +} +console.log(square(3)); diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..1fda05ef1 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,14 +1,13 @@ // Predict and explain first... -// =============> write your prediction here +// =============> SyntaxError undefined function -function multiply(a, b) { - console.log(a * b); -} - -console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); -// =============> write your explanation here +// =============> We use console.log() only when we want to print something immediately. In this case we need to use return. // Finally, correct the code to fix the problem // =============> write your new code here +function multiply(a, b) { + return a * b; +} +console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); \ No newline at end of file diff --git a/Sprint-2/2-mandatory-debug/1.js b/Sprint-2/2-mandatory-debug/1.js index 37cedfbcf..94861d35b 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,13 +1,12 @@ // Predict and explain first... -// =============> write your prediction here +// =============> the sum is undefined -function sum(a, b) { - return; - a + b; -} - -console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); -// =============> write your explanation here +// =============> This is due to Automatic semicolon Insertion // Finally, correct the code to fix the problem // =============> write your new code here +function sum(a, b) { + return a + b; +} + +console.log(`The sum of 10 + 32 is ${sum(10, 32)}`); \ No newline at end of file diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index 57d3f5dc3..21bb35163 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -1,24 +1,31 @@ // Predict and explain first... // Predict the output of the following code: -// =============> Write your prediction here +// =============> The output will always be 3 for all cases. + +// Now run the code and compare the output to your prediction +// =============> write the output here +// The last digit of 42 is 3 +//The last digit of 105 is 3 +//The last digit of 806 is 3 +// Explain why the output is the way it is +// =============> write your explanation here +//The function does not have a parameter. +//It does not use the values 42, 105, or 806. +//It always uses the global variable: +// Finally, correct the code to fix the problem +// =============> write your new code here const num = 103; -function getLastDigit() { - return num.toString().slice(-1); +function getLastDigit(value) { + return value.toString().slice(-1); } console.log(`The last digit of 42 is ${getLastDigit(42)}`); console.log(`The last digit of 105 is ${getLastDigit(105)}`); console.log(`The last digit of 806 is ${getLastDigit(806)}`); -// Now run the code and compare the output to your prediction -// =============> write the output here -// Explain why the output is the way it is -// =============> write your explanation here -// Finally, correct the code to fix the problem -// =============> write your new code here // This program should tell the user the last digit of each number. // Explain why getLastDigit is not working properly - correct the problem diff --git a/Sprint-2/3-mandatory-implement/1-bmi.js b/Sprint-2/3-mandatory-implement/1-bmi.js index 17b1cbde1..9f432e09d 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -15,5 +15,8 @@ // It should return their Body Mass Index to 1 decimal place function calculateBMI(weight, height) { - // return the BMI of someone based off their weight and height -} \ No newline at end of file + const squareHeight = height * height; + const bmi = weight / squareHeight; + return Number(bmi.toFixed(1)); +} +console.log(calculateBMI(60, 1.70)); diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js index 5b0ef77ad..dc6966eeb 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -14,3 +14,9 @@ // You will need to come up with an appropriate name for the function // Use the MDN string documentation to help you find a solution // This might help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase +function toUpperSnakeCase(str) { + return str.toUpperCase().replaceAll(" ", "_"); +} + +console.log(toUpperSnakeCase("Hello there")); // "HELLO_THERE" +console.log(toUpperSnakeCase("lord of the rings")); // "LORD_OF_THE_RINGS" \ No newline at end of file diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a70..9df0dabf2 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -4,3 +4,45 @@ // You will need to declare a function called toPounds with an appropriately named parameter. // You should call this function a number of times to check it works for different inputs +// ===>Code +// const penceString = "399p"; + +// const penceStringWithoutTrailingP = penceString.substring( +// 0, +// penceString.length - 1 +// ); + +// const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); +// const pounds = paddedPenceNumberString.substring( +// 0, +// paddedPenceNumberString.length - 2 +// ); + +// const pence = paddedPenceNumberString +// .substring(paddedPenceNumberString.length - 2) +// .padEnd(2, "0"); + +// console.log(`£${pounds}.${pence}`); + + + + +// ===>Reusable Code + + +function toPounds(str){ + + const onlyNumbers = str.replace(/[^\d]/g, ''); // removes everything that is not a digit + const decimals = (onlyNumbers/100).toFixed(2); // converts pence to pounds + + return `£${decimals}`; +}; + + + +// ===> test + +const examples = ["80p", "Fay", "130p", "£3.50", "10000"]; +for (const example of examples) { + console.log(toPounds(example)); +} diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..e93009053 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -17,18 +17,22 @@ function formatTimeDisplay(seconds) { // Questions // a) When formatTimeDisplay is called how many times will pad be called? -// =============> write your answer here +// =============> pad function will be called 3 times when formatTimeDisplay is called. // Call formatTimeDisplay with an input of 61, now answer the following: // b) What is the value assigned to num when pad is called for the first time? -// =============> write your answer here +// =============> The value assigned to num when pad is called for the first time is 0. + // c) What is the return value of pad is called for the first time? -// =============> write your answer here +/* =============> The return value of pad when it is called for the first time is "00". + because num is 0, and when we convert it to a string and pad it to 2 +characters with leading zeros, it becomes "00".*/ // d) What is the value assigned to num when pad is called for the last time in this program? Explain your answer -// =============> write your answer here +// =============> The value assigned to num when pad is called for the last time in this program is 1. + // e) What is the return value assigned to num when pad is called for the last time in this program? Explain your answer -// =============> write your answer here +// =============>The return value assigned to num when pad is called for the last time in this program is "01". diff --git a/Sprint-2/5-stretch-extend/format-time.js b/Sprint-2/5-stretch-extend/format-time.js index 32a32e66b..2cfcba511 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -22,4 +22,4 @@ const targetOutput2 = "11:00 pm"; console.assert( currentOutput2 === targetOutput2, `current output: ${currentOutput2}, target output: ${targetOutput2}` -); +); \ No newline at end of file