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
15 changes: 10 additions & 5 deletions Sprint-3/1-key-errors/0.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
// Predict and explain first...
// =============> write your prediction here
// Prediction: Node will report a SyntaxError because str is declared twice in
// the same function scope: once as a parameter and again with let.

// call the function capitalise with a string input
// interpret the error message and figure out why an error is occurring

// Faulty line from the original: let str = `${str[0].toUpperCase()}${str.slice(1)}`;

// Error: SyntaxError: Identifier 'str' has already been declared
// Explanation: A function parameter is already a binding in the function body.
// Declaring another let binding with the same name is not allowed.
// Corrected code:
function capitalise(str) {
let str = `${str[0].toUpperCase()}${str.slice(1)}`;
return str;
return `${str[0].toUpperCase()}${str.slice(1)}`;
}

// =============> write your explanation here
// =============> write your new code here
console.log(capitalise("hello"));
25 changes: 14 additions & 11 deletions Sprint-3/1-key-errors/1.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
// Predict and explain first...

// Why will an error occur when this program runs?
// =============> write your prediction here
// Prediction: Node will report a SyntaxError because decimalNumber is declared
// as a const inside the function even though it is already a parameter.

// 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);
// Faulty original lines:
// const decimalNumber = 0.5; // duplicates the parameter inside the function
// console.log(decimalNumber); // refers to the parameter outside its scope

// =============> write your explanation here
// Error: SyntaxError: Identifier 'decimalNumber' has already been declared
// Explanation: The parameter already declares decimalNumber in the function
// scope. The inner const declaration duplicates that binding. Also, the final
// console.log refers to a name that would not be available outside the function.

// Finally, correct the code to fix the problem
// =============> write your new code here
function convertToPercentage(decimalNumber) {
return `${decimalNumber * 100}%`;
}

console.log(convertToPercentage(0.5));
18 changes: 11 additions & 7 deletions Sprint-3/1-key-errors/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,22 @@

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

// =============> write your prediction of the error here
// Prediction: Node will report a SyntaxError because a number cannot be used
// as a function parameter name.

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

// =============> write the error message here
// Error: SyntaxError: Unexpected number

// =============> explain this error message here
// Explanation: Function parameters must be identifiers such as num, not literal
// values such as 3. The body also refers to num, which was never declared.

// Finally, correct the code to fix the problem

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

console.log(square(3));


17 changes: 13 additions & 4 deletions Sprint-3/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
// Prediction: The multiplication itself prints 320, but the template string
// then shows undefined because multiply does not return the result.

function multiply(a, b) {
function multiplyBeforeFix(a, b) {
console.log(a * b);
}

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

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

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

// =============> write your explanation here
// Observed before the fix: 320, then "undefined" in the template string.
// Explanation: console.log displays the product but returns undefined. The
// function call inside the template string therefore evaluates to undefined.

// Finally, correct the code to fix the problem
// =============> write your new code here
// The corrected function above returns the product for the template string.
17 changes: 13 additions & 4 deletions Sprint-3/2-mandatory-debug/1.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
// Predict and explain first...
// =============> write your prediction here
// Prediction: The output will say undefined because return exits the function
// before the addition expression can run.

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

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

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

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

// =============> write your explanation here
// Observed before the fix: undefined.
// Explanation: A newline immediately after return ends the return statement.
// The function returns undefined and the following expression is unreachable.
// Finally, correct the code to fix the problem
// =============> write your new code here
// The corrected function above returns the sum.
24 changes: 16 additions & 8 deletions Sprint-3/2-mandatory-debug/2.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,32 @@
// Predict and explain first...

// Predict the output of the following code:
// =============> Write your prediction here
// Prediction: Each line reports 103's last digit (3), because getLastDigit
// ignores its arguments and always reads the global num variable.

const num = 103;

function getLastDigit() {
function getLastDigitBeforeFix() {
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)}`);
console.log(`The last digit of 42 is ${getLastDigitBeforeFix(42)}`);
console.log(`The last digit of 105 is ${getLastDigitBeforeFix(105)}`);
console.log(`The last digit of 806 is ${getLastDigitBeforeFix(806)}`);

// Now run the code and compare the output to your prediction
// =============> write the output here
// Output: Each line reports 3.
// Explain why the output is the way it is
// =============> write your explanation here
// Explanation: getLastDigit has no parameter and reads the unchanged global
// num (103), so passing 42, 105, or 806 has no effect.
// Finally, correct the code to fix the problem
// =============> write your new code here
function getLastDigit(number) {
return number.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
5 changes: 4 additions & 1 deletion Sprint-3/3-mandatory-implement/1-bmi.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,8 @@
// It should return a string of their Body Mass Index to 1 decimal place

function calculateBMI(weight, height) {
// return the BMI of someone based off their weight and height
return (weight / height ** 2).toFixed(1);
}

console.log(calculateBMI(70, 1.73));
console.log(calculateBMI(60, 1.65));
8 changes: 8 additions & 0 deletions Sprint-3/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(input) {
return input.trim().replace(/\s+/g, "_").toUpperCase();
}

console.log(toUpperSnakeCase("hello there"));
console.log(toUpperSnakeCase("lord of the rings"));
console.log(toUpperSnakeCase(" multiple spaces "));
15 changes: 15 additions & 0 deletions Sprint-3/3-mandatory-implement/3-to-pounds.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,18 @@
// 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 penceDigits = penceString.endsWith("p")
? penceString.slice(0, -1)
: penceString;
const paddedPence = penceDigits.padStart(3, "0");
const pounds = paddedPence.slice(0, -2);
const pence = paddedPence.slice(-2);

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

console.log(toPounds("399p"));
console.log(toPounds("9p"));
console.log(toPounds("1200p"));
12 changes: 7 additions & 5 deletions Sprint-3/4-mandatory-interpret/time-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,26 @@ function formatTimeDisplay(seconds) {
return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`;
}

