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

Week 1 assignments completed. #369

Open
wants to merge 1 commit into
base: hkirat/with-tests
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
8 changes: 8 additions & 0 deletions 01-js/easy/anagram.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,15 @@
*/

function isAnagram(str1, str2) {
// Remove spaces and convert to lowercase for case-insensitive comparison
const cleanedStr1 = str1.replace(/\s/g, '').toLowerCase();
const cleanedStr2 = str2.replace(/\s/g, '').toLowerCase();

// Sort the characters in both strings and compare
const sortedStr1 = cleanedStr1.split('').sort().join('');
const sortedStr2 = cleanedStr2.split('').sort().join('');

return sortedStr1 === sortedStr2;
}

module.exports = isAnagram;
25 changes: 24 additions & 1 deletion 01-js/easy/expenditure-analysis.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,30 @@
*/

function calculateTotalSpentByCategory(transactions) {
return [];
let totalSpentByCategory = {};

for (let i = 0; i < transactions.length; i += 1) {
var transaction = transactions[i];

if(totalSpentByCategory[transaction.category]) {
totalSpentByCategory[transaction.category] = (totalSpentByCategory[transaction.category] + transaction.price);
} else {
totalSpentByCategory[transaction.category] = transaction.price;
}
}

let keys = Object.keys(totalSpentByCategory);

// Iterate through transactions to calculate total spent on each category

let resultArray = [];
for (let i = 0; i < keys.length; i += 1) {
let transaction = keys[i];
resultArray.push({category: transaction, totalSpent: totalSpentByCategory[transaction]});
}

return resultArray;

}

module.exports = calculateTotalSpentByCategory;
54 changes: 53 additions & 1 deletion 01-js/hard/calculator.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,58 @@
- `npm run test-calculator`
*/

class Calculator {}
class Calculator {
constructor() {
this.result = 0;
}

add(number) {
this.result += number;
}

subtract(number) {
this.result -= number;
}

multiply(number) {
this.result *= number;
}

divide(number) {
if(number == 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number
}

clear() {
this.result = 0;
}

getResult() {
return this.result;
}

calculate(expression) {
// Remove spaces
const sanitizedExpression = expression.replace(/\s+/g, '');
if (!/^[0-9+\-*/(). ]+$/.test(sanitizedExpression)) {
throw new Error("Invalid expression");
}
try {
// Use eval to calculate the expression
this.result = eval(sanitizedExpression);

// Check for division by zero
if (!isFinite(this.result)) {
throw new Error("Cannot divide by zero");
}
} catch (error) {
throw new Error("Invalid expression");
}
}

}


module.exports = Calculator;
33 changes: 33 additions & 0 deletions 01-js/hard/todo-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,40 @@
*/

class Todo {
constructor() {
this.todos = [];
}

add(todo) {
this.todos.push(todo);
}

remove(indexOfTodo) {
if (indexOfTodo >= 0 && indexOfTodo < this.todos.length) {
this.todos.splice(indexOfTodo, 1);
}
}

update(index, updatedTodo) {
if (index >= 0 && index < this.todos.length) {
this.todos[index] = updatedTodo;
}
}

getAll() {
return this.todos;
}

get(indexOfTodo) {
if (indexOfTodo >= 0 && indexOfTodo < this.todos.length) {
return this.todos[indexOfTodo];
}
return null;
}

clear() {
this.todos = [];
}
}

module.exports = Todo;
9 changes: 9 additions & 0 deletions 01-js/medium/palindrome.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@
*/

function isPalindrome(str) {
const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();

// Compare characters from start and end
for (let i = 0; i < cleanStr.length / 2; i++) {
if (cleanStr[i] !== cleanStr[cleanStr.length - 1 - i]) {
return false;
}
}

return true;
}

Expand Down
25 changes: 23 additions & 2 deletions 01-js/medium/times.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,27 @@ Try running it for
Hint - use Date class exposed in JS
*/

function calculateSum(n) {
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
return sum;
}

function calculateTime(n) {
return 0.01;
}
const startTime = new Date();
calculateSum(n);
const endTime = new Date();

// calculate the difference...
const timeInSeconds = (endTime - startTime) / 1000;

console.log(`Sum from 1 to ${n}: ${timeInSeconds.toFixed(6)} seconds`);
}


