From a29c6b519bd50b5705e610630a976ec782f44e37 Mon Sep 17 00:00:00 2001 From: sripathman Date: Sat, 22 Feb 2025 10:47:21 +0000 Subject: [PATCH 1/5] sprint 1 --- Sprint-1/1-key-exercises/1-count.js | 9 ++++++ Sprint-1/1-key-exercises/2-initials.js | 9 ++++-- Sprint-1/1-key-exercises/3-paths.js | 9 ++++-- Sprint-1/1-key-exercises/4-random.js | 10 ++++++ Sprint-1/2-mandatory-errors/0.js | 5 ++- Sprint-1/2-mandatory-errors/1.js | 5 +++ Sprint-1/2-mandatory-errors/2.js | 6 +++- Sprint-1/2-mandatory-errors/3.js | 4 +++ Sprint-1/2-mandatory-errors/4.js | 4 ++- .../1-percentage-change.js | 23 +++++++++++++ .../3-mandatory-interpret/2-time-format.js | 26 +++++++++++++++ Sprint-1/3-mandatory-interpret/3-to-pounds.js | 32 ++++++++++++++++++- readme.md | 2 +- 13 files changed, 135 insertions(+), 9 deletions(-) diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..669b98bb9 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -4,3 +4,12 @@ count = count + 1; // Line 1 is a variable declaration, creating the count variable with an initial value of 0 // Describe what line 3 is doing, in particular focus on what = is doing +/* count + 1 is evaluated. This takes the current value of count (which is 0) and adds 1 to it, resulting in 1. +The result of the addition (1) is then assigned to the variable count. This overwrites the previous value of count (which was 0) with the new value (1). + +So, after line 3 is executed, the variable count will hold the value 1. +*/ +/*The += symbol in this context is the assignment operator. It means "take the value of what is on + the right-hand side and store it in the variable on the left-hand side." + */ \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..a30923823 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -3,9 +3,14 @@ let middleName = "Katherine"; 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. +// 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 = ``; + + +let initials = firstName.charAt(0) + middleName.charAt(0) + lastName.charAt(0); + +console.log(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..81840195a 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -17,7 +17,12 @@ 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 dir = filePath.slice(0, lastSlashIndex + 1); +const lastDotIndex = base.lastIndexOf("."); +const ext = lastDotIndex > -1 ? base.slice(lastDotIndex) : ""; // Handle cases with no extension + +console.log(`The dir part of ${filePath} is ${dir}`); +console.log(`The ext part of ${filePath} 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..2e0a02461 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -7,3 +7,13 @@ 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 +console.log(num); // Output the generated random number + + +/*num represents a random integer between 1 and 100 (inclusive). */ + +/*Math.random() +This means it can return 0, but it will never return 1. +Think of it as generating a random fraction between 0 and 1. */ + +/* */ diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js index cf6c5039f..7aa17674f 100644 --- a/Sprint-1/2-mandatory-errors/0.js +++ b/Sprint-1/2-mandatory-errors/0.js @@ -1,2 +1,5 @@ This is just an instruction for the first activity - but it is just for human consumption -We don't want the computer to run these 2 lines - how can we solve this problem? \ No newline at end of file +We don't want the computer to run these 2 lines - how can we solve this problem? +in javascript . +// This is just an instruction for the first activity - but it is just for human consumption +// We don't want the computer to run these 2 lines - how can we solve this problem? \ 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..f2237b5b8 100644 --- a/Sprint-1/2-mandatory-errors/1.js +++ b/Sprint-1/2-mandatory-errors/1.js @@ -2,3 +2,8 @@ const age = 33; age = age + 1; +/* In JavaScript (and many other languages), const declares a constant, + meaning its value cannot be changed after it's initially assigned. */ + let age = 33; +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..2f6395885 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/2-mandatory-errors/2.js @@ -2,4 +2,8 @@ // what's the error ? console.log(`I was born in ${cityOfBirth}`); -const cityOfBirth = "Bolton"; +//const cityOfBirth = "Bolton"; +/*Always declare your variables (especially const and let) + before you attempt to use them*/ + const cityOfBirth = "Bolton"; + console.log(`I was born in ${cityOfBirth}`); \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js index ec101884d..2becfec89 100644 --- a/Sprint-1/2-mandatory-errors/3.js +++ b/Sprint-1/2-mandatory-errors/3.js @@ -7,3 +7,7 @@ const last4Digits = cardNumber.slice(-4); // Then run the code and see what error it gives. // Consider: Why does it give this error? Is this what I predicted? If not, what's different? // Then try updating the expression last4Digits is assigned to, in order to get the correct value +/* we declare cardNumber as number . slice , This function for string */ +const cardNumber = 4533787178994213; +const last4Digits = String(cardNumber).slice(-4); // Convert to string first +console.log(last4Digits); diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js index 21dad8c5d..28829a05e 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,4 @@ const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +const 24hourClockTime = "08:53"; +const twelveHourClockTime = "20:53"; +const twentyFourHourClockTime = "08:53"; \ 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..340610174 100644 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-1/3-mandatory-interpret/1-percentage-change.js @@ -20,3 +20,26 @@ console.log(`The percentage change is ${percentageChange}`); // d) Identify all the lines that are variable declarations // e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? +a) carPrice.replaceAll(",", "") +priceAfterOneYear.replaceAll(",", "") +Number() +console.log() +b) + There's a missing comma after the first argument in replaceAll. It should be: + priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); + c) + carPrice = Number(carPrice.replaceAll(",", "")); +priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); +d) +let carPrice = "10,000"; +let priceAfterOneYear = "8,543"; +const priceDifference = carPrice - priceAfterOneYear; +const percentageChange = (priceDifference / carPrice) * 100; +e) +carPrice.replaceAll(",", ""): This part uses the replaceAll method to +replace all occurrences of the comma (,) within the carPrice string with + an empty string (""). This removes the comma from the + string "10,000", +resulting in the string "10000". + +Number(): The Number() function convert the string as Number \ 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..1151db6e5 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -23,3 +23,29 @@ console.log(result); // e) What do you think the variable result represents? Can you think of a better name for this variable? // f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer +a) +result is also a variable declaration, there are six. +b) +There is one function call: console.log(result) + +c) +The % symbol is the modulo operator. + the modulo operator returns the remainder of a division. + So, movieLength % 60 calculates the remainder when movieLength is divided + by 60. +d) +movieLength - remainingSeconds: This subtracts the remaining seconds + from the total seconds. +/ 60: this division gives you the total number of whole minutes in the movie. + +e) +1)The variable result represents the formatted movie length in hours, minutes, and seconds (HH:MM:SS format). + + 2)formattedTime or formattedMovieLength. + f) + +1)The modulo operator and integer division will handle positive integer values correctly. +2) If movieLength is 0, the code will correctly produce "0:0:0". +3)If movieLength is negative, the modulo operator will return a negative +remainder. While the code might technically run, +the output will not be a correct \ 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..5fc971dd0 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -24,4 +24,34 @@ console.log(`£${pounds}.${pence}`); // Try and describe the purpose / rationale behind each step // To begin, we can start with -// 1. const penceString = "399p": initialises a string variable with the value "399p" +/* 1. const penceString = "399p": initialises a string variable with + the value "399p" + 2. + const penceString = "399p";: + This line initializes a constant variable named penceString and assigns it the string value "399p". This string represents a price in pence. The const keyword means the variable's value cannot be reassigned later in the program. + +const penceStringWithoutTrailingP = penceString.substring(0, penceString.length - 1);: + This line creates a new constant variable called penceStringWithoutTrailingP. It uses the substring() method to extract a portion of the penceString. penceString.length gets the total length of the string (5 in this case). Subtracting 1 gives us 4. substring(0, 4) extracts the characters from index 0 up to (but not including) index 4, effectively removing the last character "p". The result, "399", is stored in penceStringWithoutTrailingP. The rationale is to isolate the numerical part of the pence value. + +const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");: + This line creates another constant, paddedPenceNumberString. It uses the padStart() method to + pad the penceStringWithoutTrailingP with leading zeros until it reaches a length of 3. If the + string is already 3 or more characters long, no padding is added. In our example, "399" is + already 3 digits, so no padding occurs. The result, "399", is stored in paddedPenceNumberString. + The rationale for padding is to ensure that even single-digit or double-digit pence values are + formatted correctly when converted to pounds and pence (e.g., "9p" becomes "009"). + +const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2);: + This line extracts the pounds portion of the price. paddedPenceNumberString.length - 2 calculates the index + two characters from the end. substring(0, paddedPenceNumberString.length - 2) extracts the + characters from the beginning up to that index. + In our example, paddedPenceNumberString.length is 3, + so paddedPenceNumberString.length - 2 is 1. substring(0, 1) extracts the first character, "3". + The result, "3", is assigned to the pounds constant. The rationale is to separate the pounds from + the pence. + +const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2).padEnd(2, "0");: + This line extracts the pence portion. paddedPenceNumberString.substring(paddedPenceNumberString.length - 2) extracts the last two characters of the padded number string ("99" in our example). The padEnd(2, "0") method ensures that the pence value has at least two digits, adding trailing zeros if necessary. In our case, "99" already has two digits, so no padding is added. The result, "99", is assigned to the pence constant. The rationale is to isolate the pence value. + +console.log(£pounds.{pence});: This line uses a template literal (backticks) to create a string that combines the pounds and pence values with a pound symbol and a decimal point. It then uses console.log() to print this formatted string to the console. In our example, it will print "£3.99". This is the final formatted price in pounds and pence. + */ diff --git a/readme.md b/readme.md index 873178bda..13cd25f5b 100644 --- a/readme.md +++ b/readme.md @@ -2,7 +2,7 @@ > https://programming.codeyourfuture.io/structuring-data/ -> [!TIP] +> [!TIP]k > You should always do the prep work _before_ attempting the coursework. > The prep shows you _how_ to do the coursework. > There is often a step by step video you can code along with too. From 5399c46b91e9bf662f3b655fb9162f6fa30f5c3d Mon Sep 17 00:00:00 2001 From: sripathman Date: Sun, 9 Mar 2025 19:14:46 +0000 Subject: [PATCH 2/5] sprint-3 feature --- Sprint-3/1-key-implement/1-get-angle-type.js | 21 ++++++++--- .../1-key-implement/2-is-proper-fraction.js | 16 +++++++-- Sprint-3/1-key-implement/3-get-card-value.js | 36 ++++++++++++++++--- .../2-mandatory-rewrite/1-get-angle-type.js | 20 ++++------- .../1-get-angle-type.test.js | 36 +++++++++++-------- .../2-is-proper-fraction.js | 10 ++++-- .../2-is-proper-fraction.test.js | 14 ++++++++ .../2-mandatory-rewrite/3-get-card-value.js | 25 ++++++++++--- .../3-get-card-value.test.js | 22 ++++++++++++ .../3-mandatory-practice/implement/count.js | 16 ++++++--- .../implement/count.test.js | 34 ++++++++++++++++++ .../3-mandatory-practice/implement/repeat.js | 17 +++++++-- .../implement/repeat.test.js | 25 ++++++++++--- 13 files changed, 235 insertions(+), 57 deletions(-) diff --git a/Sprint-3/1-key-implement/1-get-angle-type.js b/Sprint-3/1-key-implement/1-get-angle-type.js index 08d1f0cba..149c1e982 100644 --- a/Sprint-3/1-key-implement/1-get-angle-type.js +++ b/Sprint-3/1-key-implement/1-get-angle-type.js @@ -6,18 +6,25 @@ // The assertion error will tell you what the expected output is // Write the code to pass the test // Then, write the next test! :) Go through this process until all the cases are implemented - +/* function getAngleType(angle) { if (angle === 90) return "Right angle"; // read to the end, complete line 36, then pass your test here } - +*/ +function getAngleType(angle) { + if (angle === 90) return "Right angle"; + if (angle < 90) return "Acute angle"; + if (angle > 90 && angle < 180) return "Obtuse angle"; + if (angle === 180) return "Straight angle"; + if (angle > 180 && angle < 360) return "Reflex angle"; +} // we're going to use this helper function to make our assertions easier to read // if the actual output matches the target output, the test will pass function assertEquals(actualOutput, targetOutput) { console.assert( actualOutput === targetOutput, - `Expected ${actualOutput} to equal ${targetOutput}` + `Expected ${actualOutput} to equal ${targetOutput}` ); } @@ -44,13 +51,17 @@ assertEquals(acute, "Acute angle"); // Then the function should return "Obtuse angle" const obtuse = getAngleType(120); // ====> write your test here, and then add a line to pass the test in the function above - +assertEquals(obtuse, "Obtuse angle"); // Case 4: Identify Straight Angles: // When the angle is exactly 180 degrees, // Then the function should return "Straight angle" // ====> write your test here, and then add a line to pass the test in the function above +const straight = getAngleType(180); +assertEquals(straight, "Straight angle"); // Case 5: Identify Reflex Angles: // When the angle is greater than 180 degrees and less than 360 degrees, // Then the function should return "Reflex angle" -// ====> write your test here, and then add a line to pass the test in the function above \ No newline at end of file +// ====> write your test here, and then add a line to pass the test in the function above +const reflex = getAngleType(270); +assertEquals(reflex, "Reflex angle"); \ No newline at end of file diff --git a/Sprint-3/1-key-implement/2-is-proper-fraction.js b/Sprint-3/1-key-implement/2-is-proper-fraction.js index 91583e941..1965fa5b9 100644 --- a/Sprint-3/1-key-implement/2-is-proper-fraction.js +++ b/Sprint-3/1-key-implement/2-is-proper-fraction.js @@ -7,8 +7,10 @@ // complete the rest of the tests and cases // write one test at a time, and make it pass, build your solution up methodically + function isProperFraction(numerator, denominator) { - if (numerator < denominator) return true; + if (numerator < denominator && denominator !== 0) return true; + return false; } // here's our helper again @@ -41,13 +43,23 @@ assertEquals(improperFraction, false); // Explanation: The fraction -4/7 is a proper fraction because the absolute value of the numerator (4) is less than the denominator (7). The function should return true. const negativeFraction = isProperFraction(-4, 7); // ====> complete with your assertion - +assertEquals(negativeFraction, true); // Equal Numerator and Denominator check: // Input: numerator = 3, denominator = 3 // target output: false // Explanation: The fraction 3/3 is not a proper fraction because the numerator is equal to the denominator. The function should return false. const equalFraction = isProperFraction(3, 3); // ====> complete with your assertion +assertEquals(equalFraction, false); // Stretch: // What other scenarios could you test for? + +// Zero Numerator check: + +const zeroNumerator = isProperFraction(0, 5); +assertEquals(zeroNumerator, true); + +// Zero Denominator check: +const zeroDenominator = isProperFraction(5, 0); +assertEquals(zeroDenominator, false); \ No newline at end of file diff --git a/Sprint-3/1-key-implement/3-get-card-value.js b/Sprint-3/1-key-implement/3-get-card-value.js index aa1cc9f90..ee3520fcf 100644 --- a/Sprint-3/1-key-implement/3-get-card-value.js +++ b/Sprint-3/1-key-implement/3-get-card-value.js @@ -8,7 +8,21 @@ // write one test at a time, and make it pass, build your solution up methodically // just make one change at a time -- don't rush -- programmers are deep and careful thinkers function getCardValue(card) { - if (rank === "A") return 11; + const rank = card.slice(0, -1); // Extract the rank (e.g., "A", "2", "K") + if (rank === "A") return 11; + if (rank === "2") return 2; + if (rank === "3") return 3; + if (rank === "4") return 4; + if (rank === "5") return 5; + if (rank === "6") return 6; + if (rank === "7") return 7; + if (rank === "8") return 8; + if (rank === "9") return 9; + if (rank === "10") return 10; + if (rank === "J") return 10; + if (rank === "Q") return 10; + if (rank === "K") return 10; + return 0; // Default case (shouldn't happen with valid cards) } // You need to write assertions for your function to check it works in different cases @@ -20,6 +34,7 @@ function assertEquals(actualOutput, targetOutput) { `Expected ${actualOutput} to equal ${targetOutput}` ); } + // Acceptance criteria: // Given a card string in the format "A♠" (representing a card in blackjack - the last character will always be an emoji for a suit, and all characters before will be a number 2-10, or one letter of J, Q, K, A), @@ -34,18 +49,29 @@ assertEquals(aceofSpades, 11); // Then it should return the numeric value corresponding to the rank (e.g., "5" should return 5). const fiveofHearts = getCardValue("5♥"); // ====> write your test here, and then add a line to pass the test in the function above - +assertEquals(fiveofHearts, 5); // Handle Face Cards (J, Q, K): // Given a card with a rank of "10," "J," "Q," or "K", // When the function is called with such a card, // Then it should return the value 10, as these cards are worth 10 points each in blackjack. - +const tenofDiamonds = getCardValue("10♦"); +assertEquals(tenofDiamonds, 10); +const jackofClubs = getCardValue("J♣"); +assertEquals(jackofClubs, 10); +const queenofSpades = getCardValue("Q♠"); +assertEquals(queenofSpades, 10); +const kingofHearts = getCardValue("K♥"); +assertEquals(kingofHearts, 10); // Handle Ace (A): // Given a card with a rank of "A", // When the function is called with an Ace, // Then it should, by default, assume the Ace is worth 11 points, which is a common rule in blackjack. - +const aceofClubs = getCardValue("A♣"); +assertEquals(aceofClubs, 11); // Handle Invalid Cards: // Given a card with an invalid rank (neither a number nor a recognized face card), -// When the function is called with such a card, +// When the function is called with such +// a card, // Then it should throw an error indicating "Invalid card rank." +const invalidCard = getCardValue("X♥"); +assertEquals(invalidCard, 0); \ No newline at end of file diff --git a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js index d61254bd7..859429532 100644 --- a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js +++ b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js @@ -1,18 +1,12 @@ function getAngleType(angle) { if (angle === 90) return "Right angle"; - // replace with your completed function from key-implement - + if (angle < 90 && angle > 0) return "Acute angle"; + if (angle > 90 && angle < 180) return "Obtuse angle"; + if (angle === 180) return "Straight angle"; + if (angle > 180 && angle < 360) return "Reflex angle"; + if (angle === 0) return "Zero angle"; + if (angle === 360) return "Full angle"; + return "Invalid angle"; } - - - - - - - -// Don't get bogged down in this detail -// Jest uses CommonJS module syntax by default as it's quite old -// We will upgrade our approach to ES6 modules in the next course module, so for now -// we have just written the CommonJS module.exports syntax for you module.exports = getAngleType; \ No newline at end of file diff --git a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.test.js b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.test.js index b62827b7c..0e153c8fe 100644 --- a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.test.js +++ b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.test.js @@ -4,21 +4,27 @@ test("should identify right angle (90°)", () => { expect(getAngleType(90)).toEqual("Right angle"); }); -// REPLACE the comments with the tests -// make your test descriptions as clear and readable as possible - -// Case 2: Identify Acute Angles: -// When the angle is less than 90 degrees, -// Then the function should return "Acute angle" +test("should identify acute angles (less than 90°)", () => { + expect(getAngleType(30)).toEqual("Acute angle"); + expect(getAngleType(60)).toEqual("Acute angle"); + expect(getAngleType(1)).toEqual("Acute angle"); + expect(getAngleType(89)).toEqual("Acute angle"); +}); -// Case 3: Identify Obtuse Angles: -// When the angle is greater than 90 degrees and less than 180 degrees, -// Then the function should return "Obtuse angle" +test("should identify obtuse angles (greater than 90° and less than 180°)", () => { + expect(getAngleType(120)).toEqual("Obtuse angle"); + expect(getAngleType(150)).toEqual("Obtuse angle"); + expect(getAngleType(91)).toEqual("Obtuse angle"); + expect(getAngleType(179)).toEqual("Obtuse angle"); +}); -// Case 4: Identify Straight Angles: -// When the angle is exactly 180 degrees, -// Then the function should return "Straight angle" +test("should identify straight angle (180°)", () => { + expect(getAngleType(180)).toEqual("Straight angle"); +}); -// Case 5: Identify Reflex Angles: -// When the angle is greater than 180 degrees and less than 360 degrees, -// Then the function should return "Reflex angle" +test("should identify reflex angles (greater than 180° and less than 360°)", () => { + expect(getAngleType(210)).toEqual("Reflex angle"); + expect(getAngleType(270)).toEqual("Reflex angle"); + expect(getAngleType(300)).toEqual("Reflex angle"); + expect(getAngleType(359)).toEqual("Reflex angle"); +}); \ No newline at end of file diff --git a/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.js b/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.js index 9836fe398..6585c7d53 100644 --- a/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.js +++ b/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.js @@ -1,6 +1,12 @@ function isProperFraction(numerator, denominator) { - if (numerator < denominator) return true; - // add your completed function from key-implement here + if (denominator === 0) { + return false; + } + if (Math.abs(numerator) < Math.abs(denominator)) { + return true; + } else { + return false; + } } module.exports = isProperFraction; \ No newline at end of file diff --git a/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.test.js b/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.test.js index ff1cc8173..cbef92f20 100644 --- a/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.test.js +++ b/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.test.js @@ -5,7 +5,21 @@ test("should return true for a proper fraction", () => { }); // Case 2: Identify Improper Fractions: +test("should return false for an improper fraction", () => { + expect(isProperFraction(4, 3)).toEqual(false); + expect(isProperFraction(5, 2)).toEqual(false); +}); // Case 3: Identify Negative Fractions: +test("should handle negative numerators and denominators", () => { + expect(isProperFraction(-1, 2)).toEqual(true); + expect(isProperFraction(1, -2)).toEqual(true); + expect(isProperFraction(-3, -2)).toEqual(false); + expect(isProperFraction(-2, -3)).toEqual(true); +}); // Case 4: Identify Equal Numerator and Denominator: +test("should return false for equal numerator and denominator", () => { + expect(isProperFraction(3, 3)).toEqual(false); + expect(isProperFraction(1, 1)).toEqual(false); +}); \ No newline at end of file diff --git a/Sprint-3/2-mandatory-rewrite/3-get-card-value.js b/Sprint-3/2-mandatory-rewrite/3-get-card-value.js index 0d95d3736..79f64d72c 100644 --- a/Sprint-3/2-mandatory-rewrite/3-get-card-value.js +++ b/Sprint-3/2-mandatory-rewrite/3-get-card-value.js @@ -1,5 +1,22 @@ function getCardValue(card) { - // replace with your code from key-implement - return 11; -} -module.exports = getCardValue; \ No newline at end of file + if (typeof card !== 'string' || card.length < 1) { + return 0; // Or throw an error, depending on desired behavior for invalid cards. + } + + const value = card[0]; + + if (value === 'A') { + return 11; + } else if (['J', 'Q', 'K'].includes(value)) { + return 10; + } else if (['2', '3', '4', '5', '6', '7', '8', '9', '10'].includes(value)) { + if(value === '1' && card[1] === '0'){ + return 10; + } + return parseInt(value); + } else { + return 0; // Or throw an error, depending on desired behavior for invalid cards. + } + } + + module.exports = getCardValue; \ No newline at end of file diff --git a/Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js b/Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js index 03a8e2f34..e6496c419 100644 --- a/Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js +++ b/Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js @@ -6,6 +6,28 @@ test("should return 11 for Ace of Spades", () => { }); // Case 2: Handle Number Cards (2-10): +test("should return 2-9 for number cards", () => { + expect(getCardValue("2♥")).toEqual(2); + expect(getCardValue("5♦")).toEqual(5); + expect(getCardValue("9♣")).toEqual(9); + }); // Case 3: Handle Face Cards (J, Q, K): +test("should return 10 for face cards", () => { + expect(getCardValue("J♥")).toEqual(10); + expect(getCardValue("Q♦")).toEqual(10); + expect(getCardValue("K♣")).toEqual(10); + }); // Case 4: Handle Ace (A): +test("should return 11 for Ace", () => { + expect(getCardValue("A♥")).toEqual(11); + expect(getCardValue("A♦")).toEqual(11); + expect(getCardValue("A♣")).toEqual(11); + }); // Case 5: Handle Invalid Cards: +test("should return 0 for invalid cards", () => { + expect(getCardValue("X")).toEqual(0); + expect(getCardValue("")).toEqual(0); + expect(getCardValue(123)).toEqual(0); + expect(getCardValue(null)).toEqual(0); + expect(getCardValue(undefined)).toEqual(0); + }); \ No newline at end of file diff --git a/Sprint-3/3-mandatory-practice/implement/count.js b/Sprint-3/3-mandatory-practice/implement/count.js index fce249650..88fb729a9 100644 --- a/Sprint-3/3-mandatory-practice/implement/count.js +++ b/Sprint-3/3-mandatory-practice/implement/count.js @@ -1,5 +1,11 @@ -function countChar(stringOfCharacters, findCharacter) { - return 5 -} - -module.exports = countChar; \ No newline at end of file +const countChar = (str, char) => { + let count = 0; + for (let i = 0; i < str.length; i++) { + if (str[i] === char) { + count++; + } + } + return count; + }; + + module.exports = countChar; \ No newline at end of file diff --git a/Sprint-3/3-mandatory-practice/implement/count.test.js b/Sprint-3/3-mandatory-practice/implement/count.test.js index 42baf4b4b..72477e1e0 100644 --- a/Sprint-3/3-mandatory-practice/implement/count.test.js +++ b/Sprint-3/3-mandatory-practice/implement/count.test.js @@ -22,3 +22,37 @@ test("should count multiple occurrences of a character", () => { // And a character char that does not exist within the case-sensitive str, // When the function is called with these inputs, // Then it should return 0, indicating that no occurrences of the char were found in the case-sensitive str. +// Scenario: No Occurrences +// Given the input string str, +// And a character char that does not exist within the case-sensitive str, +// When the function is called with these inputs, +// Then it should return 0, indicating that no occurrences of the char were found in the case-sensitive str. + +test("should return 0 when character does not exist", () => { + const str = "hello"; + const char = "z"; + const count = countChar(str, char); + expect(count).toEqual(0); +}); + +test("should handle empty string", () => { + const str = ""; + const char = "a"; + const count = countChar(str, char); + expect(count).toEqual(0); +}); + +test("should handle empty character", () => { + const str = "abc"; + const char = ""; + const count = countChar(str, char); + expect(count).toEqual(0); +}); + +test("should handle string with different case", () => { + const str = "aBcDa"; + const char = "a"; + const count = countChar(str, char); + expect(count).toEqual(2); +}); + diff --git a/Sprint-3/3-mandatory-practice/implement/repeat.js b/Sprint-3/3-mandatory-practice/implement/repeat.js index 621f9bd35..d6cd83532 100644 --- a/Sprint-3/3-mandatory-practice/implement/repeat.js +++ b/Sprint-3/3-mandatory-practice/implement/repeat.js @@ -1,5 +1,18 @@ -function repeat() { - return "hellohellohello"; +// repeat.js +function repeat(str, count) { + if (count < 0) { + throw new Error("Count must be a non-negative integer."); + } + + if (count === 0) { + return ""; + } + + let result = ""; + for (let i = 0; i < count; i++) { + result += str; + } + return result; } module.exports = repeat; \ No newline at end of file diff --git a/Sprint-3/3-mandatory-practice/implement/repeat.test.js b/Sprint-3/3-mandatory-practice/implement/repeat.test.js index 8a4ab42ef..db54d1733 100644 --- a/Sprint-3/3-mandatory-practice/implement/repeat.test.js +++ b/Sprint-3/3-mandatory-practice/implement/repeat.test.js @@ -3,7 +3,7 @@ const repeat = require("./repeat"); // Given a target string str and a positive integer count, // When the repeat function is called with these inputs, // Then it should: - +describe("repeat function", () => { // case: repeat String: // Given a target string str and a positive integer count, // When the repeat function is called with these inputs, @@ -19,14 +19,31 @@ test("should repeat the string count times", () => { // case: handle Count of 1: // Given a target string str and a count equal to 1, // When the repeat function is called with these inputs, -// Then it should return the original str without repetition, ensuring that a count of 1 results in no repetition. - +// Then it should return the original str without repetition, +// ensuring that a count of 1 results in no repetition. +test("should return the original str when count is 1", () => { + const str = "world"; + const count = 1; + const repeatedStr = repeat(str, count); + expect(repeatedStr).toEqual("world"); +}); // case: Handle Count of 0: // Given a target string str and a count equal to 0, // When the repeat function is called with these inputs, // Then it should return an empty string, ensuring that a count of 0 results in an empty output. - +test("should return an empty string when count is 0", () => { + const str = "test"; + const count = 0; + const repeatedStr = repeat(str, count); + expect(repeatedStr).toEqual(""); +}); // case: Negative Count: // Given a target string str and a negative integer count, // When the repeat function is called with these inputs, // Then it should throw an error or return an appropriate error message, as negative counts are not valid. +test("should throw an error for negative count", () => { + const str = "error"; + const count = -1; + expect(() => repeat(str, count)).toThrow("Count must be a non-negative integer."); +}); +}); \ No newline at end of file From 92d260158180f9cc9e3669fb2a09a3f37364f81d Mon Sep 17 00:00:00 2001 From: Sripathmanathan <111650472+sripathman@users.noreply.github.com> Date: Sat, 12 Apr 2025 12:47:10 +0100 Subject: [PATCH 3/5] Delete Sprint-1 directory --- Sprint-1/1-key-exercises/1-count.js | 15 ----- Sprint-1/1-key-exercises/2-initials.js | 16 ------ Sprint-1/1-key-exercises/3-paths.js | 28 --------- Sprint-1/1-key-exercises/4-random.js | 19 ------- Sprint-1/2-mandatory-errors/0.js | 5 -- Sprint-1/2-mandatory-errors/1.js | 9 --- Sprint-1/2-mandatory-errors/2.js | 9 --- Sprint-1/2-mandatory-errors/3.js | 13 ----- Sprint-1/2-mandatory-errors/4.js | 4 -- .../1-percentage-change.js | 45 --------------- .../3-mandatory-interpret/2-time-format.js | 51 ----------------- Sprint-1/3-mandatory-interpret/3-to-pounds.js | 57 ------------------- Sprint-1/4-stretch-explore/chrome.md | 18 ------ Sprint-1/4-stretch-explore/objects.md | 16 ------ Sprint-1/readme.md | 35 ------------ 15 files changed, 340 deletions(-) delete mode 100644 Sprint-1/1-key-exercises/1-count.js delete mode 100644 Sprint-1/1-key-exercises/2-initials.js delete mode 100644 Sprint-1/1-key-exercises/3-paths.js delete mode 100644 Sprint-1/1-key-exercises/4-random.js delete mode 100644 Sprint-1/2-mandatory-errors/0.js delete mode 100644 Sprint-1/2-mandatory-errors/1.js delete mode 100644 Sprint-1/2-mandatory-errors/2.js delete mode 100644 Sprint-1/2-mandatory-errors/3.js delete mode 100644 Sprint-1/2-mandatory-errors/4.js delete mode 100644 Sprint-1/3-mandatory-interpret/1-percentage-change.js delete mode 100644 Sprint-1/3-mandatory-interpret/2-time-format.js delete mode 100644 Sprint-1/3-mandatory-interpret/3-to-pounds.js delete mode 100644 Sprint-1/4-stretch-explore/chrome.md delete mode 100644 Sprint-1/4-stretch-explore/objects.md delete mode 100644 Sprint-1/readme.md diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js deleted file mode 100644 index 669b98bb9..000000000 --- a/Sprint-1/1-key-exercises/1-count.js +++ /dev/null @@ -1,15 +0,0 @@ -let count = 0; - -count = count + 1; - -// Line 1 is a variable declaration, creating the count variable with an initial value of 0 -// Describe what line 3 is doing, in particular focus on what = is doing -/* count + 1 is evaluated. This takes the current value of count (which is 0) and adds 1 to it, resulting in 1. -The result of the addition (1) is then assigned to the variable count. This overwrites the previous value of count (which was 0) with the new value (1). - -So, after line 3 is executed, the variable count will hold the value 1. -*/ -/*The -= symbol in this context is the assignment operator. It means "take the value of what is on - the right-hand side and store it in the variable on the left-hand side." - */ \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js deleted file mode 100644 index a30923823..000000000 --- a/Sprint-1/1-key-exercises/2-initials.js +++ /dev/null @@ -1,16 +0,0 @@ -let firstName = "Creola"; -let middleName = "Katherine"; -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 = firstName.charAt(0) + middleName.charAt(0) + lastName.charAt(0); - -console.log(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 deleted file mode 100644 index 81840195a..000000000 --- a/Sprint-1/1-key-exercises/3-paths.js +++ /dev/null @@ -1,28 +0,0 @@ -// The diagram below shows the different names for parts of a file path on a Unix operating system - -// ┌─────────────────────┬────────────┐ -// │ dir │ base │ -// ├──────┬ ├──────┬─────┤ -// │ root │ │ name │ ext │ -// " / home/user/dir / file .txt " -// └──────┴──────────────┴──────┴─────┘ - -// (All spaces in the "" line should be ignored. They are purely for formatting.) - -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 = filePath.slice(0, lastSlashIndex + 1); -const lastDotIndex = base.lastIndexOf("."); -const ext = lastDotIndex > -1 ? base.slice(lastDotIndex) : ""; // Handle cases with no extension - -console.log(`The dir part of ${filePath} is ${dir}`); -console.log(`The ext part of ${filePath} 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 deleted file mode 100644 index 2e0a02461..000000000 --- a/Sprint-1/1-key-exercises/4-random.js +++ /dev/null @@ -1,19 +0,0 @@ -const minimum = 1; -const maximum = 100; - -const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; - -// In this exercise, you will need to work out what num represents? -// 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 -console.log(num); // Output the generated random number - - -/*num represents a random integer between 1 and 100 (inclusive). */ - -/*Math.random() -This means it can return 0, but it will never return 1. -Think of it as generating a random fraction between 0 and 1. */ - -/* */ diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js deleted file mode 100644 index 7aa17674f..000000000 --- a/Sprint-1/2-mandatory-errors/0.js +++ /dev/null @@ -1,5 +0,0 @@ -This is just an instruction for the first activity - but it is just for human consumption -We don't want the computer to run these 2 lines - how can we solve this problem? -in javascript . -// This is just an instruction for the first activity - but it is just for human consumption -// We don't want the computer to run these 2 lines - how can we solve this problem? \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/1.js b/Sprint-1/2-mandatory-errors/1.js deleted file mode 100644 index f2237b5b8..000000000 --- a/Sprint-1/2-mandatory-errors/1.js +++ /dev/null @@ -1,9 +0,0 @@ -// trying to create an age variable and then reassign the value by 1 - -const age = 33; -age = age + 1; -/* In JavaScript (and many other languages), const declares a constant, - meaning its value cannot be changed after it's initially assigned. */ - let age = 33; -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 deleted file mode 100644 index 2f6395885..000000000 --- a/Sprint-1/2-mandatory-errors/2.js +++ /dev/null @@ -1,9 +0,0 @@ -// 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"; -/*Always declare your variables (especially const and let) - before you attempt to use them*/ - const cityOfBirth = "Bolton"; - console.log(`I was born in ${cityOfBirth}`); \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js deleted file mode 100644 index 2becfec89..000000000 --- a/Sprint-1/2-mandatory-errors/3.js +++ /dev/null @@ -1,13 +0,0 @@ -const cardNumber = 4533787178994213; -const last4Digits = cardNumber.slice(-4); - -// The last4Digits variable should store the last 4 digits of cardNumber -// However, the code isn't working -// Before running the code, make and explain a prediction about why the code won't work -// Then run the code and see what error it gives. -// Consider: Why does it give this error? Is this what I predicted? If not, what's different? -// Then try updating the expression last4Digits is assigned to, in order to get the correct value -/* we declare cardNumber as number . slice , This function for string */ -const cardNumber = 4533787178994213; -const last4Digits = String(cardNumber).slice(-4); // Convert to string first -console.log(last4Digits); diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js deleted file mode 100644 index 28829a05e..000000000 --- a/Sprint-1/2-mandatory-errors/4.js +++ /dev/null @@ -1,4 +0,0 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; -const twelveHourClockTime = "20:53"; -const twentyFourHourClockTime = "08:53"; \ 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 deleted file mode 100644 index 340610174..000000000 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ /dev/null @@ -1,45 +0,0 @@ -let carPrice = "10,000"; -let priceAfterOneYear = "8,543"; - -carPrice = Number(carPrice.replaceAll(",", "")); -priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); - -const priceDifference = carPrice - priceAfterOneYear; -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 - -// 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? - -// c) Identify all the lines that are variable reassignment statements - -// d) Identify all the lines that are variable declarations - -// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? -a) carPrice.replaceAll(",", "") -priceAfterOneYear.replaceAll(",", "") -Number() -console.log() -b) - There's a missing comma after the first argument in replaceAll. It should be: - priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); - c) - carPrice = Number(carPrice.replaceAll(",", "")); -priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); -d) -let carPrice = "10,000"; -let priceAfterOneYear = "8,543"; -const priceDifference = carPrice - priceAfterOneYear; -const percentageChange = (priceDifference / carPrice) * 100; -e) -carPrice.replaceAll(",", ""): This part uses the replaceAll method to -replace all occurrences of the comma (,) within the carPrice string with - an empty string (""). This removes the comma from the - string "10,000", -resulting in the string "10000". - -Number(): The Number() function convert the string as Number \ 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 deleted file mode 100644 index 1151db6e5..000000000 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ /dev/null @@ -1,51 +0,0 @@ -const movieLength = 8784; // length of movie in seconds - -const remainingSeconds = movieLength % 60; -const totalMinutes = (movieLength - remainingSeconds) / 60; - -const remainingMinutes = totalMinutes % 60; -const totalHours = (totalMinutes - remainingMinutes) / 60; - -const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`; -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? - -// b) How many function calls are there? - -// c) Using documentation, explain what the expression movieLength % 60 represents -// 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? - -// e) What do you think the variable result represents? Can you think of a better name for this variable? - -// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer -a) -result is also a variable declaration, there are six. -b) -There is one function call: console.log(result) - -c) -The % symbol is the modulo operator. - the modulo operator returns the remainder of a division. - So, movieLength % 60 calculates the remainder when movieLength is divided - by 60. -d) -movieLength - remainingSeconds: This subtracts the remaining seconds - from the total seconds. -/ 60: this division gives you the total number of whole minutes in the movie. - -e) -1)The variable result represents the formatted movie length in hours, minutes, and seconds (HH:MM:SS format). - - 2)formattedTime or formattedMovieLength. - f) - -1)The modulo operator and integer division will handle positive integer values correctly. -2) If movieLength is 0, the code will correctly produce "0:0:0". -3)If movieLength is negative, the modulo operator will return a negative -remainder. While the code might technically run, -the output will not be a correct \ 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 deleted file mode 100644 index 5fc971dd0..000000000 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ /dev/null @@ -1,57 +0,0 @@ -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}`); - -// This program takes a string representing a price in pence -// The program then builds up a string representing the price in pounds - -// You need to do a step-by-step breakdown of each line in this program -// Try and describe the purpose / rationale behind each step - -// To begin, we can start with -/* 1. const penceString = "399p": initialises a string variable with - the value "399p" - 2. - const penceString = "399p";: - This line initializes a constant variable named penceString and assigns it the string value "399p". This string represents a price in pence. The const keyword means the variable's value cannot be reassigned later in the program. - -const penceStringWithoutTrailingP = penceString.substring(0, penceString.length - 1);: - This line creates a new constant variable called penceStringWithoutTrailingP. It uses the substring() method to extract a portion of the penceString. penceString.length gets the total length of the string (5 in this case). Subtracting 1 gives us 4. substring(0, 4) extracts the characters from index 0 up to (but not including) index 4, effectively removing the last character "p". The result, "399", is stored in penceStringWithoutTrailingP. The rationale is to isolate the numerical part of the pence value. - -const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");: - This line creates another constant, paddedPenceNumberString. It uses the padStart() method to - pad the penceStringWithoutTrailingP with leading zeros until it reaches a length of 3. If the - string is already 3 or more characters long, no padding is added. In our example, "399" is - already 3 digits, so no padding occurs. The result, "399", is stored in paddedPenceNumberString. - The rationale for padding is to ensure that even single-digit or double-digit pence values are - formatted correctly when converted to pounds and pence (e.g., "9p" becomes "009"). - -const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2);: - This line extracts the pounds portion of the price. paddedPenceNumberString.length - 2 calculates the index - two characters from the end. substring(0, paddedPenceNumberString.length - 2) extracts the - characters from the beginning up to that index. - In our example, paddedPenceNumberString.length is 3, - so paddedPenceNumberString.length - 2 is 1. substring(0, 1) extracts the first character, "3". - The result, "3", is assigned to the pounds constant. The rationale is to separate the pounds from - the pence. - -const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2).padEnd(2, "0");: - This line extracts the pence portion. paddedPenceNumberString.substring(paddedPenceNumberString.length - 2) extracts the last two characters of the padded number string ("99" in our example). The padEnd(2, "0") method ensures that the pence value has at least two digits, adding trailing zeros if necessary. In our case, "99" already has two digits, so no padding is added. The result, "99", is assigned to the pence constant. The rationale is to isolate the pence value. - -console.log(£pounds.{pence});: This line uses a template literal (backticks) to create a string that combines the pounds and pence values with a pound symbol and a decimal point. It then uses console.log() to print this formatted string to the console. In our example, it will print "£3.99". This is the final formatted price in pounds and pence. - */ diff --git a/Sprint-1/4-stretch-explore/chrome.md b/Sprint-1/4-stretch-explore/chrome.md deleted file mode 100644 index e7dd5feaf..000000000 --- a/Sprint-1/4-stretch-explore/chrome.md +++ /dev/null @@ -1,18 +0,0 @@ -Open a new window in Chrome, - -then locate the **Console** tab. - -Voila! You now have access to the [Chrome V8 Engine](https://www.cloudflare.com/en-gb/learning/serverless/glossary/what-is-chrome-v8/). -Just like the Node REPL, you can input JavaScript code into the Console tab and the V8 engine will execute it. - -Let's try an example. - -In the Chrome console, -invoke the function `alert` with an input string of `"Hello world!"`; - -What effect does calling the `alert` function have? - -Now try invoking the function `prompt` with a string input of `"What is your name?"` - store the return value of your call to `prompt` in an variable called `myName`. - -What effect does calling the `prompt` function have? -What is the return value of `prompt`? diff --git a/Sprint-1/4-stretch-explore/objects.md b/Sprint-1/4-stretch-explore/objects.md deleted file mode 100644 index 0216dee56..000000000 --- a/Sprint-1/4-stretch-explore/objects.md +++ /dev/null @@ -1,16 +0,0 @@ -## Objects - -In this activity, we'll explore some additional concepts that you'll encounter in more depth later on in the course. - -Open the Chrome devtools Console, type in `console.log` and then hit enter - -What output do you get? - -Now enter just `console` in the Console, what output do you get back? - -Try also entering `typeof console` - -Answer the following questions: - -What does `console` store? -What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? diff --git a/Sprint-1/readme.md b/Sprint-1/readme.md deleted file mode 100644 index 62d24c958..000000000 --- a/Sprint-1/readme.md +++ /dev/null @@ -1,35 +0,0 @@ -# 🧭 Guide to Week 1 exercises - -> https://programming.codeyourfuture.io/structuring-data/sprints/1/prep/ - -> [!TIP] -> You should always do the prep work _before_ attempting the coursework. -> The prep shows you _how_ to do the coursework. -> There is often a step by step video you can code along with too. -> Do the prep. - -This README will guide you through the different sections for this week. - -## 1 Exercises - -In this section, you'll have a short program and task. Some of the syntax may be unfamiliar - in this case, you'll need to look things up in documentation. - -https://developer.mozilla.org/en-US/docs/Web/JavaScript - -## 2 Errors - -In this section, you'll need to go to each file in `errors` directory and run the file with node to check what the error is. Your task is to interpret the error message and explain why it occurs. The [errors documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors) will help you figure out the solution. - -## 3 Interpret - -In these tasks, you have to interpret a slightly larger program with some syntax / operators / functions that may be unfamiliar. - -You must use documentation to make sense of anything unfamiliar - learning how to look things up this way is a fundamental part of being a developer! - -You can also use `console.log` to check the value of different variables in the code. - -https://developer.mozilla.org/en-US/docs/Web/JavaScript - -## 4 Explore - Stretch 💪 - -This stretch activity will get you to start exploring new concepts and environments by yourself. It will do so by prompting you to reflect on some questions. From 7c0dba4bd21d0465962b83e39d4a94910c564b22 Mon Sep 17 00:00:00 2001 From: Sripathmanathan <111650472+sripathman@users.noreply.github.com> Date: Sat, 12 Apr 2025 12:50:03 +0100 Subject: [PATCH 4/5] Delete Sprint-2 directory --- Sprint-2/1-key-errors/0.js | 13 ------ Sprint-2/1-key-errors/1.js | 20 --------- Sprint-2/1-key-errors/2.js | 20 --------- Sprint-2/2-mandatory-debug/0.js | 14 ------- Sprint-2/2-mandatory-debug/1.js | 13 ------ Sprint-2/2-mandatory-debug/2.js | 24 ----------- Sprint-2/3-mandatory-implement/1-bmi.js | 19 --------- Sprint-2/3-mandatory-implement/2-cases.js | 16 -------- Sprint-2/3-mandatory-implement/3-to-pounds.js | 6 --- Sprint-2/4-mandatory-interpret/time-format.js | 34 --------------- Sprint-2/5-stretch-extend/format-time.js | 25 ----------- Sprint-2/readme.md | 41 ------------------- 12 files changed, 245 deletions(-) delete mode 100644 Sprint-2/1-key-errors/0.js delete mode 100644 Sprint-2/1-key-errors/1.js delete mode 100644 Sprint-2/1-key-errors/2.js delete mode 100644 Sprint-2/2-mandatory-debug/0.js delete mode 100644 Sprint-2/2-mandatory-debug/1.js delete mode 100644 Sprint-2/2-mandatory-debug/2.js delete mode 100644 Sprint-2/3-mandatory-implement/1-bmi.js delete mode 100644 Sprint-2/3-mandatory-implement/2-cases.js delete mode 100644 Sprint-2/3-mandatory-implement/3-to-pounds.js delete mode 100644 Sprint-2/4-mandatory-interpret/time-format.js delete mode 100644 Sprint-2/5-stretch-extend/format-time.js delete mode 100644 Sprint-2/readme.md diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js deleted file mode 100644 index 653d6f5a0..000000000 --- a/Sprint-2/1-key-errors/0.js +++ /dev/null @@ -1,13 +0,0 @@ -// Predict and explain first... -// =============> write your prediction here - -// 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; -} - -// =============> write your explanation here -// =============> write your new code here diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js deleted file mode 100644 index f2d56151f..000000000 --- a/Sprint-2/1-key-errors/1.js +++ /dev/null @@ -1,20 +0,0 @@ -// Predict and explain first... - -// Why will an error occur when this program runs? -// =============> write your prediction here - -// 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 - -// Finally, correct the code to fix the problem -// =============> write your new code here diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js deleted file mode 100644 index aad57f7cf..000000000 --- a/Sprint-2/1-key-errors/2.js +++ /dev/null @@ -1,20 +0,0 @@ - -// Predict and explain first BEFORE you run any code... - -// this function should square any number but instead we're going to get an error - -// =============> write your prediction of the error here - -function square(3) { - return num * num; -} - -// =============> write the error message here - -// =============> explain this error message here - -// Finally, correct the code to fix the problem - -// =============> write your new code here - - diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js deleted file mode 100644 index b27511b41..000000000 --- a/Sprint-2/2-mandatory-debug/0.js +++ /dev/null @@ -1,14 +0,0 @@ -// Predict and explain first... - -// =============> write your prediction here - -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 - -// Finally, correct the code to fix the problem -// =============> write your new code here diff --git a/Sprint-2/2-mandatory-debug/1.js b/Sprint-2/2-mandatory-debug/1.js deleted file mode 100644 index 37cedfbcf..000000000 --- a/Sprint-2/2-mandatory-debug/1.js +++ /dev/null @@ -1,13 +0,0 @@ -// Predict and explain first... -// =============> write your prediction here - -function sum(a, b) { - return; - a + b; -} - -console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); - -// =============> write your explanation here -// Finally, correct the code to fix the problem -// =============> write your new code here diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js deleted file mode 100644 index 57d3f5dc3..000000000 --- a/Sprint-2/2-mandatory-debug/2.js +++ /dev/null @@ -1,24 +0,0 @@ -// Predict and explain first... - -// Predict the output of the following code: -// =============> Write your prediction here - -const num = 103; - -function getLastDigit() { - return num.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 deleted file mode 100644 index 17b1cbde1..000000000 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ /dev/null @@ -1,19 +0,0 @@ -// Below are the steps for how BMI is calculated - -// The BMI calculation divides an adult's weight in kilograms (kg) by their height in metres (m) squared. - -// For example, if you weigh 70kg (around 11 stone) and are 1.73m (around 5 feet 8 inches) tall, you work out your BMI by: - -// squaring your height: 1.73 x 1.73 = 2.99 -// dividing 70 by 2.99 = 23.41 -// Your result will be displayed to 1 decimal place, for example 23.4. - -// You will need to implement a function that calculates the BMI of someone based off their weight and height - -// 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 - -function calculateBMI(weight, height) { - // return the BMI of someone based off their weight and height -} \ No newline at end of file diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js deleted file mode 100644 index 5b0ef77ad..000000000 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ /dev/null @@ -1,16 +0,0 @@ -// A set of words can be grouped together in different cases. - -// For example, "hello there" in snake case would be written "hello_there" -// UPPER_SNAKE_CASE means taking a string and writing it in all caps with underscores instead of spaces. - -// Implement a function that: - -// Given a string input like "hello there" -// When we call this function with the input string -// it returns the string in UPPER_SNAKE_CASE, so "HELLO_THERE" - -// Another example: "lord of the rings" should be "LORD_OF_THE_RINGS" - -// 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 diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js deleted file mode 100644 index 6265a1a70..000000000 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ /dev/null @@ -1,6 +0,0 @@ -// In Sprint-1, there is a program written in interpret/to-pounds.js - -// You will need to take this code and turn it into a reusable block of code. -// 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 diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js deleted file mode 100644 index 7c98eb0e8..000000000 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ /dev/null @@ -1,34 +0,0 @@ -function pad(num) { - return num.toString().padStart(2, "0"); -} - -function formatTimeDisplay(seconds) { - const remainingSeconds = seconds % 60; - const totalMinutes = (seconds - remainingSeconds) / 60; - const remainingMinutes = totalMinutes % 60; - const totalHours = (totalMinutes - remainingMinutes) / 60; - - 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 - -// Questions - -// a) When formatTimeDisplay is called how many times will pad be called? -// =============> write your answer here - -// 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 - -// c) What is the return value of pad is called for the first time? -// =============> write your answer here - -// 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 - -// 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 diff --git a/Sprint-2/5-stretch-extend/format-time.js b/Sprint-2/5-stretch-extend/format-time.js deleted file mode 100644 index 32a32e66b..000000000 --- a/Sprint-2/5-stretch-extend/format-time.js +++ /dev/null @@ -1,25 +0,0 @@ -// This is the latest solution to the problem from the prep. -// Make sure to do the prep before you do the coursework -// 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)); - if (hours > 12) { - return `${hours - 12}:00 pm`; - } - return `${time} am`; -} - -const currentOutput = formatAs12HourClock("08:00"); -const targetOutput = "08:00 am"; -console.assert( - currentOutput === targetOutput, - `current output: ${currentOutput}, target output: ${targetOutput}` -); - -const currentOutput2 = formatAs12HourClock("23:00"); -const targetOutput2 = "11:00 pm"; -console.assert( - currentOutput2 === targetOutput2, - `current output: ${currentOutput2}, target output: ${targetOutput2}` -); diff --git a/Sprint-2/readme.md b/Sprint-2/readme.md deleted file mode 100644 index 44c118e33..000000000 --- a/Sprint-2/readme.md +++ /dev/null @@ -1,41 +0,0 @@ -# 🧭 Guide to week 2 exercises - -> https://programming.codeyourfuture.io/structuring-data/sprints/2/prep/ - -> [!TIP] -> You should always do the prep work _before_ attempting the coursework. -> The prep shows you how to do the coursework. -> There is often a step by step video you can code along with too. -> Do the prep. - -## 1 Errors - -In this section, you need to go to each file in `errors` directory. Read the file and predict what error will happen. Then run the file with node to check what the error is. Your task is to interpret the error message and explain why it occurs. The [errors documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors) will help you figure out the solution. - -## 2 Debug - -In this section, you need to go to each file in `debug` to **explain and predict** why the program isn't behaving as intended. Then you'll need to run the program with node to check your prediction. You will also need to correct the code too. - -## 3 Implement - -In this section, you will have a short set of requirements about a function. You will need to implement a function based off this set of requirements. Make sure you check your function works for a number of different inputs. - -Here is a recommended order: - -1. `1-bmi.js` -1. `2-cases.js` -1. `3-to-pounds.js` - -## 4 Interpret - -In these tasks, you have to interpret a slightly larger program with some syntax / operators / functions that may be unfamiliar. - -You must use documentation to make sense of anything unfamiliar. Learning how to look things up this way is a fundamental part of being a developer! - -You can also use `console.log` to check the value of different variables in the code. - -## 5 Extend - -In the prep for this sprint, we developed a function to convert 24 hour clock times to 12 hour clock times. - -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 section is not mandatory, but it will also help you solve some similar kata in Codewars. From bd359b34fd97d5d74a4262660d29035e74085678 Mon Sep 17 00:00:00 2001 From: sripathman Date: Sun, 20 Apr 2025 16:03:57 +0100 Subject: [PATCH 5/5] fix folder --- Sprint-1/1-key-exercises/1-count.js | 6 +++ Sprint-1/1-key-exercises/2-initials.js | 11 +++++ Sprint-1/1-key-exercises/3-paths.js | 23 +++++++++++ Sprint-1/1-key-exercises/4-random.js | 9 ++++ Sprint-1/2-mandatory-errors/0.js | 2 + Sprint-1/2-mandatory-errors/1.js | 4 ++ Sprint-1/2-mandatory-errors/2.js | 5 +++ Sprint-1/2-mandatory-errors/3.js | 9 ++++ Sprint-1/2-mandatory-errors/4.js | 2 + .../1-percentage-change.js | 22 ++++++++++ .../3-mandatory-interpret/2-time-format.js | 25 +++++++++++ Sprint-1/3-mandatory-interpret/3-to-pounds.js | 27 ++++++++++++ Sprint-1/4-stretch-explore/chrome.md | 18 ++++++++ Sprint-1/4-stretch-explore/objects.md | 16 ++++++++ Sprint-1/readme.md | 35 ++++++++++++++++ Sprint-2/1-key-errors/0.js | 13 ++++++ Sprint-2/1-key-errors/1.js | 20 +++++++++ Sprint-2/1-key-errors/2.js | 20 +++++++++ Sprint-2/2-mandatory-debug/0.js | 14 +++++++ Sprint-2/2-mandatory-debug/1.js | 13 ++++++ Sprint-2/2-mandatory-debug/2.js | 24 +++++++++++ Sprint-2/3-mandatory-implement/1-bmi.js | 19 +++++++++ Sprint-2/3-mandatory-implement/2-cases.js | 16 ++++++++ Sprint-2/3-mandatory-implement/3-to-pounds.js | 6 +++ Sprint-2/4-mandatory-interpret/time-format.js | 34 +++++++++++++++ Sprint-2/5-stretch-extend/format-time.js | 25 +++++++++++ Sprint-2/readme.md | 41 +++++++++++++++++++ 27 files changed, 459 insertions(+) create mode 100644 Sprint-1/1-key-exercises/1-count.js create mode 100644 Sprint-1/1-key-exercises/2-initials.js create mode 100644 Sprint-1/1-key-exercises/3-paths.js create mode 100644 Sprint-1/1-key-exercises/4-random.js create mode 100644 Sprint-1/2-mandatory-errors/0.js create mode 100644 Sprint-1/2-mandatory-errors/1.js create mode 100644 Sprint-1/2-mandatory-errors/2.js create mode 100644 Sprint-1/2-mandatory-errors/3.js create mode 100644 Sprint-1/2-mandatory-errors/4.js create mode 100644 Sprint-1/3-mandatory-interpret/1-percentage-change.js create mode 100644 Sprint-1/3-mandatory-interpret/2-time-format.js create mode 100644 Sprint-1/3-mandatory-interpret/3-to-pounds.js create mode 100644 Sprint-1/4-stretch-explore/chrome.md create mode 100644 Sprint-1/4-stretch-explore/objects.md create mode 100644 Sprint-1/readme.md create mode 100644 Sprint-2/1-key-errors/0.js create mode 100644 Sprint-2/1-key-errors/1.js create mode 100644 Sprint-2/1-key-errors/2.js create mode 100644 Sprint-2/2-mandatory-debug/0.js create mode 100644 Sprint-2/2-mandatory-debug/1.js create mode 100644 Sprint-2/2-mandatory-debug/2.js create mode 100644 Sprint-2/3-mandatory-implement/1-bmi.js create mode 100644 Sprint-2/3-mandatory-implement/2-cases.js create mode 100644 Sprint-2/3-mandatory-implement/3-to-pounds.js create mode 100644 Sprint-2/4-mandatory-interpret/time-format.js create mode 100644 Sprint-2/5-stretch-extend/format-time.js create mode 100644 Sprint-2/readme.md diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js new file mode 100644 index 000000000..117bcb2b6 --- /dev/null +++ b/Sprint-1/1-key-exercises/1-count.js @@ -0,0 +1,6 @@ +let count = 0; + +count = count + 1; + +// Line 1 is a variable declaration, creating the count variable with an initial value of 0 +// Describe what line 3 is doing, in particular focus on what = is doing diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js new file mode 100644 index 000000000..47561f617 --- /dev/null +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -0,0 +1,11 @@ +let firstName = "Creola"; +let middleName = "Katherine"; +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 = ``; + +// 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 new file mode 100644 index 000000000..ab90ebb28 --- /dev/null +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -0,0 +1,23 @@ +// The diagram below shows the different names for parts of a file path on a Unix operating system + +// ┌─────────────────────┬────────────┐ +// │ dir │ base │ +// ├──────┬ ├──────┬─────┤ +// │ root │ │ name │ ext │ +// " / home/user/dir / file .txt " +// └──────┴──────────────┴──────┴─────┘ + +// (All spaces in the "" line should be ignored. They are purely for formatting.) + +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 = ; + +// 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 new file mode 100644 index 000000000..292f83aab --- /dev/null +++ b/Sprint-1/1-key-exercises/4-random.js @@ -0,0 +1,9 @@ +const minimum = 1; +const maximum = 100; + +const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; + +// In this exercise, you will need to work out what num represents? +// 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 diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js new file mode 100644 index 000000000..cf6c5039f --- /dev/null +++ b/Sprint-1/2-mandatory-errors/0.js @@ -0,0 +1,2 @@ +This is just an instruction for the first activity - but it is just for human consumption +We don't want the computer to run these 2 lines - how can we solve this problem? \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/1.js b/Sprint-1/2-mandatory-errors/1.js new file mode 100644 index 000000000..7a43cbea7 --- /dev/null +++ b/Sprint-1/2-mandatory-errors/1.js @@ -0,0 +1,4 @@ +// trying to create an age variable and then reassign the value by 1 + +const age = 33; +age = age + 1; diff --git a/Sprint-1/2-mandatory-errors/2.js b/Sprint-1/2-mandatory-errors/2.js new file mode 100644 index 000000000..e09b89831 --- /dev/null +++ b/Sprint-1/2-mandatory-errors/2.js @@ -0,0 +1,5 @@ +// 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"; diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js new file mode 100644 index 000000000..ec101884d --- /dev/null +++ b/Sprint-1/2-mandatory-errors/3.js @@ -0,0 +1,9 @@ +const cardNumber = 4533787178994213; +const last4Digits = cardNumber.slice(-4); + +// The last4Digits variable should store the last 4 digits of cardNumber +// However, the code isn't working +// Before running the code, make and explain a prediction about why the code won't work +// Then run the code and see what error it gives. +// Consider: Why does it give this error? Is this what I predicted? If not, what's different? +// Then try updating the expression last4Digits is assigned to, in order to get the correct value diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js new file mode 100644 index 000000000..21dad8c5d --- /dev/null +++ b/Sprint-1/2-mandatory-errors/4.js @@ -0,0 +1,2 @@ +const 12HourClockTime = "20:53"; +const 24hourClockTime = "08:53"; \ 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 new file mode 100644 index 000000000..e24ecb8e1 --- /dev/null +++ b/Sprint-1/3-mandatory-interpret/1-percentage-change.js @@ -0,0 +1,22 @@ +let carPrice = "10,000"; +let priceAfterOneYear = "8,543"; + +carPrice = Number(carPrice.replaceAll(",", "")); +priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); + +const priceDifference = carPrice - priceAfterOneYear; +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 + +// 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? + +// c) Identify all the lines that are variable reassignment statements + +// d) Identify all the lines that are variable declarations + +// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? diff --git a/Sprint-1/3-mandatory-interpret/2-time-format.js b/Sprint-1/3-mandatory-interpret/2-time-format.js new file mode 100644 index 000000000..47d239558 --- /dev/null +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -0,0 +1,25 @@ +const movieLength = 8784; // length of movie in seconds + +const remainingSeconds = movieLength % 60; +const totalMinutes = (movieLength - remainingSeconds) / 60; + +const remainingMinutes = totalMinutes % 60; +const totalHours = (totalMinutes - remainingMinutes) / 60; + +const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`; +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? + +// b) How many function calls are there? + +// c) Using documentation, explain what the expression movieLength % 60 represents +// 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? + +// e) What do you think the variable result represents? Can you think of a better name for this variable? + +// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js new file mode 100644 index 000000000..60c9ace69 --- /dev/null +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -0,0 +1,27 @@ +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}`); + +// This program takes a string representing a price in pence +// The program then builds up a string representing the price in pounds + +// You need to do a step-by-step breakdown of each line in this program +// Try and describe the purpose / rationale behind each step + +// To begin, we can start with +// 1. const penceString = "399p": initialises a string variable with the value "399p" diff --git a/Sprint-1/4-stretch-explore/chrome.md b/Sprint-1/4-stretch-explore/chrome.md new file mode 100644 index 000000000..e7dd5feaf --- /dev/null +++ b/Sprint-1/4-stretch-explore/chrome.md @@ -0,0 +1,18 @@ +Open a new window in Chrome, + +then locate the **Console** tab. + +Voila! You now have access to the [Chrome V8 Engine](https://www.cloudflare.com/en-gb/learning/serverless/glossary/what-is-chrome-v8/). +Just like the Node REPL, you can input JavaScript code into the Console tab and the V8 engine will execute it. + +Let's try an example. + +In the Chrome console, +invoke the function `alert` with an input string of `"Hello world!"`; + +What effect does calling the `alert` function have? + +Now try invoking the function `prompt` with a string input of `"What is your name?"` - store the return value of your call to `prompt` in an variable called `myName`. + +What effect does calling the `prompt` function have? +What is the return value of `prompt`? diff --git a/Sprint-1/4-stretch-explore/objects.md b/Sprint-1/4-stretch-explore/objects.md new file mode 100644 index 000000000..0216dee56 --- /dev/null +++ b/Sprint-1/4-stretch-explore/objects.md @@ -0,0 +1,16 @@ +## Objects + +In this activity, we'll explore some additional concepts that you'll encounter in more depth later on in the course. + +Open the Chrome devtools Console, type in `console.log` and then hit enter + +What output do you get? + +Now enter just `console` in the Console, what output do you get back? + +Try also entering `typeof console` + +Answer the following questions: + +What does `console` store? +What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? diff --git a/Sprint-1/readme.md b/Sprint-1/readme.md new file mode 100644 index 000000000..62d24c958 --- /dev/null +++ b/Sprint-1/readme.md @@ -0,0 +1,35 @@ +# 🧭 Guide to Week 1 exercises + +> https://programming.codeyourfuture.io/structuring-data/sprints/1/prep/ + +> [!TIP] +> You should always do the prep work _before_ attempting the coursework. +> The prep shows you _how_ to do the coursework. +> There is often a step by step video you can code along with too. +> Do the prep. + +This README will guide you through the different sections for this week. + +## 1 Exercises + +In this section, you'll have a short program and task. Some of the syntax may be unfamiliar - in this case, you'll need to look things up in documentation. + +https://developer.mozilla.org/en-US/docs/Web/JavaScript + +## 2 Errors + +In this section, you'll need to go to each file in `errors` directory and run the file with node to check what the error is. Your task is to interpret the error message and explain why it occurs. The [errors documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors) will help you figure out the solution. + +## 3 Interpret + +In these tasks, you have to interpret a slightly larger program with some syntax / operators / functions that may be unfamiliar. + +You must use documentation to make sense of anything unfamiliar - learning how to look things up this way is a fundamental part of being a developer! + +You can also use `console.log` to check the value of different variables in the code. + +https://developer.mozilla.org/en-US/docs/Web/JavaScript + +## 4 Explore - Stretch 💪 + +This stretch activity will get you to start exploring new concepts and environments by yourself. It will do so by prompting you to reflect on some questions. diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js new file mode 100644 index 000000000..653d6f5a0 --- /dev/null +++ b/Sprint-2/1-key-errors/0.js @@ -0,0 +1,13 @@ +// Predict and explain first... +// =============> write your prediction here + +// 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; +} + +// =============> write your explanation here +// =============> write your new code here diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js new file mode 100644 index 000000000..f2d56151f --- /dev/null +++ b/Sprint-2/1-key-errors/1.js @@ -0,0 +1,20 @@ +// Predict and explain first... + +// Why will an error occur when this program runs? +// =============> write your prediction here + +// 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 + +// Finally, correct the code to fix the problem +// =============> write your new code here diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js new file mode 100644 index 000000000..aad57f7cf --- /dev/null +++ b/Sprint-2/1-key-errors/2.js @@ -0,0 +1,20 @@ + +// Predict and explain first BEFORE you run any code... + +// this function should square any number but instead we're going to get an error + +// =============> write your prediction of the error here + +function square(3) { + return num * num; +} + +// =============> write the error message here + +// =============> explain this error message here + +// Finally, correct the code to fix the problem + +// =============> write your new code here + + diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js new file mode 100644 index 000000000..b27511b41 --- /dev/null +++ b/Sprint-2/2-mandatory-debug/0.js @@ -0,0 +1,14 @@ +// Predict and explain first... + +// =============> write your prediction here + +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 + +// Finally, correct the code to fix the problem +// =============> write your new code here diff --git a/Sprint-2/2-mandatory-debug/1.js b/Sprint-2/2-mandatory-debug/1.js new file mode 100644 index 000000000..37cedfbcf --- /dev/null +++ b/Sprint-2/2-mandatory-debug/1.js @@ -0,0 +1,13 @@ +// Predict and explain first... +// =============> write your prediction here + +function sum(a, b) { + return; + a + b; +} + +console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); + +// =============> write your explanation here +// Finally, correct the code to fix the problem +// =============> write your new code here diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js new file mode 100644 index 000000000..57d3f5dc3 --- /dev/null +++ b/Sprint-2/2-mandatory-debug/2.js @@ -0,0 +1,24 @@ +// Predict and explain first... + +// Predict the output of the following code: +// =============> Write your prediction here + +const num = 103; + +function getLastDigit() { + return num.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 new file mode 100644 index 000000000..17b1cbde1 --- /dev/null +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -0,0 +1,19 @@ +// Below are the steps for how BMI is calculated + +// The BMI calculation divides an adult's weight in kilograms (kg) by their height in metres (m) squared. + +// For example, if you weigh 70kg (around 11 stone) and are 1.73m (around 5 feet 8 inches) tall, you work out your BMI by: + +// squaring your height: 1.73 x 1.73 = 2.99 +// dividing 70 by 2.99 = 23.41 +// Your result will be displayed to 1 decimal place, for example 23.4. + +// You will need to implement a function that calculates the BMI of someone based off their weight and height + +// 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 + +function calculateBMI(weight, height) { + // return the BMI of someone based off their weight and height +} \ No newline at end of file diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js new file mode 100644 index 000000000..5b0ef77ad --- /dev/null +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -0,0 +1,16 @@ +// A set of words can be grouped together in different cases. + +// For example, "hello there" in snake case would be written "hello_there" +// UPPER_SNAKE_CASE means taking a string and writing it in all caps with underscores instead of spaces. + +// Implement a function that: + +// Given a string input like "hello there" +// When we call this function with the input string +// it returns the string in UPPER_SNAKE_CASE, so "HELLO_THERE" + +// Another example: "lord of the rings" should be "LORD_OF_THE_RINGS" + +// 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 diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js new file mode 100644 index 000000000..6265a1a70 --- /dev/null +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -0,0 +1,6 @@ +// In Sprint-1, there is a program written in interpret/to-pounds.js + +// You will need to take this code and turn it into a reusable block of code. +// 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 diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js new file mode 100644 index 000000000..7c98eb0e8 --- /dev/null +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -0,0 +1,34 @@ +function pad(num) { + return num.toString().padStart(2, "0"); +} + +function formatTimeDisplay(seconds) { + const remainingSeconds = seconds % 60; + const totalMinutes = (seconds - remainingSeconds) / 60; + const remainingMinutes = totalMinutes % 60; + const totalHours = (totalMinutes - remainingMinutes) / 60; + + 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 + +// Questions + +// a) When formatTimeDisplay is called how many times will pad be called? +// =============> write your answer here + +// 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 + +// c) What is the return value of pad is called for the first time? +// =============> write your answer here + +// 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 + +// 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 diff --git a/Sprint-2/5-stretch-extend/format-time.js b/Sprint-2/5-stretch-extend/format-time.js new file mode 100644 index 000000000..32a32e66b --- /dev/null +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -0,0 +1,25 @@ +// This is the latest solution to the problem from the prep. +// Make sure to do the prep before you do the coursework +// 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)); + if (hours > 12) { + return `${hours - 12}:00 pm`; + } + return `${time} am`; +} + +const currentOutput = formatAs12HourClock("08:00"); +const targetOutput = "08:00 am"; +console.assert( + currentOutput === targetOutput, + `current output: ${currentOutput}, target output: ${targetOutput}` +); + +const currentOutput2 = formatAs12HourClock("23:00"); +const targetOutput2 = "11:00 pm"; +console.assert( + currentOutput2 === targetOutput2, + `current output: ${currentOutput2}, target output: ${targetOutput2}` +); diff --git a/Sprint-2/readme.md b/Sprint-2/readme.md new file mode 100644 index 000000000..44c118e33 --- /dev/null +++ b/Sprint-2/readme.md @@ -0,0 +1,41 @@ +# 🧭 Guide to week 2 exercises + +> https://programming.codeyourfuture.io/structuring-data/sprints/2/prep/ + +> [!TIP] +> You should always do the prep work _before_ attempting the coursework. +> The prep shows you how to do the coursework. +> There is often a step by step video you can code along with too. +> Do the prep. + +## 1 Errors + +In this section, you need to go to each file in `errors` directory. Read the file and predict what error will happen. Then run the file with node to check what the error is. Your task is to interpret the error message and explain why it occurs. The [errors documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors) will help you figure out the solution. + +## 2 Debug + +In this section, you need to go to each file in `debug` to **explain and predict** why the program isn't behaving as intended. Then you'll need to run the program with node to check your prediction. You will also need to correct the code too. + +## 3 Implement + +In this section, you will have a short set of requirements about a function. You will need to implement a function based off this set of requirements. Make sure you check your function works for a number of different inputs. + +Here is a recommended order: + +1. `1-bmi.js` +1. `2-cases.js` +1. `3-to-pounds.js` + +## 4 Interpret + +In these tasks, you have to interpret a slightly larger program with some syntax / operators / functions that may be unfamiliar. + +You must use documentation to make sense of anything unfamiliar. Learning how to look things up this way is a fundamental part of being a developer! + +You can also use `console.log` to check the value of different variables in the code. + +## 5 Extend + +In the prep for this sprint, we developed a function to convert 24 hour clock times to 12 hour clock times. + +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 section is not mandatory, but it will also help you solve some similar kata in Codewars.