Skip to content

London | May-2025 | Reza Jahanimir | Coursework/sprint 2 #524

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
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
3 changes: 3 additions & 0 deletions Sprint-1/1-key-exercises/1-count.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@ 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

// We are updating the previous value of count to a new value. The = operator assigns a new value
// to the variable, meaning the data stored in memory is being changed.
3 changes: 2 additions & 1 deletion Sprint-1/1-key-exercises/2-initials.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ let lastName = "Johnson";
// Declare a variable called initials that stores the first character of each string.
// This should produce the string "CKJ", but you must not write the characters C, K, or J in the code of your solution.

let initials = ``;
let initials = `${firstName[0]}${middleName[0]}${lastName[0]}`;

// https://www.google.com/search?q=get+first+character+of+string+mdn

console.log(initials);
13 changes: 10 additions & 3 deletions Sprint-1/1-key-exercises/3-paths.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,17 @@ 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
const dir = filePath.slice(0 ,lastSlashIndex + 1);
console.log(`The div part of ${filePath} is ${dir}`);


// Create a variable to store the ext part of the variable
const lastDoteIndex = filePath.lastIndexOf(".");
const ext = filePath.slice(lastDoteIndex);
console.log(`The ext part of ${filePath} is ${ext}`);

const dir = ;
const ext = ;
// https://www.google.com/search?q=slice+mdn

// https://www.google.com/search?q=slice+mdn
console.log(lastSlashIndex);
15 changes: 15 additions & 0 deletions Sprint-1/1-key-exercises/4-random.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,22 @@ 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


// order of math calculation - () > ** > * / % > + - (Parentheses first, then Exponentiation
// (right to left), then Multiplication/Division/Modulo (left to right), then Addition/Subtraction
// (left to right)).

//Math.floor - returns the value of x rounded down to its nearest integer
//Math.random - returns a random number

// First, the innermost parentheses are evaluated: (maximum - minimum + 1).
// Then, the result is multiplied by the random number generated by the Math object.
// Math.floor rounds the result down to the nearest integer.
// Finally, the value is added to the minimum.
17 changes: 14 additions & 3 deletions Sprint-2/1-key-errors/0.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
// Predict and explain first...
// =============> write your prediction here
// =============> this function takes a string and capitalize the first letter of each word,
// then returns the modified string. However. if the first character is a space or a number,
// the function must validate this edge case before processing to avoid unexpected results.

// 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
console.log(capitalise("reza"));

// =============> the parameter name and the variable are the same while causes this error
// =============> write your new code here

function capitalise(str) {
const cap_string = `${str[0].toUpperCase()}${str.slice(1)}`;
return cap_string;
};

console.log(capitalise("reza"));
18 changes: 15 additions & 3 deletions Sprint-2/1-key-errors/1.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// Predict and explain first...

// Why will an error occur when this program runs?
// =============> write your prediction here
// =============> decimalNumber is already the name of the function parameter.
// You can't redeclare a variable with the same name in the same scope. and we do not even need to
// define a new variable

// Try playing computer with the example to work out what is going on

Expand All @@ -12,9 +14,19 @@ function convertToPercentage(decimalNumber) {
return percentage;
}

console.log(decimalNumber);
console.log(convertToPercentage(50));

// =============> i removed the variable

// =============> write your explanation here

// Finally, correct the code to fix the problem
// =============> write your new code here

function convertToPercentage(decimalNumber) {
const percentage = `${decimalNumber * 100}%`;

return percentage;
}


console.log(convertToPercentage(50));
37 changes: 33 additions & 4 deletions Sprint-2/1-key-errors/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,47 @@

// this function should square any number but instead we're going to get an error

// =============> write your prediction of the error here
// =============> the parameter can not be a number
// Valid JavaScript Identifiers
// Must start with a letter (a-z, A-Z), underscore (_), or dollar sign ($).
// Cannot start with a number (0-9).
// Can contain letters, numbers, underscores, or dollar signs after the first character.
// Cannot be a reserved keyword (e.g., if, else, function, return).

function square(3) {
return num * num;
}
// function square(3) {
// return num * num;
// }

// console.log(square(4));

// =============> write the error message here
// /Users/setup/Documents/CYF/Module-Structuring-and-Testing-Data/Sprint-2/1-key-errors/2.js:13
// function square(3) {
// ^

// SyntaxError: Unexpected number
// at wrapSafe (node:internal/modules/cjs/loader:1662:18)
// at Module._compile (node:internal/modules/cjs/loader:1704:20)
// at Object..js (node:internal/modules/cjs/loader:1895:10)
// at Module.load (node:internal/modules/cjs/loader:1465:32)
// at Function._load (node:internal/modules/cjs/loader:1282:12)
// at TracingChannel.traceSync (node:diagnostics_channel:322:14)
// at wrapModuleLoad (node:internal/modules/cjs/loader:235:24)
// at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
// at node:internal/main/run_main_module:36:49

// Node.js v22.16.0

// =============> explain this error message here
// First Two Lines: Locate the file path and the specific line of code causing the error.
// Following Lines: Display the type of error (SyntaxError) and its message.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a simple and straight forward explanation, nice job


// Finally, correct the code to fix the problem

// =============> write your new code here
function square(num) {
return num * num;
}

console.log(square(4));

9 changes: 9 additions & 0 deletions Sprint-2/2-mandatory-debug/0.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Predict and explain first...

// =============> write your prediction here
// the console.log inside the function will run but the one in global will raise the undefine error
// we will get an undefine error because we are not retuning the value

