Skip to content
Open
12 changes: 12 additions & 0 deletions Sprint-2/1-key-errors/0.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Predict and explain first...
// =============> write your prediction here
// The variable str is being declared twice within the same scope, which will cause a syntax error.

// call the function capitalise with a string input
// interpret the error message and figure out why an error is occurring
Expand All @@ -8,6 +9,17 @@ function capitalise(str) {
let str = `${str[0].toUpperCase()}${str.slice(1)}`;
return str;
}
const result = capitalise('hello');
console.log(result);
// SyntaxError: Identifier 'str' has already been declared

// =============> write your explanation here
// // The first declaration is in the function parameter and the second one is inside the function body.
// In JavaScript, you cannot declare the same variable name in the same scope using let or const.
// To fix this, we can either rename the inner variable or assign the capitalised value to the parameter itself without redeclaring it.

// =============> write your new code here
function capitalise(str) {
str = `${str[0].toUpperCase()}${str.slice(1)}`;
return str;
}
25 changes: 17 additions & 8 deletions Sprint-2/1-key-errors/1.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,29 @@
// Predict and explain first...

// Why will an error occur when this program runs?
// =============> write your prediction here
// constant decimalNumber is being declared twice within the same scope, which will cause a syntax error.

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

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

return percentage;
}
//return percentage;
//}

console.log(decimalNumber);
//console.log(decimalNumber);

// =============> write your explanation here
// SyntaxError: Identifier 'decimalNumber' has already been declared
// decimalNumber is declared as a parameter of the function and then again inside the function using const.
// In JavaScript, you cannot declare the same variable name in the same scope using let or const.
// Function input is ignored if a variable with the same name is declared inside the function body.
// const decimalNumber = 0.5 will always output 50% regardless of the input value.

// Finally, correct the code to fix the problem
// =============> write your new code here
function convertToPercentage(decimalNumber) {
const percentage = `${decimalNumber * 100}%`;
return percentage;
}
console.log(convertToPercentage(0.75)); // Example call to test the function
26 changes: 17 additions & 9 deletions Sprint-2/1-key-errors/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,26 @@

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

// =============> write your prediction of the error here
// The function does not define the parameter correctly
// Instead, the input has been inserted where the parameter name should be
// Then num is being used in the function body but it is not defined anywhere

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

// =============> write the error message here
// function square(3) {
// return num * num;
// }

// =============> explain this error message here
// SyntaxError: Unexpected number
// The number 3 is used directly in the function parameter
// The function parameter should be num to accept any number as input
// Then the function body can use num to square the input value
//Defining a function should describe the parameters it expects, not specific values

// Finally, correct the code to fix the problem

// =============> write your new code here
function square(num) {
return num * num;
}
console.log(square(5));
console.log(square(10));
console.log(square(-3));


15 changes: 12 additions & 3 deletions Sprint-2/2-mandatory-debug/0.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
// Predict and explain first...

// =============> write your prediction here
// console.log is being used inside the multiply function, which does not return any value.
// This will result in undefined being printed in the template literal.

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
// Output in the terminal was: "320
// The result of multiplying 10 and 32 is undefined"
// Console.log within the function prints the product of the calculation, but the function does not return the value to the global scope.
// Therefore within the template literal, the meaning of the multiply function call is undefined

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

function multiply(a, b) {
return a * b;
}

console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`);
12 changes: 9 additions & 3 deletions Sprint-2/2-mandatory-debug/1.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Predict and explain first...
// =============> write your prediction here
// a + b should be written on the same line as return statement
// This function will not return anything because of the semicolon, so when the function is call on line 10 it will be undefined.

function sum(a, b) {
return;
Expand All @@ -8,6 +9,11 @@ function sum(a, b) {

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

// =============> write your explanation here
// Terminal output "The sum of 10 and 32 is undefined"
// Console.log is calling a function that was not defined because the function body has an incorrect return statement.

// 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)}`);
19 changes: 15 additions & 4 deletions Sprint-2/2-mandatory-debug/2.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// Predict and explain first...

// Predict the output of the following code:
// =============> Write your prediction here
// This function will always return the last digit of the number 103.
// This is because the variable num is hardcoded to 103 within the function scope.

const num = 103;

Expand All @@ -14,11 +15,21 @@ 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
// The last digit of 42 is 3
// The last digit of 105 is 3
// The last digit of 806 is 3

// Explain why the output is the way it is
// =============> write your explanation here
// The number 103 is assigned as a constant variable so the function will always use num as 103
// So when the function is called with different arguments, it still returns the last digit of 103 which is 3

