diff --git a/01-js/easy/anagram.js b/01-js/easy/anagram.js index fff61427..b69d6fb8 100644 --- a/01-js/easy/anagram.js +++ b/01-js/easy/anagram.js @@ -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; diff --git a/01-js/easy/expenditure-analysis.js b/01-js/easy/expenditure-analysis.js index 20fbb943..9469f58f 100644 --- a/01-js/easy/expenditure-analysis.js +++ b/01-js/easy/expenditure-analysis.js @@ -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; diff --git a/01-js/hard/calculator.js b/01-js/hard/calculator.js index 82d48229..17905976 100644 --- a/01-js/hard/calculator.js +++ b/01-js/hard/calculator.js @@ -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; diff --git a/01-js/hard/todo-list.js b/01-js/hard/todo-list.js index 7c9c1806..e68bfaaf 100644 --- a/01-js/hard/todo-list.js +++ b/01-js/hard/todo-list.js @@ -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; diff --git a/01-js/medium/palindrome.js b/01-js/medium/palindrome.js index d8fe2d8f..7b2467de 100644 --- a/01-js/medium/palindrome.js +++ b/01-js/medium/palindrome.js @@ -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; } diff --git a/01-js/medium/times.js b/01-js/medium/times.js index eb125cc2..c245819f 100644 --- a/01-js/medium/times.js +++ b/01-js/medium/times.js @@ -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; -} \ No newline at end of file + 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); \ No newline at end of file diff --git a/02-async-js/easy/1-counter.md b/02-async-js/easy/1-counter.md index 54483eab..f5199404 100644 --- a/02-async-js/easy/1-counter.md +++ b/02-async-js/easy/1-counter.md @@ -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 \ No newline at end of file +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); \ No newline at end of file diff --git a/02-async-js/easy/2-counter.md b/02-async-js/easy/2-counter.md index db5f2fff..9ca27511 100644 --- a/02-async-js/easy/2-counter.md +++ b/02-async-js/easy/2-counter.md @@ -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); +} diff --git a/02-async-js/easy/3-read-from-file.md b/02-async-js/easy/3-read-from-file.md index f619d71a..f925bf17 100644 --- a/02-async-js/easy/3-read-from-file.md +++ b/02-async-js/easy/3-read-from-file.md @@ -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; +} \ No newline at end of file diff --git a/02-async-js/easy/4-write-to-file.md b/02-async-js/easy/4-write-to-file.md index f1c151f9..305944b7 100644 --- a/02-async-js/easy/4-write-to-file.md +++ b/02-async-js/easy/4-write-to-file.md @@ -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. \ No newline at end of file +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); \ No newline at end of file diff --git a/02-async-js/hard (promises)/1-promisify-setTimeout.js b/02-async-js/hard (promises)/1-promisify-setTimeout.js index cc0b7dd7..aca8f216 100644 --- a/02-async-js/hard (promises)/1-promisify-setTimeout.js +++ b/02-async-js/hard (promises)/1-promisify-setTimeout.js @@ -3,4 +3,13 @@ */ function wait(n) { -} \ No newline at end of file + return new Promise(resolve => { + setTimeout(() => { + resolve('Promise resolved after ${n} seconds', n*1000); + }); + }); +} + +wait(5).then(result => { + console.log(result); +}); \ No newline at end of file diff --git a/02-async-js/hard (promises)/2-sleep-completely.js b/02-async-js/hard (promises)/2-sleep-completely.js index 499a5647..ceb6185c 100644 --- a/02-async-js/hard (promises)/2-sleep-completely.js +++ b/02-async-js/hard (promises)/2-sleep-completely.js @@ -4,5 +4,8 @@ */ function sleep (seconds) { - + const start = Date.now(); + while (Date.now() - start < milliseconds) { + // Busy-waiting + } } \ No newline at end of file diff --git a/02-async-js/hard (promises)/3-promise-all.js b/02-async-js/hard (promises)/3-promise-all.js index 5028a009..2391df28 100644 --- a/02-async-js/hard (promises)/3-promise-all.js +++ b/02-async-js/hard (promises)/3-promise-all.js @@ -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}`); + }); +} -} \ No newline at end of file +calculateTime(); \ No newline at end of file diff --git a/02-async-js/hard (promises)/4-promise-chain.js b/02-async-js/hard (promises)/4-promise-chain.js index 97da4f3c..dd758563 100644 --- a/02-async-js/hard (promises)/4-promise-chain.js +++ b/02-async-js/hard (promises)/4-promise-chain.js @@ -6,17 +6,48 @@ */ 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(); + waitOneSecond().then(result => { + console.log(result); + return waitTwoSecond(); + }). + then(result => { + console.log(result); + return waitThreeSecond(); + }) + .then(result => { + console.log(result); + const endTime = Date.now(); + const totolTime = endTime - startTime; + console.log("Entire operation completed in ${totalTime} milliseconds") + }) + .catch(error => { + console.error(`Error: ${error.message}`); + }); +} -} \ No newline at end of file +calculateTime(); \ No newline at end of file diff --git a/02-async-js/medium/1-file-cleaner.md b/02-async-js/medium/1-file-cleaner.md index 2be6e450..a153fa95 100644 --- a/02-async-js/medium/1-file-cleaner.md +++ b/02-async-js/medium/1-file-cleaner.md @@ -10,4 +10,25 @@ After the program runs, the output should be ``` hello world my name is raman -``` \ No newline at end of file +``` + +const fs = require('fs'); + +function clean(data) { + return data; +} + +function fileWritten(err) { + console.log("done"); +} + +function fileRead(err, data) { + if(err) { + console.log(err); + return; + } + let cleanData = clean(data); + fs.writeFile('/path/to/your/file', 'utf-8', fileWritten); +} + +fs.readFile('a.txt', 'utf-8', fileRead); \ No newline at end of file diff --git a/02-async-js/medium/2-clock.md b/02-async-js/medium/2-clock.md index 4a034c67..f23246d8 100644 --- a/02-async-js/medium/2-clock.md +++ b/02-async-js/medium/2-clock.md @@ -6,3 +6,16 @@ Can you make it so that it updates every second, and shows time in the following - HH:MM::SS (Eg. 13:45:23) - HH:MM::SS AM/PM (Eg 01:45:23 PM) + + function printCurrentTime() { + let currentDate = new Date(); + const answer = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); + console.log(answer); +} + +function printTime() { + console.clear(); + printCurrentTime(); +} + +setInterval(printTime,1000);