Skip to content
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

NW-6 | Zeliha Pala | JS1| [TECH ED] Complete week 2 exercises | WEEK-2 #165

Open
wants to merge 5 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 .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"cSpell.words": ["Visualiser"]
}
24 changes: 24 additions & 0 deletions test-sil.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
function calculate(str) {
//your code here...
str = `+${str}`;
str = str.replaceAll("plus", "+");
str = str.replaceAll("minus", "-");
let num;
while (str.length > 0) {
let lastMinus = str.lastIndexOf("-");
let lastPlus = str.lastIndexOf("+");

if (lastPlus > lastMinus) {
num += Number(str.slice(lastPlus + 1));
str = str.slice(0, lastPlus);
} else if (lastMinus > lastPlus) {
num -= Number(str.slice(lastMinus + 1));
str = str.slice(0, lastMinus);
} else {
break;
}
}

return num.toString();
}
console.log(calculate("1plus2plus3plus4"));
5 changes: 4 additions & 1 deletion week-2/debug/0.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
// Predict and explain first...

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

console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`);
//the console does not return any value without return , it will return undefined

// If we want a function to return a value, we should use the return keyword.
5 changes: 3 additions & 2 deletions week-2/debug/1.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// Predict and explain first...
//The semicolon (;) following the return statement causes an immediate termination of the function. This semicolon prevents the continuation of expressions within the block and disregards the rest of the function.

function sum(a, b) {
return;
a + b;
//return; a + b; } so it will be like this
return a + b;
}

console.log(`The sum of 10 and 32 is ${sum(10, 32)}`);
25 changes: 21 additions & 4 deletions week-2/debug/2.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,31 @@
// Predict and explain first...

const num = 103;
//Constant (const) declaration of 103
//return converts the value of the num variable to a string (using the toString() method),
// console.log gives last digit of any number.

// This program should tell the user the last digit of each number...
// Explain why getLastDigit is not working properly - correct the problem...

/* The issue is that the function is not using the parameter passed to it. It always returns the last digit of the constant num, which is set to 103. The function should take a parameter and return the last digit of that parameter. */

/*

const num = 103;
function getLastDigit() {
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 806 is ${getLastDigit(806)}`); */

//here is my solution ;