// Finally, correct the code to fix the problem
// =============> write your new code here
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)}`);

// This program should tell the user the last digit of each number.
// Explain why getLastDigit is not working properly - correct the problem
15 changes: 8 additions & 7 deletions Sprint-2/3-mandatory-implement/1-bmi.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
// 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
}
var bmi = (weight / (height * height));
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid using var to declare variables. Use let instead.

return bmi.toFixed(1);
Copy link
Contributor

Choose a reason for hiding this comment

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

What type of value do you expect the function to return? A number or a string?
Does your function return the type of value you expect?

}
console.log(calculateBMI(70, 1.73));
console.log(calculateBMI(95, 1.82));
console.log(calculateBMI(52, 1.6));
console.log(calculateBMI(110, 1.75));
console.log(calculateBMI(65, 1.9));
8 changes: 8 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,11 @@
// You will need to come up with an appropriate name for the function
// Use the MDN string documentation to help you find a solution
// This might help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase

function toUpperSnakeCase(string) {
return string.toUpperCase().replace(/ /g, "_");
}
console.log(toUpperSnakeCase("hello there"));
console.log(toUpperSnakeCase("lord of the rings"));
console.log(toUpperSnakeCase("javascript 4eva"));
console.log(toUpperSnakeCase("unit testing is important!!"));
32 changes: 30 additions & 2 deletions Sprint-2/3-mandatory-implement/3-to-pounds.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,34 @@
// 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

function toPounds(penceString) {
penceString = String(penceString);// ensures input is treated as a string even if number is inputted
// const penceStringWithoutTrailingP = penceString.substring(
let penceStringWithoutTrailingP = penceString;
if (penceString.endsWith("p")) {
penceStringWithoutTrailingP = penceString.substring(0, penceString.length - 1);
} // This prevents the last characters from being sliced off if there is no p.

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}`;
}
Comment on lines +6 to +25
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you improve the indentation of the code in this function?

Note: In VSCode, we can install the prettier extension and then use the "Format document" function" to automatically indent code.

console.log(toPounds("481p"));
console.log(toPounds("50p"));
console.log(toPounds("5p"));
console.log(toPounds("0p"));
console.log(toPounds("12345p"));
console.log(toPounds("9")); // edge case: missing 'p' at the end, returns 0 rather than error because last character is sliced off
// Can be fixed by changing line 8
console.log(toPounds("abc")); // Works but returns nonsense value
console.log(toPounds(123)); // Works with number input because of line 7 converting to string
19 changes: 12 additions & 7 deletions Sprint-2/4-mandatory-interpret/time-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ function pad(num) {
return num.toString().padStart(2, "0");
}

function formatTimeDisplay(seconds) {
function formatTimeDisplay(num) {
const remainingSeconds = seconds % 60;
const totalMinutes = (seconds - remainingSeconds) / 60;
const remainingMinutes = totalMinutes % 60;
Expand All @@ -17,18 +17,23 @@ function formatTimeDisplay(seconds) {
// Questions

// a) When formatTimeDisplay is called how many times will pad be called?
// =============> write your answer here
// 3 times: the return statement contains 3 pad calls within the formatTimeDisplay function.

// 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
// num = 0 as when the input is 61 seconds, remainingSeconds = 1, totalMinutes = 1, remainingMinutes = 1, totalHours = 0.
// totalHours = (totalMinutes - remainingMinutes) / 60 = (1 - 1) / 60 = 0 / 60 = 0 (dividing once into minutes and once into hours).

// c) What is the return value of pad is called for the first time?
// =============> write your answer here
// c) What is the return value of pad when called for the first time?
// "00" as num is 0, and padStart(2, "0") adds a leading zero to make it two digits.

// d) What is the value assigned to num when pad is called for the last time in this program? Explain your answer
// =============> write your answer here
// The last time pad is called, num is assigned the value of remainingSeconds, which is 1.
// Go to line const remainingSeconds = seconds % 60; and use input of seconds = 61 to calculate remainder of 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
// The last time pad is called, it uses remainingSeconds which is 1
// The call is pad(1) which converts to a string and adds a leading 0 if there's less than 2 characters
// So, the return value is "01".
// The final formatted time string for an input of 61 seconds is "00:01:01".
22 changes: 19 additions & 3 deletions Sprint-2/5-stretch-extend/format-time.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,17 @@
// 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) {
if (!/^\d{2}:\d{2}$/.test(time)) { //If input does not match HH:MM format, returns string "Invalid time format"
return "Invalid time format";
}

const hours = Number(time.slice(0, 2));
if (hours > 12) {
return `${hours - 12}:00 pm`;
}
const minutes = time.slice(3);
Copy link
Contributor

Choose a reason for hiding this comment

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

Could also consider use time.slice(-2) to better express we are extracting the last two characters.

if (hours === 0) return `12:${minutes} am`;
if (hours === 12) return `12:${minutes} pm`;
if (hours === 24) return `12:${minutes} am`;
if (hours > 12) return `${hours - 12}:00 pm`;

return `${time} am`;
Comment on lines +15 to 17
Copy link
Contributor

Choose a reason for hiding this comment

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

The return values of these two function calls are not formatted consistently.

console.log(formatAs12HourClock("15:30"));
console.log(formatAs12HourClock("03:30"));

Can you improve the consistency?

}

Expand All @@ -23,3 +30,12 @@ console.assert(
currentOutput2 === targetOutput2,
`current output: ${currentOutput2}, target output: ${targetOutput2}`
);

console.log(formatAs12HourClock("12:00")); //
console.log(formatAs12HourClock("00:00")); //
console.log(formatAs12HourClock("15:30")); //
console.log(formatAs12HourClock("11:45")); //
console.log(formatAs12HourClock("24:00")); //
console.log(formatAs12HourClock("ab:cd")); //
console.log(formatAs12HourClock("9:00")); //
console.log(formatAs12HourClock("09:0"));
Loading