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
38 changes: 34 additions & 4 deletions Sprint-2/1-key-errors/0.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,43 @@
// Predict and explain first...
// =============> write your prediction here
// It will return an error.

// 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;
}
//function capitalise(str) {
// let str = `${str[0].toUpperCase()}${str.slice(1)}`;
// return str;
//}

//SyntaxError: Identifier 'str' has already been declared
//
// =============> write your explanation here
// The error is a SyntaxError, trying to redeclare the "str" variable
// =============> write your new code here

function capitalise(str) {
if (typeof str !== "string" || str.length === 0) {
return str;
}

let foundFirstLetter = false;

return str
.split("") // convert string to array of characters
.map((char) => {
if (!foundFirstLetter && char !== " ") {
foundFirstLetter = true; // first non-space character found
return char.toUpperCase(); // capitalize it
}
return char; // leave other characters as-is
})
.join(""); // convert back to string
}
console.log(capitalise("hello world")); // "Hello world"
console.log(capitalise(" leading space")); // " Leading space"
console.log(capitalise("")); // ""
console.log(capitalise(" ")); // " "
console.log(capitalise(123)); // 123
console.log(capitalise("a")); // "A"
console.log(capitalise(" A")); // " A"
30 changes: 23 additions & 7 deletions Sprint-2/1-key-errors/1.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,35 @@

// Why will an error occur when this program runs?
// =============> write your prediction here
// It will return an error
// The function is trying to redeclare the 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;
}
//function convertToPercentage(decimalNumber) {
// const decimalNumber = 0.5;
// const percentage = `${decimalNumber * 100}%`;
//
// return percentage;
//}

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

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

// Finally, correct the code to fix the problem
// =============> write your new code here
//
function convertToPercentage(decimalNumber) {
const isValidNumber = Number(decimalNumber);

if (isNaN(isValidNumber)) return "Invalid input";
const convertedNumber = `${isValidNumber * 100}%`;

return convertedNumber;
}

console.log(convertToPercentage(0.1));
console.log(convertToPercentage(-0.1));
console.log(convertToPercentage(null));
console.log(convertToPercentage("1.2"));
22 changes: 18 additions & 4 deletions Sprint-2/1-key-errors/2.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,34 @@

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

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

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

// =============> explain this error message here
// function parameters can't be numbers same as variable name declaration

// Finally, correct the code to fix the problem

// =============> write your new code here

function square(num) {
const value = Number(num);
if (isNaN(value)) return "Invalid input";
const squaredNum = value * value;
if (!Number.isSafeInteger(squaredNum)) return "Integer Overflow";
return squaredNum;
}

console.log(square(3));
console.log(square("90000000"));
console.log(square(1e8));
console.log(square("hello"));
console.log(square(94906265));
6 changes: 5 additions & 1 deletion Sprint-2/2-mandatory-debug/0.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
// Predict and explain first...

// =============> write your prediction here
// It will run but not as intended

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

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

// =============> write your explanation here
// the function logs the product, but it does not return it.
// after the funtion is ecxecuted if the function does not have a return value it
// will return undefined as default

// Finally, correct the code to fix the problem
// =============> write your new code here
6 changes: 6 additions & 0 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
// the program will run and return undefined

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

// =============> write your explanation here
// a soon as the function is called it immidaitely return
// and will not reach the a + b line
// Finally, correct the code to fix the problem
// =============> write your new code here
function sum(a, b) {
return a + b;
}
10 changes: 10 additions & 0 deletions Sprint-2/2-mandatory-debug/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

// Predict the output of the following code:
// =============> Write your prediction here
// the program will run but not as intended

const num = 103;

Expand All @@ -15,10 +16,19 @@ 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
// node 2.js
//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 function getLastDigit does not have parameter so it will alway return the
// last value whatever value the num variable is asigned to
// Finally, correct the code to fix the problem
// =============> write your new code here
function getLastDigit(number) {
return number.toString().slice(-1);
}

// This program should tell the user the last digit of each number.
// Explain why getLastDigit is not working properly - correct the problem
10 changes: 8 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,11 @@
// 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 validWeight = Number(weight);
const validHeight = Number(height);

const bmi = validWeight / (validHeight * validHeight);

return bmi.toFixed(1);
}
console.log(calculateBMI(70, 1.73));
9 changes: 8 additions & 1 deletion Sprint-2/3-mandatory-implement/2-cases.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// 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.