function multiply(a, b) {
console.log(a * b);
Expand All @@ -9,6 +11,13 @@ function multiply(a, b) {
console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`);

// =============> write your explanation here
// To use the final result of a function, we must return the value. Otherwise, it will raise an undefined error.

// Finally, correct the code to fix the problem
// =============> write your new code here
function multiply(a, b) {
const result = a * b;
return result;
}

console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You provided the right solution here, with a simple suggestion.

The console.log in the function is not necessary, as you will notice that the final result will print out two results, the first is just the result, and the second will be the statement in line 24

10 changes: 10 additions & 0 deletions Sprint-2/2-mandatory-debug/1.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Predict and explain first...
// =============> write your prediction here
// Lines of code after a return statement are not executed, as the function exits immediately at that point


function sum(a, b) {
return;
Expand All @@ -9,5 +11,13 @@ function sum(a, b) {
console.log(`The sum of 10 and 32 is ${sum(10, 32)}`);

// =============> write your explanation here
// we have to write the code inform of the return

// Finally, correct the code to fix the problem
// =============> write your new code here

function sum(a, b) {
return a + b;
}

console.log(`The sum of 10 and 32 is ${sum(10, 32)}`);
17 changes: 15 additions & 2 deletions Sprint-2/2-mandatory-debug/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

// Predict the output of the following code:
// =============> Write your prediction here
// Since we haven't defined a parameter for the function, it won't use any arguments we pass to it.
// Instead, every time we call the function, it will use the num value in its calculation.

const num = 103;

Expand All @@ -15,10 +17,21 @@ 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
// we get the same output for all the consol,log

// =============> write your explanation here
// we get the same output because the Function is not using the argument we send
// but instead is using the number in the variable num

// 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

function getLastDigit(num) {
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)}`);
8 changes: 6 additions & 2 deletions Sprint-2/3-mandatory-implement/1-bmi.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,9 @@
// 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
}
const height_squared = height * height;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simple solutions that are simple to read are always good code, which you have done here. Just want to draw your attention to some built-in methods that JavaScript has for this same thing

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow

const bmi = height_squared / weight;
return bmi.toFixed(1);
}

console.log(calculateBMI(83, 180));
9 changes: 9 additions & 0 deletions Sprint-2/3-mandatory-implement/2-cases.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,12 @@
// You will need to come up with an appropriate name for the function
// Use the MDN string documentation to help you find a solution
// This might help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase

function upper_snake_case(string) {
const replace_space = string.replaceAll(" ", "_");
const to_uppercase = replace_space.toUpperCase();
return to_uppercase;
}

console.log(upper_snake_case("hello there"));
console.log(upper_snake_case("lord of the rings"));
26 changes: 26 additions & 0 deletions Sprint-2/3-mandatory-implement/3-to-pounds.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,29 @@
// 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

function toPounds(penceString) {
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");

return `£${pounds}.${pence}`;
}

// Test cases
console.log(toPounds("399p"));
console.log(toPounds("9p"));
console.log(toPounds("1234p")); // £12.34 (assuming input can be longer than 3 digits)
console.log(toPounds("0p"));
console.log(toPounds("5p"));
12 changes: 7 additions & 5 deletions Sprint-2/4-mandatory-interpret/time-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,20 @@ function formatTimeDisplay(seconds) {
// Questions

// a) When formatTimeDisplay is called how many times will pad be called?
// =============> write your answer here
// =============> 3

// 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
// =============> 0

// c) What is the return value of pad is called for the first time?
// =============> write your answer here
// =============> "00"

// d) What is the value assigned to num when pad is called for the last time in this program? Explain your answer
// =============> write your answer here
// =============> 1
// Last pad call is pad(remainingSeconds), and remainingSeconds = 61 % 60 = 1

// e) What is the return value assigned to num when pad is called for the last time in this program? Explain your answer
// =============> write your answer here
// =============> "01"
// pad(1) => "01" because "1".padStart(2, "0") results in "01"
22 changes: 18 additions & 4 deletions Sprint-2/5-stretch-extend/format-time.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,18 @@
// 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`;
const [hourStr, minuteStr] = time.split(":");
const hours = Number(hourStr);

let period = hours >= 12 ? "pm" : "am";
let displayHour = hours % 12;
if (displayHour === 0) {
displayHour = 12; // Handles 00:xx (midnight) and 12:xx (noon)
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your solution is returning 12 pm when we expect to see 12:00 pm, for example.

You need to take a look at the original question again and see how you can do that 🙂

return `${time} am`;
// If you input "08:00" is allowed to pass
const paddedHour = hourStr.length === 2 && displayHour < 10 ? `0${displayHour}` : `${displayHour}`;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work in formatting the hour it is returned. I have a resource that you might want to consider should you need to do this again in the future

String Padding


return `${paddedHour}:${minuteStr} ${period}`;
}

const currentOutput = formatAs12HourClock("08:00");
Expand All @@ -23,3 +30,10 @@ console.assert(
currentOutput2 === targetOutput2,
`current output: ${currentOutput2}, target output: ${targetOutput2}`
);

console.assert(formatAs12HourClock("00:00") === "12:00 am", "Midnight failed");
console.assert(formatAs12HourClock("01:00") === "01:00 am", "1am failed");
console.assert(formatAs12HourClock("08:00") === "08:00 am", "8am failed");
console.assert(formatAs12HourClock("12:00") === "12:00 pm", "Noon failed");
console.assert(formatAs12HourClock("13:00") === "01:00 pm", "1pm failed");
console.assert(formatAs12HourClock("23:00") === "11:00 pm", "11pm failed");