Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Sprint-2/1-key-exercises/1-count.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ 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
// Line 3 is evaluated from the right side. It adds 1 to the current value of count,
// then assigns the new value back to the count variable.
4 changes: 2 additions & 2 deletions Sprint-2/1-key-exercises/2-initials.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ const 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.

const initials = ``;
const initials = firstName[0] + middleName[0] + lastName[0];
console.log(initials);

// https://www.google.com/search?q=get+first+character+of+string+mdn
4 changes: 2 additions & 2 deletions Sprint-2/1-key-exercises/3-paths.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ 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);
const ext = filePath.slice(filePath.lastIndexOf("."));

// https://www.google.com/search?q=slice+mdn
8 changes: 7 additions & 1 deletion Sprint-2/1-key-exercises/4-random.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,14 @@ const minimum = 1;
const maximum = 100;

const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;

console.log(num);
// 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

// num represents a random whole number between 1 and 100, including both 1 and 100.
// Math.random() generates a random number from 0 up to, but not including, 1.
// Multiplying by (maximum - minimum + 1) creates the required range.
// Math.floor() rounds the result down to a whole number.
// Adding minimum makes the final range start at 1.
7 changes: 5 additions & 2 deletions Sprint-2/2-mandatory-errors/1.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// trying to create an age variable and then reassign the value by 1
// The error occurs because age is declared with const, so its value cannot be reassigned.
// The next line tries to assign a new value to age, which causes a TypeError.
// Using let fixes the error because let allows the variable to be reassigned.

const age = 33;
let age = 33;
age = age + 1;
console.log(age);
7 changes: 6 additions & 1 deletion Sprint-2/2-mandatory-errors/2.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
// Currently trying to print the string "I was born in Bolton" but it isn't working...
// what's the error ?

console.log(`I was born in ${cityOfBirth}`);
const cityOfBirth = "Bolton";
console.log(`I was born in ${cityOfBirth}`);

// The error occurs because cityOfBirth is accessed before it has been initialized.
// Variables declared with const cannot be accessed before their declaration is executed.
// This causes a ReferenceError because the variable is in the Temporal Dead Zone (TDZ).
// Moving the declaration before console.log fixes the error because cityOfBirth has a value before it is used.
20 changes: 12 additions & 8 deletions Sprint-2/2-mandatory-errors/3.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
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
const last4Digits = cardNumber.toString().slice(-4);

console.log(last4Digits);

// Prediction: the code will not work because cardNumber is a number,
// and the slice() method cannot be used directly on numbers.

// Running the original code gives a TypeError because cardNumber.slice is not a function.
// This happens because slice() is available for strings and arrays, but not for numbers.

// Converting cardNumber to a string first allows slice(-4) to return the last four characters.
// Therefore, last4Digits stores "4213".
9 changes: 7 additions & 2 deletions Sprint-2/2-mandatory-errors/4.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
const 12HourClockTime = "8:53pm";
const 24hourClockTime = "20:53";
const twelveHourClockTime = "8:53pm";
const twentyFourHourClockTime = "20:53";

// The error occurs because JavaScript variable names cannot start with a number.
// Both variable names begin with digits, so JavaScript cannot parse them as valid identifiers
// and throws a SyntaxError.
// Renaming the variables so they start with letters fixes the error.
22 changes: 21 additions & 1 deletion Sprint-2/3-mandatory-interpret/1-percentage-change.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ let carPrice = "10,000";
let priceAfterOneYear = "8,543";

carPrice = Number(carPrice.replaceAll(",", ""));
priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," ""));
priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", ""));

const priceDifference = carPrice - priceAfterOneYear;
const percentageChange = (priceDifference / carPrice) * 100;
Expand All @@ -12,11 +12,31 @@ console.log(`The percentage change is ${percentageChange}`);
// Read the code and then answer the questions below

// a) How many function calls are there in this file? Write down all the lines where a function call is made
// There are 5 function/method calls:
// Line 4: carPrice.replaceAll(",", "")
// Line 4: Number(...)
// Line 5: priceAfterOneYear.replaceAll(",", "")
// Line 5: Number(...)
// Line 10: console.log(...)

// 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?
// The error originally comes from line 5.
// priceAfterOneYear was declared with const, but line 5 tries to assign a new value to it.
// A variable declared with const cannot be reassigned, so JavaScript throws a TypeError.
// To fix the error, change const to let because priceAfterOneYear needs to be reassigned.

// c) Identify all the lines that are variable reassignment statements
// Line 4: carPrice = Number(carPrice.replaceAll(",", ""));
// Line 5: priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", ""));

// d) Identify all the lines that are variable declarations
// Line 1: let carPrice = "10,000";
// Line 2: let priceAfterOneYear = "8,543";
// Line 7: const priceDifference = carPrice - priceAfterOneYear;
// Line 8: const percentageChange = (priceDifference / carPrice) * 100;

// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression?
// carPrice.replaceAll(",", "") removes all commas from the string,
// changing "10,000" to "10000".
// Number(...) then converts the string "10000" into the number 10000.
// This allows carPrice to be used correctly in mathematical calculations.
50 changes: 48 additions & 2 deletions Sprint-2/3-mandatory-interpret/2-time-format.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,71 @@
const movieLength = 8784; // length of movie in seconds