// Test with different values of n
calculateTime(100);
calculateTime(100000);
calculateTime(1000000000);
11 changes: 10 additions & 1 deletion 02-async-js/easy/1-counter.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
## Create a counter in JavaScript

We have already covered this in the second lesson, but as an easy recap try to code a counter in Javascript
It should go up as time goes by in intervals of 1 second
It should go up as time goes by in intervals of 1 second

var counter = 0;

function printAndIncreaseCount() {
console.log(counter);
counter += 1;
}

setInterval(printAndIncreaseCount, 1000);
10 changes: 10 additions & 0 deletions 02-async-js/easy/2-counter.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@

Without using setInterval, try to code a counter in Javascript. There is a hint at the bottom of the file if you get stuck.

var counter = 0;

function printAndIncreaseCount() {
console.log(counter);
counter += 1;
}

for (var i = 0; i <= 100; i += 1) {
setTimeout(printAndIncreaseCount,(i+1)*1000);
}



Expand Down
16 changes: 16 additions & 0 deletions 02-async-js/easy/3-read-from-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,19 @@ You can use the fs library to as a black box, the goal is to understand async ta
Try to do an expensive operation below the file read and see how it affects the output.
Make the expensive operation more and more expensive and see how it affects the output.

const fs = require('fs);

function printFile(err, data) {
if(err) {
console.error(err);
return;
}
console.log(data);
}

fs.readFile('/path/to/your/file', 'utf-8', printFile)

counter = 0;
for (var i = 0; i < 1000000000; i += 1) {
counter += 1;
}
16 changes: 15 additions & 1 deletion 02-async-js/easy/4-write-to-file.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
## Write to a file
Using the fs library again, try to write to the contents of a file.
You can use the fs library to as a black box, the goal is to understand async tasks.
You can use the fs library to as a black box, the goal is to understand async tasks.

const fs = require('fs);

let data = "This is some sample data to write to the file";

function afterContentsUpdated(err) {
if(err) {
console.error(err);
return;
}
console.log('File has been written');
}

fs.writeFile('/path/to/your/file', 'utf-8', afterContentsUpdated);
11 changes: 10 additions & 1 deletion 02-async-js/hard (promises)/1-promisify-setTimeout.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,13 @@
*/

function wait(n) {
}
return new Promise(resolve => {
setTimeout(() => {
resolve('Promise resolved after ${n} seconds', n*1000);
});
});
}

wait(5).then(result => {
console.log(result);
});
5 changes: 4 additions & 1 deletion 02-async-js/hard (promises)/2-sleep-completely.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,8 @@
*/

function sleep (seconds) {

const start = Date.now();
while (Date.now() - start < milliseconds) {
// Busy-waiting
}
}
33 changes: 29 additions & 4 deletions 02-async-js/hard (promises)/3-promise-all.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,42 @@


function waitOneSecond() {

return new Promise(resolve => {
setTimeout(() => {
resolve('Promise resolved after 1 second', 1000);
});
});
}

function waitTwoSecond() {

return new Promise(resolve => {
setTimeout(() => {
resolve('Promise resolved after 2 second', 2000);
});
});
}

function waitThreeSecond() {

return new Promise(resolve => {
setTimeout(() => {
resolve('Promise resolved after 3 second', 3000);
});
});
}

function calculateTime() {
const startTime = Date.now();

Promise.all([waitOneSecond(), waitTwoSecond(), waitThreeSecond()])
.then(results => {
const endTime = Date.now();
const totalTime = endTime - startTime;
console.log(`All promises resolved in ${totalTime} milliseconds`);
console.log(results);
})
.catch(error => {
console.error(`Error: ${error.message}`);
});
}

}
calculateTime();
Loading