console.log(formatTimeDisplay(61));

// You will need to play computer with this example - use the Python Visualiser https://pythontutor.com/visualize.html#mode=edit
// to help you answer these questions

// Questions

// a) When formatTimeDisplay is called how many times will pad be called?
// =============> write your answer here
// Answer: Three times, once for hours, once for minutes, and once for seconds.

// 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
// Answer: 0, because 61 seconds contains 0 whole hours.

// c) What is the return value of pad when it is called for the first time?
// =============> write your answer here
// Answer: "00". pad converts 0 to a string and prepends a zero.

// 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
// Answer: 1, because the remaining seconds after 61 is divided into minutes is 1.

// e) What is the return value of pad when it is called for the last time in this program? Explain your answer
// =============> write your answer here
// Answer: "01", because pad converts 1 to a string and prepends a zero.
39 changes: 23 additions & 16 deletions Sprint-3/5-stretch-extend/format-time.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,31 @@
// 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.

const assert = require("node:assert/strict");

function formatAs12HourClock(time) {
const hours = Number(time.slice(0, 2));
if (hours > 12) {
return `${hours - 12}:00 pm`;
if (typeof time !== "string" || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(time)) {
throw new RangeError("time must be a valid 24-hour time in HH:MM format");
}
return `${time} am`;

const hours = Number(time.slice(0, 2));
const displayHours = String(hours % 12 || 12).padStart(2, "0");
const minutes = time.slice(3);
const period = hours < 12 ? "am" : "pm";

return `${displayHours}:${minutes} ${period}`;
}

const currentOutput = formatAs12HourClock("08:00");
const targetOutput = "08:00 am";
console.assert(
currentOutput === targetOutput,
`current output: ${currentOutput}, target output: ${targetOutput}`
);
assert.equal(formatAs12HourClock("00:00"), "12:00 am");
assert.equal(formatAs12HourClock("00:05"), "12:05 am");
assert.equal(formatAs12HourClock("08:00"), "08:00 am");
assert.equal(formatAs12HourClock("11:59"), "11:59 am");
assert.equal(formatAs12HourClock("12:00"), "12:00 pm");
assert.equal(formatAs12HourClock("12:45"), "12:45 pm");
assert.equal(formatAs12HourClock("13:07"), "01:07 pm");
assert.equal(formatAs12HourClock("23:59"), "11:59 pm");
assert.throws(() => formatAs12HourClock("24:00"), RangeError);
assert.throws(() => formatAs12HourClock("12:60"), RangeError);
assert.throws(() => formatAs12HourClock("8:00"), RangeError);

const currentOutput2 = formatAs12HourClock("23:00");
const targetOutput2 = "11:00 pm";
console.assert(
currentOutput2 === targetOutput2,
`current output: ${currentOutput2}, target output: ${targetOutput2}`
);
console.log("All formatAs12HourClock tests passed.");
Loading