// Test values tried:
// const movieLength = 9893;
// const movieLength = 223;
// const movieLength = 50;
// const movieLength = 345;
// const movieLength = 600;
// const movieLength = 400;
// const movieLength = 90;
// const movieLength = 189;

function movieFormatting(num) {
if (num < 10) {
return "0" + num.toString();
} else {
return num.toString();
}
}

const remainingSeconds = movieLength % 60;
const totalMinutes = (movieLength - remainingSeconds) / 60;

const remainingMinutes = totalMinutes % 60;
const totalHours = (totalMinutes - remainingMinutes) / 60;

const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`;
const result = `${movieFormatting(totalHours)}:${movieFormatting(remainingMinutes)}:${movieFormatting(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?
// There are 6 variable declarations in the original program:
// movieLength, remainingSeconds, totalMinutes, remainingMinutes, totalHours, and result.

// b) How many function calls are there?
// There is 1 function call in the original program:
// console.log(result).

// c) Using documentation, explain what the expression movieLength % 60 represents
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators
// The % operator is the remainder operator. It returns the remainder after division.
// Here, movieLength % 60 gives the number of seconds left over after dividing
// the total movie length in seconds by 60.
// For example, with movieLength = 8784, the remainder is 24,
// so remainingSeconds is 24.

// d) Interpret line 4, what does the expression assigned to totalMinutes mean?
// First, remainingSeconds is subtracted from movieLength.
// This removes the leftover seconds and leaves a value that can be divided
// evenly by 60. The result is then divided by 60 to convert the seconds
// into the total number of whole minutes.
// For movieLength = 8784, totalMinutes is 146.

// e) What do you think the variable result represents? Can you think of a better name for this variable?
// result represents the movie duration in hours, minutes and seconds.
// A more descriptive variable name could be movieDurationHHMMSS.
// For movieLength = 8784, the formatted result is "02:26:24".

// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer
// I tested the code with multiple values of movieLength, including:
// 9893, 223, 50, 345, 600, 400, 90 and 189.

// The original code works for the positive whole-number values I tested,
// but it does not always format the output in HH:MM:SS format.
// If the hours, minutes, or seconds are less than 10, for example 5 or 7,
// they are displayed as a single digit instead of two digits.

// I created the movieFormatting() function to add a leading 0 when a value
// is less than 10. Otherwise, the function returns the value as a string.
// I then tested the updated code with multiple movieLength values and
// the tested values produced the expected HH:MM:SS formatted output.
67 changes: 57 additions & 10 deletions Sprint-2/3-mandatory-interpret/3-to-pounds.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,74 @@
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.

// Step-by-step breakdown:

// 1. const penceString = "399p";
// Initialises the penceString variable with the string "399p".
// This represents a price of 399 pence.

// 2. penceString.length - 1
// penceString has a length of 4. Subtracting 1 gives 3.
// This is used to identify the position before the final "p".

// 3. penceString.substring(0, penceString.length - 1)
// substring() extracts the characters from index 0 up to, but not including,
// index 3. This removes the trailing "p" and produces the string "399".

// 4. const penceStringWithoutTrailingP = ...
// Stores the result "399", so the price now contains only the numeric characters.

// 5. penceStringWithoutTrailingP.padStart(3, "0")
// padStart() makes sure the string contains at least 3 characters.
// If it has fewer than 3 characters, "0" is added to the beginning.
// For "399", no padding is needed, so the value remains "399".
// This is useful for smaller values such as "99", which would become "099".

// 6. const paddedPenceNumberString = ...
// Stores the padded string. For the current input, its value is "399".

// 7. paddedPenceNumberString.length - 2
// This calculates the position that separates the pounds from the final
// two digits representing pence. For "399", the length is 3, so 3 - 2 = 1.

// 8. paddedPenceNumberString.substring(
// 0,
// paddedPenceNumberString.length - 2
// )
// Extracts the characters before the final two digits.
// For "399", this extracts "3", which represents the pounds.

// 9. const pounds = ...
// Stores the pounds part of the price. In this example, pounds is "3".

// 10. paddedPenceNumberString
// .substring(paddedPenceNumberString.length - 2)
// substring() starts two characters from the end of the string.
// For "399", it extracts "99", which represents the pence part.

// This program takes a string representing a price in pence
// The program then builds up a string representing the price in pounds
// 11. .padEnd(2, "0")
// Makes sure the pence part contains at least two characters.
// If necessary, "0" is added to the end until the string has a length of 2.
// In this example, "99" already has two characters, so it remains "99".

// You need to do a step-by-step breakdown of each line in this program
// Try and describe the purpose / rationale behind each step
// 12. const pence = ...
// Stores the final pence part. In this example, pence is "99".

// To begin, we can start with
// 1. const penceString = "399p": initialises a string variable with the value "399p"
// 13. console.log(`£${pounds}.${pence}`);
// Uses a template literal to combine the pound sign, pounds value,
// decimal point and pence value.
// With the input "399p", the final output is "£3.99".
Loading