Expand All @@ -14,3 +13,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(str) {
if (typeof str !== "string") return "Invalid input";
let toConvert = str;
return toConvert.trim().split(/\s+/).join("_").toUpperCase();
}
console.log(toUpperSnakeCase("hello world"));
console.log(toUpperSnakeCase(" Lord of the rings "));
console.log(toUpperSnakeCase(312321));
34 changes: 33 additions & 1 deletion Sprint-2/3-mandatory-implement/3-to-pounds.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,38 @@
// 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
// assuming the function will revieve the the parameter in a format same as "399p"
// Function to convert pence to pounds
function toPounds(penceString) {
// Remove the trailing "p"
const penceStringWithoutTrailingP = penceString.substring(
0,
penceString.length - 1
);

// Pad the number to ensure it has at least 3 digits
const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");

// Get the pounds part (everything except the last 2 digits)
const pounds = paddedPenceNumberString.substring(
0,
paddedPenceNumberString.length - 2
);

// Get the pence part (the last 2 digits)
const pence = paddedPenceNumberString
.substring(paddedPenceNumberString.length - 2)
.padEnd(2, "0");

// Return the formatted price as pounds and pence
return `£${pounds}.${pence}`;
}
// Test the function with different inputs
console.log(toPounds("399p"));
console.log(toPounds("5p"));
console.log(toPounds("100p"));
console.log(toPounds("50p"));
console.log(toPounds("999p"));
console.log(toPounds("123p"));
11 changes: 8 additions & 3 deletions Sprint-2/4-mandatory-interpret/time-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,22 @@ function formatTimeDisplay(seconds) {

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

// Three times
// 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, Because the value that will be stored in the remainingSeconds is 61 % 60
// which is 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", This is because the padStart methond checks if the value from the
// num.toString is less than 2 then it will add a padding in this case it is the
// character '0'
42 changes: 27 additions & 15 deletions Sprint-2/5-stretch-extend/format-time.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,36 @@
// 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`;
//}

function formatAs12HourClock(time) {
// Extract hours and minutes from the input time
const hours = Number(time.slice(0, 2));
const minutes = time.slice(3);

// Handle edge case for "00:00"
if (hours === 0) {
return `12:${minutes} am`;
}

// Handle case for "12:00" (noon or midnight)
if (hours === 12) {
return `12:${minutes} pm`;
}

// If hours are greater than 12, convert to 12-hour format and use "pm"
if (hours > 12) {
return `${hours - 12}:00 pm`;
return `${hours - 12 < 10 ? "0" + (hours - 12) : hours - 12}:${minutes} pm`;
}
return `${time} am`;
}

const currentOutput = formatAs12HourClock("08:00");
const targetOutput = "08:00 am";
console.assert(
currentOutput === targetOutput,
`current output: ${currentOutput}, target output: ${targetOutput}`
);
// For hours less than 12, use "am" (with leading zero for hours < 10)
return `${hours < 10 ? "0" + hours : hours}:${minutes} am`;
}

const currentOutput2 = formatAs12HourClock("23:00");
const targetOutput2 = "11:00 pm";
console.assert(
currentOutput2 === targetOutput2,
`current output: ${currentOutput2}, target output: ${targetOutput2}`
);
module.exports = formatAs12HourClock;
34 changes: 34 additions & 0 deletions Sprint-2/5-stretch-extend/test-format-time.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// testFormatAs12HourClock.js
const assert = require("assert");
const formatAs12HourClock = require("./format-time.js");

function testFormatAs12HourClock() {
// Valid inputs and expected outputs
const testCases = [
{ input: "08:00", expected: "08:00 am" }, // Standard AM case
{ input: "23:00", expected: "11:00 pm" }, // PM case, after 12
{ input: "12:00", expected: "12:00 pm" }, // Noon
{ input: "00:00", expected: "12:00 am" }, // Midnight
{ input: "01:00", expected: "01:00 am" }, // Single digit hour with AM
{ input: "12:01", expected: "12:01 pm" }, // 12:01 pm case
{ input: "13:45", expected: "01:45 pm" }, // 1:45 pm case
{ input: "18:30", expected: "06:30 pm" }, // 6:30 pm case
{ input: "02:59", expected: "02:59 am" }, // AM time close to 03:00
{ input: "11:15", expected: "11:15 am" }, // AM case near noon
{ input: "00:00", expected: "12:00 am" }, // Midnight with minutes
];

// Loop through test cases and check if the function returns the correct output
testCases.forEach(({ input, expected }) => {
const result = formatAs12HourClock(input);
assert.strictEqual(
result,
expected,
`For input ${input}, expected ${expected}, but got ${result}`
);
});

console.log("All tests passed!");
}

testFormatAs12HourClock();