// This program should tell the user the last digit of each number.
// Explain why getLastDigit is not working properly - correct the problem
function getLastDigit(number) {
return number.toString().slice(-1); // we need only -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)}`);

Choose a reason for hiding this comment

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

You have explained this very well here. I understand what you wrote and did. 👍

Copy link
Author

Choose a reason for hiding this comment

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

Thank you

20 changes: 19 additions & 1 deletion week-2/errors/0.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,25 @@
// then call the function capitalise with a string input
// interpret the error message and figure out why it's happening, if your prediction was wrong

function capitalise(str) {
/* function capitalise(str) {
let str = `${str[0].toUpperCase()}${str.slice(1)}`;
return str;
}


function, named capitalise, is meant to take a text input and change its first letter to a capital letter.
It takes a text (str) as an input parameter.
It converts the first letter of the input text to uppercase using str[0].toUpperCase().
t takes the remaining part of the text after the first letter using str.slice(1).
It combines the uppercase first letter with the rest of the text to create a new text string where the first letter is capitalized.
Finally, it returns this newly formed text string.

The problem is that the code tries to use the name "str" for two different things inside the function, which isn't allowed in JavaScript. we can't have two variables with the same name within the same block of code.
To solve this issue, just rename the second "str" to something else, like "modifiedStr": */

function capitalise(str) {
Str = `${str[0].toUpperCase()}${str.slice(1)}`;
return Str;
}
Comment on lines +22 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.

Your explanation is correct here 👍
But I think your implementation may be improved.

Firstly, in JS we have a convention to use camelCasedNames, it means your new variable name should start with lowercased latter. Your suggestion t use modifiedStr is perfect for this purpose!

Secondly, if you introduce a new variable, you should use either let or const in the beginning.

Thirdly, just str = ${str[0].toUpperCase()}${str.slice(1)}`` (without let in front of it) should work too. As all the function arguments (like str here) may be changed as any variable declared with `let`.
But we should be careful with this approach, because after changing initial value of `str` we won't be able to refer to initial value any more.

Fourthly, you may even avoid creating variables her and just:

return `${str[0].toUpperCase()}${str.slice(1)}`;

console.log(capitalise("hello "));
//This way, each variable has its own unique name and the function will work without any errors.
11 changes: 10 additions & 1 deletion week-2/errors/1.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,20 @@
// Why will an error occur when this program runs?
// Play computer with the example to work out what is going on

const decimalNumber = 0.5; // defines decimalNumber in the outer scope

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

return percentage;
}

console.log(decimalNumber);

/*Answers

The variable decimalNumber is declared as a parameter inside the convertToPercentage function. Therefore, it's only accessible within the scope of that function. Trying to access decimalNumber outside of the function will result in a ReferenceError because it's not defined in that outer scope. So I defined decimalNumber in that scope.*/

console.log(convertToPercentage(0.5));
console.log(convertToPercentage(0.4));
16 changes: 8 additions & 8 deletions week-2/errors/2.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
/* Answer
there's a syntax error in the function definition. Function parameters should be variables, not specific values or numbers. In this case, 3 is being used as a parameter, which isn't allowed in JavaScript function declarations.

// Predict and explain first...
// this function should square any number but instead we're going to get an error
// what is happening? How can we fix it?

function square(3) {
return num * num;
To fix this, we should declare the function with a parameter representing the number we want to square. */
function square(num) {
return num * num;
}


console.log(square(4));
console.log(square(3));
console.log(square(5));
15 changes: 15 additions & 0 deletions week-2/implement/bmi.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,18 @@
// Given someone's weight in kg and height in metres
// When we call this function with the weight and height
// Then it returns their Body Mass Index to 1 decimal place

function calculateBMI(weight, height) {
const bmi = weight / (height * height);

//return parseFloat(bmi.toFixed(1));

// parsefloat finds the first number in a string and ignores other num
// foFixed(1 ) rounds the number to one decimal place as a string, I want a number so used parseFloat. But actually here is no need for a number we can use a string as well.

return bmi.toFixed(1);
}

console.log(calculateBMI(70, 1.73)); // Example input: weight 70kg, height 1.73m
console.log(calculateBMI(56, 1.65));
console.log(calculateBMI(87, 1.63));
39 changes: 39 additions & 0 deletions week-2/implement/cases.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,42 @@

// Come up with a clear, simple name for the function
// Use the string documentation to help you plan your solution

///answer

function toUpperCamelCase(inputString) {
// Split the input string by spaces
const movieName = inputString.split(" ");

// This is like creating an Array. For instance, when you input "lord of the rings," it transforms into an array ["lord", "of", "the", "rings"] by splitting it at each space.

// Capitalize each word and join them with underscores
const upperCamelCase = movieName.map((word) => word.toUpperCase()).join("_");

return upperCamelCase;
}

Choose a reason for hiding this comment

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

Could you explain what .split on line 23 and .map on line 26 does? I want to understand thhis better to know what you were doing.

console.log(toUpperCamelCase("lord of the rings")); // "LORD_OF_THE_RINGS"
console.log(toUpperCamelCase("the great gatsby")); // "THE_GREAT_GATSBY"
console.log(toUpperCamelCase("the da vinci code")); // "THE_DA_VINCI_CODE"
console.log(toUpperCamelCase("darkness of the night"));

// The map() function iterates over each element (each word) within the movieName array. It takes each element (referred to as word) and converts it to uppercase using toUpperCase(). After this transformation, it then joins these converted words (using join("_")) with an underscore (_) in between each word. This process results in a string where each word is in uppercase and separated by underscores.

//self study
/* function toUpperCamelCase(inputString) {
const movieName = inputString.split(" ");

const upperCamelCase = movieName.map((word, index) => {

if (index === 0 || index === movieName.length - 1) {
return word.toUpperCase();
} else {
return word.toLowerCase();
}
}).join("_");

return upperCamelCase;
}

console.log(toUpperCamelCase("the da vinci code")); // "THE_da_vinci_CODE"
21 changes: 21 additions & 0 deletions week-2/implement/to-pounds.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,24 @@
// Take this code and turn it into a reusable block of code.
// Declare a function called toPounds with an appropriately named parameter.
// Call this function a number of times to check it works for different inputs

function toPounds(str) {
const num = str.slice(0, -1).padStart(3, "0");
const pounds = num.slice(0, -2);
const pence = num.slice(-2);
return `£${pounds}.${pence}`;
}

Choose a reason for hiding this comment

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

This code is so neat and easily understandable.

//Test cases
console.log(toPounds("399p")); // Output: £3.99
console.log(toPounds("5p")); // Output: £0.05
console.log(toPounds("1094p")); // Output: £10.24
console.log${pounds("1094p")}; // Output: £10.24 *

/* The toPounds function:
Takes a string str representing an amount in pence.
Removes the 'p' from the end of the string and ensures it has at least three digits by adding leading zeros if necessary.
Separates the first part as pounds and the last two digits as pence.
Formats these values into the £X.YY (pounds and pence) format.
Returns the result.
The console.log statements demonstrate how the function converts different pence values into pounds and pence (£X.YY). Adjust the inputs to test other amounts! */
8 changes: 8 additions & 0 deletions week-2/implement/vat.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,11 @@
// Given a number,
// When I call this function with a number
// Then it returns the new price with VAT added on

function calculatePriceWithVAT(price) {
return price * 1.2; // Adds 20% VAT to the given price
}

const originalPrice = 59;
const priceWithVAT = calculatePriceWithVAT(originalPrice);
console.log(`Price with VAT: £${priceWithVAT}`);
21 changes: 12 additions & 9 deletions week-2/interpret/time-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,29 @@ function formatTimeDisplay(seconds) {
}

console.log(formatTimeDisplay(143));
console.log(formatTimeDisplay(2436));

// You can 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?
/* a) When formatTimeDisplay is called, how many times will pad be called?

// Call formatTimeDisplay with an input of 143, now answer the following:
In this scenario, the pad function will be called three times since there are three instances of pad within the formatTimeDisplay function: once each for hours, minutes, and seconds.
b) What value is assigned to the parameter num when pad is called for the first time?

// b) What value is assigned to the parameter num when pad is called for the first time?
When pad is called for the first time within formatTimeDisplay, it will be called with the value of remainingHours, which is derived from the calculations in the function.
c) What is the return value of pad when it is called for the first time?

// c) What is the return value of pad when it is called for the first time?
The pad function adds a leading zero to numbers less than 10. In this case, when called with remainingHours, if the value is less than 10, it will prepend a zero to the number and return a string with the leading zero and the value.
d) What is the value assigned to the parameter num when pad is called for the last time in this program? Explain your answer.

// d) What is the value assigned to the parameter num when pad
// is called for the last time in this program? Explain your answer
The last call to pad is for remainingSeconds, which has the value derived from the input argument of formatTimeDisplay(143). Therefore, the value of num when pad is called for the last time will be 3 (as 143 % 60 equals 3).
e) What is the return value when pad is called for the last time in this program? Explain your answer.

// e) What is the return value when pad is called
// for the last time in this program? Explain your answer
The pad function will return the string '03' because remainingSeconds is 3, which is less than 10, so the function adds a leading zero to meet the formatting criteria.

// f) Research an alternative way of padding the numbers in this code.
// Look up the string functions on mdn
// Look up the string functions on mdn.*/