diff --git a/Sprint-1/interpret/to-pounds.js b/Sprint-1/interpret/to-pounds.js index 60c9ace69..02b6bc353 100644 --- a/Sprint-1/interpret/to-pounds.js +++ b/Sprint-1/interpret/to-pounds.js @@ -25,3 +25,6 @@ console.log(`£${pounds}.${pence}`); // To begin, we can start with // 1. const penceString = "399p": initialises a string variable with the value "399p" + + + diff --git a/Sprint-2/debug/0.js b/Sprint-2/debug/0.js index b46d471a8..5c9c4812f 100644 --- a/Sprint-2/debug/0.js +++ b/Sprint-2/debug/0.js @@ -1,7 +1,20 @@ // Predict and explain first... +/* + the function won't return anything because we did not have any return so this will be undefine + it will print what is in the console but no in the second console because we are callin the function which will return undefine + + + + function multiply(a, b) { + console.log(a * b); + } +*/ +// ==================== this will return the arguments sent in the second console ==================== + function multiply(a, b) { - console.log(a * b); + return(a * b); } + console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); diff --git a/Sprint-2/debug/1.js b/Sprint-2/debug/1.js index df4020cae..5e4c82859 100644 --- a/Sprint-2/debug/1.js +++ b/Sprint-2/debug/1.js @@ -1,8 +1,23 @@ // Predict and explain first... -function sum(a, b) { +/* + the reason why is returning undefined is because as soon the function find the return + will stop reading the rest. also the addition is ignoring because we have the statement + one line break after the return + + function sum(a, b) { return; a + b; } +*/ + + + +//=================== this will work ============== + +function sum(a, b) { + return a + b; +} + console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); diff --git a/Sprint-2/debug/2.js b/Sprint-2/debug/2.js index bae9652a8..d121061e1 100644 --- a/Sprint-2/debug/2.js +++ b/Sprint-2/debug/2.js @@ -1,14 +1,47 @@ // Predict and explain first... +/* + - If we run this code. nothing will happen because the function is not called. + + -once we invoke the function this will take the number and converted into string to manipulate and take the las digit and return the new string 42 => will return 2. + + const num = 103; + + function getLastDigit() { + return num.toString().slice(-1); + } +*/ + +//=========== This will work ============== +// This program should tell the user the last digit of each number. +// Explain why getLastDigit is not working properly - correct the problem + + const num = 103; -function getLastDigit() { +function getLastDigit(num) { return num.toString().slice(-1); } +console.log(`The last digit of 42 is ${getLastDigit(num)}`); 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)}`); -// This program should tell the user the last digit of each number. -// Explain why getLastDigit is not working properly - correct the problem + + +//=========== finding the middle digit ============== +// Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 +// Value: 2 0 5 5 5 6 4 2 3 2 5 6 9 + +function getMiddleDigit(num) { + const str = num.toString(); + // console.log(str); + + const middleIndex = Math.floor(str.length / 2); // 13/2 = 6.5 math.floor round the number to the nearest integer 6. + // console.log(middleIndex); + + return str[middleIndex]; //we can access to the position 6 which contains the value '4' +} + +console.log(`The middle of 105 is ${getMiddleDigit(2055564232569)}`) \ No newline at end of file diff --git a/Sprint-2/errors/0.js b/Sprint-2/errors/0.js index 74640e118..9fd228ddb 100644 --- a/Sprint-2/errors/0.js +++ b/Sprint-2/errors/0.js @@ -1,9 +1,43 @@ // Predict and explain first... // call the function capitalise with a string input -// interpret the error message and figure out why an error is occurring +// interpret the error message and figure out why an error occurring -function capitalise(str) { - let str = `${str[0].toUpperCase()}${str.slice(1)}`; + +/* + - Occur SyntaxError because the var str has been declared in the in the parameter, so to fix this we + just need to assign the new value. and remove the let. + + - Then call the function +*/ + + +// function capitalize(str) { +// let str = `${str[0].toUpperCase()}${str.slice(1)}`; +// return str; +// } + +// console.log(capitalize("alejandra")); + + + +/*================== fixed =======================*/ + +function capitalize(str) { + str = `${str[0].toUpperCase()}${str.slice(1)}`; return str; } + +console.log(capitalize("alejandra")); + + +/* + In this function, we are taking a string parameter, "alejandra", as input. + Inside the function, we modify the string by capitalizing the first character. + - First, we access the first character of the string using `str[0]` and use the `toUpperCase()` method + to convert it to a capital letter. + - Then, we use `str.slice(1)` to extract the rest of the string, starting from the second character. + - Finally, we combine the capitalized first letter and the rest of the string using a template literal. + + The result is for the input "alejandra", the output is "Alejandra". +*/ diff --git a/Sprint-2/errors/1.js b/Sprint-2/errors/1.js index 4602ed237..b601ef4ff 100644 --- a/Sprint-2/errors/1.js +++ b/Sprint-2/errors/1.js @@ -1,13 +1,35 @@ // Predict and explain first... -// Why will an error occur when this program runs? -// Try playing computer with the example to work out what is going on +/* -function convertToPercentage(decimalNumber) { - const decimalNumber = 0.5; + Why will an error occur when this program runs? + Try playing computer with the example to work out what is going on + + 1. The function won't run because we are not invoking the function, + 2. we have been declared one variable with const and this can not reassigned after, const decimalNumber also has a fixed value + 3. To work efficiently we should assign the parameter =+ inside the function and declare the var decimalNumber + 4. we call the function correctly with its respective argument + + function convertToPercentage(decimalNumber) { + const decimalNumber = 0.5; + const percentage = `${decimalNumber * 100}%`; + + return percentage; + } + + console.log(decimalNumber); +*/ + + +/*================== fixed =======================*/ + +function convertToPercentage(num) { + const decimalNumber = num; const percentage = `${decimalNumber * 100}%`; return percentage; } -console.log(decimalNumber); +console.log(convertToPercentage(.2)); //20% + + diff --git a/Sprint-2/errors/2.js b/Sprint-2/errors/2.js index 814334d9e..0953e7ca4 100644 --- a/Sprint-2/errors/2.js +++ b/Sprint-2/errors/2.js @@ -3,8 +3,30 @@ // this function should square any number but instead we're going to get an error -function square(3) { + +/* + parameter are in the function, in this example we are not receiving any parameter and this we can not write the + argument directly, + + arguments are in the console.log and we are not calling the function so that's why we are not having any response. + + function square(3) { + return num * num; + + } + +*/ + +/*================== fixed =======================*/ + + +function square(num) { return num * num; } +console.log(square(7)) + + + + diff --git a/Sprint-2/extend/format-time.js b/Sprint-2/extend/format-time.js index f3b83062d..c3e81cd5e 100644 --- a/Sprint-2/extend/format-time.js +++ b/Sprint-2/extend/format-time.js @@ -1,24 +1,111 @@ -// This is the latest solution to the problem from the prep. -// Your task is to write tests for as many different groups of input data or edge cases as you can, and fix any bugs you find. +/* + This is the latest solution to the problem from the prep. + Your task is to write tests for as many different groups of input data or edge cases as you can, and fix any bugs you find. + + function formatAs12HourClock(time) { + const hours = Number(time.slice(0, 2)); + console.log(hours); + if (hours > 12) { + return `${hours - 12}:00 pm`; + } + return `${time} am`; + } + +*/ + +// ====================== function and cases ======================= + + +// time.slice(0, 2): method that return the positions 0 and 1 of the string, +// const hours = Number(time.slice(0, 2)) will convert the substring in numbers to manipulate and performs calculations. + function formatAs12HourClock(time) { - const hours = Number(time.slice(0, 2)); - if (hours > 12) { - return `${hours - 12}:00 pm`; + const hours = Number(time.slice(0, 2)); //Extracts characters from position 0 to 2 (not including the character at index 2) + const minutes = time.slice(3, 5); // extract characters from position 3 to 5 (for minutes part) + + if (hours === 0) { + return `12:${minutes} am`; + } else if (hours === 12) { + return `12:${minutes} pm`; + } else if (hours > 12) { + return `${hours - 12}:${minutes} pm`; + } else { + return `${hours}:${minutes} am`; } - return `${time} am`; + //the previous conditions always lead to a return } -const currentOutput = formatAs12HourClock("08:00"); -const targetOutput = "08:00 am"; + +// ============================= test =============================== + +const currentOutput = formatAs12HourClock("00:42"); +const targetOutput = "12:42 am"; console.assert( currentOutput === targetOutput, `current output: ${currentOutput}, target output: ${targetOutput}` ); -const currentOutput2 = formatAs12HourClock("23:00"); -const targetOutput2 = "11:00 pm"; + +// ============================= test 1 ============================= + +const currentOutput1 = formatAs12HourClock("00:00"); +const targetOutput1 = "12:00 am"; +console.assert( + currentOutput1 === targetOutput1, + `current output: ${currentOutput1}, target output: ${targetOutput1}` +); + + +// ============================= test 2 failed ====================== + +const currentOutput2 = formatAs12HourClock("26:00"); //26 > 14; go in the second else if, 26-12=14 +const targetOutput2 = "10:00 pm"; + console.assert( currentOutput2 === targetOutput2, - `current output: ${currentOutput2}, target output: ${targetOutput2}` + `current output time: ${currentOutput2}, target output: ${targetOutput2}` + //will print Assertion failed: current output time: 14:00 pm, target output: 10:00 pm ); + + + +const testCases = [ + { input: "00:00", expected: "12:00 am" }, + { input: "12:00", expected: "12:00 pm" }, + { input: "15:30", expected: "3:30 pm" }, + { input: "08:05", expected: "8:05 am" }, + { input: "23:59", expected: "11:59 pm" }, +]; + +for (const { input, expected } of testCases) { + const result = formatAs12HourClock(input); + console.assert( + result === expected, + `Input: ${input} | Expected: ${expected}, but got: ${result}` + ); +} + +// ================ icons test with console/log ======================== + +const testCasesIcons = [ + { input: "25:00", expected: "12:00 am" }, //test failed + { input: "12:00", expected: "12:00 pm" }, + { input: "15:30", expected: "3:30 pm" }, + { input: "08:05", expected: "8:05 am" }, + { input: "23:59", expected: "11:59 pm" }, +]; + + +for (const { input, expected } of testCasesIcons) { + const result = formatAs12HourClock(input); + if (result === expected) { + console.log(`✅ Test passed! Input: ${input} | Output: ${result}`); + } else { + console.error( + `❌ Test failed! Input: ${input} | Expected: ${expected}, but got: ${result}` + ); + } +} + + diff --git a/Sprint-2/implement/bmi.js b/Sprint-2/implement/bmi.js index 259f62d48..8e8f5d506 100644 --- a/Sprint-2/implement/bmi.js +++ b/Sprint-2/implement/bmi.js @@ -13,3 +13,37 @@ // Given someone's weight in kg and height in metres // Then when we call this function with the weight and height // It should return their Body Mass Index to 1 decimal place + +// ============================= BMI TEST =============================== + +function bodyMassIndex(weight, height) { + const kilograms = Number(weight); + const metres = Number(height); + + if (kilograms > 0 && metres > 0) { + const bmi = kilograms / metres ** 2; + return Math.round(bmi * 10) / 10; + } + return "Invalid input. Please enter valid weight and height."; +} + +//Avoid .toFixed() if we need a number (as .toFixed() returns a string). +console.log(bodyMassIndex(70, 0)); + + +/* + Dynamic Precision with Math.round() + Combining Math.pow() with Math.round() offers a dynamic solution for those + seeking a more flexible approach that can adapt to rounding to various decimal + places. + + function roundTo(num, precision) { + const factor = Math.pow(10, precision) + return Math.round(num * factor) / factor + } + console.log(roundTo(4.687, 0)); // Output: 5 + console.log(roundTo(4.687, 1)); //one decimal place + console.log(roundTo(4.687, 2)); //two decimal places + console.log(roundTo(4.687, 3)); // Output: 4.687 + +*/ diff --git a/Sprint-2/implement/cases.js b/Sprint-2/implement/cases.js index 9e56a27b6..89a70139f 100644 --- a/Sprint-2/implement/cases.js +++ b/Sprint-2/implement/cases.js @@ -13,3 +13,63 @@ // You will need to come up with an appropriate name for the function // Use the string documentation to help you find a solution + + + +// ================== Strings in UpperCase ===================== + +function convertUpperCaseString(str) { + let UPPER_SNAKE_CASE = ""; +// console.log(typeof str); + + for (let i = 0; i < str.length; i++) { + if (str[i] === " ") { + UPPER_SNAKE_CASE += "_"; + } else UPPER_SNAKE_CASE += str[i].toUpperCase();; + } + + return UPPER_SNAKE_CASE; +} + +console.log(convertUpperCaseString("hola there")); + +// ================ First letter capitalized =================== + + +function firstLetterCapitalized1(str) { + let result = ""; + for (let i = 0; i < str.length; i++) { + if (i === 0 || str[i - 1] === " ") { + result += str[i].toUpperCase(); + } else { + result += str[i]; + } + } + return result; +} + +console.log(firstLetterCapitalized1("first letter capitalized")); + + +// ================ Last letter capitalized =================== + +let quote = 'He said, "It\'s a sunny day!"'; + +function lastLetterCapitalized(str) { + let result = ""; + + for (let i = 0; i < str.length; i++) { + if (i === str.length - 1 || str[i + 1] === " " ) { + result += str[i].toUpperCase(); + } else { + result += str[i]; + } + // console.log(`positions ${i}: of str ${str[i]}`); + + } + return result; +} + +console.log(lastLetterCapitalized(`hola there ${quote}`)); + + diff --git a/Sprint-2/implement/to-pounds.js b/Sprint-2/implement/to-pounds.js index 6265a1a70..32d9dfc3a 100644 --- a/Sprint-2/implement/to-pounds.js +++ b/Sprint-2/implement/to-pounds.js @@ -4,3 +4,82 @@ // 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 from Sprint-1 =============================== + + +const penceString = "399"; + +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}`); + +// ================= Converted as reusable block of code ======================== + +function convertPenceToPound1(priceAmount) { + const numberwithoutpence = priceAmount.substring(0, priceAmount.length - 1); + const paddedPenceNumberString = numberwithoutpence.padStart(3, "0"); + const pounds = paddedPenceNumberString.substring( + 0, + paddedPenceNumberString.length - 2 + ); + const pence = paddedPenceNumberString + .substring(paddedPenceNumberString.length - 2) + .padEnd(2, "0"); + + return `£${pounds}.${pence}`; +} + +priceAmount = "999p" + +console.log(convertPenceToPound1(priceAmount)); + + +// ==================== function handling decimal inputs ======================== + +money = "0.23p"; + +function convertPenceToPounds(money) { + const cleanInput = money.substring(0, money.length - 1); + + if (cleanInput.includes(".")) { + const [pounds, pence] = cleanInput.split("."); //destructuring; + const formattedPence = pence.padEnd(2, "0"); + return `£${pounds}.${formattedPence}`; + } else { + // Handle the integer case (e.g., "399p") + const paddedPenceNumberString = cleanInput.padStart(3, "0"); + const pounds = paddedPenceNumberString.substring( + 0, + paddedPenceNumberString.length - 2 + ); + const pence = paddedPenceNumberString + .substring(paddedPenceNumberString.length - 2) + .padEnd(2, "0"); + + return `£${pounds}.${pence}`; + } +} + +console.log(convertPenceToPounds(money)); // "£0.23" +console.log(convertPenceToPounds("399p")); // "£3.99" +console.log(convertPenceToPounds("3.99p")); // "£3.99" +console.log(convertPenceToPounds("50p")); // "£0.50" +console.log(convertPenceToPounds("65p")); // £0.65 +console.log(convertPenceToPounds("0.3p")); // "£0.30" \ No newline at end of file diff --git a/Sprint-2/implement/vat.js b/Sprint-2/implement/vat.js index 3fb167226..5fb6015c6 100644 --- a/Sprint-2/implement/vat.js +++ b/Sprint-2/implement/vat.js @@ -8,3 +8,16 @@ // Given a number, // When I call this function with a number // it returns the new price with VAT added on + + +function addVatporcentage (price) { + const vatIncluded = Number(price * 1.2); //converted the str into number + return `Vat included ${vatIncluded}`; + +} + +console.log(addVatporcentage("30")); + +/* + This will return the new price with the vat included and also converted the string into number with the method Number() +*/ \ No newline at end of file diff --git a/Sprint-2/interpret/time-format.js b/Sprint-2/interpret/time-format.js index c5a0c1619..5a7a276d2 100644 --- a/Sprint-2/interpret/time-format.js +++ b/Sprint-2/interpret/time-format.js @@ -1,4 +1,5 @@ function pad(num) { + console.log(num); return num.toString().padStart(2, "0"); } @@ -7,25 +8,32 @@ function formatTimeDisplay(seconds) { const totalMinutes = (seconds - remainingSeconds) / 60; const remainingMinutes = totalMinutes % 60; const totalHours = (totalMinutes - remainingMinutes) / 60; - - return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad( - remainingSeconds - )}`; + return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`; } -// You will need to play computer with this example - use the Python Visualiser https://pythontutor.com/visualize.html#mode=edit -// to help you answer these questions +console.log(formatTimeDisplay(61)); + +/* +You will need to play computer with this example - use the Python Visualiser https://pythontutor.com/visualize.html#mode=edit +to help you answer these questions -// Questions +Questions -// a) When formatTimeDisplay is called how many times will pad be called? +a) When formatTimeDisplay is called how many times will pad be called? + - 3 times, pad is called three times, once for each part of the time: hours, minutes, and seconds. -// Call formatTimeDisplay with an input of 61, now answer the following: +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? +b) What is the value assigned to num when pad is called for the first time? + - 0, because the first pad is totalHours and we don't have any hours yet, only minutes -// c) What is the return value of pad is called for the first time? +c) What is the return value of pad is called for the first time? + - "00" and calling formatTimeDisplay(61) = 00:01:01 -// d) What is the value assigned to num when pad is called for the last time in this program? Explain your answer +d) What is the value assigned to num when pad is called for the last time in this program? Explain your answer + - In this case, the value of num before it is passed to pad is 1 (the remainder when 61 are divided by 60). -// e) What is the return value assigned to num when pad is called for the last time in this program? Explain your answer +e) What is the return value assigned to num when pad is called for the last time in this program? Explain your answer + - After pad processes 1, it will return the value "01" because it ensures the number is two digits long (by adding a leading zero) +*/