From 1f3c96b2bf8a70d1b356c3fd2822e28836adf3d1 Mon Sep 17 00:00:00 2001 From: rohittrana Date: Fri, 24 Jan 2025 15:43:44 +0530 Subject: [PATCH 1/3] 01-js done --- .../01-js/easy/anagram.js | 18 +++++++ .../01-js/easy/expenditure-analysis.js | 19 +++++++- .../01-js/hard/calculator.js | 47 ++++++++++++++++++- .../01-js/hard/todo-list.js | 27 ++++++++++- .../01-js/medium/palindrome.js | 7 ++- .../01-js/medium/times.js | 14 +++++- 6 files changed, 125 insertions(+), 7 deletions(-) diff --git a/week-1/Week-1-assignment-with-tests/01-js/easy/anagram.js b/week-1/Week-1-assignment-with-tests/01-js/easy/anagram.js index fff614278..a779138c8 100644 --- a/week-1/Week-1-assignment-with-tests/01-js/easy/anagram.js +++ b/week-1/Week-1-assignment-with-tests/01-js/easy/anagram.js @@ -8,7 +8,25 @@ */ function isAnagram(str1, str2) { + + + if(str1.length != str2.length){ + return false; + } + + + str1 = str1.toLowerCase(); + str2 = str2.toLowerCase(); + + str1 = str1.split('').sort().join(''); + str2 = str2.split('').sort().join(''); + if(str1 == str2){ + return true; + } + else{ + return false; + } } module.exports = isAnagram; diff --git a/week-1/Week-1-assignment-with-tests/01-js/easy/expenditure-analysis.js b/week-1/Week-1-assignment-with-tests/01-js/easy/expenditure-analysis.js index 20fbb9435..48ede9057 100644 --- a/week-1/Week-1-assignment-with-tests/01-js/easy/expenditure-analysis.js +++ b/week-1/Week-1-assignment-with-tests/01-js/easy/expenditure-analysis.js @@ -9,7 +9,24 @@ */ function calculateTotalSpentByCategory(transactions) { - return []; + var returnElement = []; + + transactions.forEach((traEle) => { + ///go through each and every element in transactions + var elemen = returnElement.find((ele) => (ele.category === traEle.category)); + ///check if that element is present + if (elemen) { + elemen.totalSpent = elemen.totalSpent + traEle.price; + } else { + returnElement.push({ category: traEle.category, totalSpent: traEle.price }); + } + }); + + + + return returnElement; } + + module.exports = calculateTotalSpentByCategory; diff --git a/week-1/Week-1-assignment-with-tests/01-js/hard/calculator.js b/week-1/Week-1-assignment-with-tests/01-js/hard/calculator.js index 82d48229a..ad7e3897b 100644 --- a/week-1/Week-1-assignment-with-tests/01-js/hard/calculator.js +++ b/week-1/Week-1-assignment-with-tests/01-js/hard/calculator.js @@ -17,6 +17,51 @@ - `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 be divided by 0"); + } + + this.result /= number; + } + + clear() { + this.result = 0; + } + + getResult() { + return this.result; + } + + calculate(expression) { + expression = expression.replace(/\s+/g, ""); + + this.result = eval(expression); + + if (isNaN(this.result)) { + throw new Error("Invalid expression"); + } else if (this.result === Infinity) { + throw new Error("Cannot be divided by 0"); + } + } + +} +var calc = new Calculator(); module.exports = Calculator; diff --git a/week-1/Week-1-assignment-with-tests/01-js/hard/todo-list.js b/week-1/Week-1-assignment-with-tests/01-js/hard/todo-list.js index 7c9c18064..92489c009 100644 --- a/week-1/Week-1-assignment-with-tests/01-js/hard/todo-list.js +++ b/week-1/Week-1-assignment-with-tests/01-js/hard/todo-list.js @@ -12,7 +12,32 @@ */ class Todo { - + constructor() { + this.todos = [] + } + add(todo) { + this.todos.push(todo) + } + remove(indexOfTodo) { + this.todos.splice(indexOfTodo, 1) + } + update(indexOfTodo, updatedTodo) { + if (indexOfTodo < this.todos.length) { + this.todos[indexOfTodo] = updatedTodo + } + } + getAll() { + return this.todos + } + get(indexOfTodo) { + if (indexOfTodo >= this.todos.length) { + return null + } + return this.todos[indexOfTodo] + } + clear() { + this.todos.splice(0) + } } module.exports = Todo; diff --git a/week-1/Week-1-assignment-with-tests/01-js/medium/palindrome.js b/week-1/Week-1-assignment-with-tests/01-js/medium/palindrome.js index d8fe2d8f8..79b8ca5af 100644 --- a/week-1/Week-1-assignment-with-tests/01-js/medium/palindrome.js +++ b/week-1/Week-1-assignment-with-tests/01-js/medium/palindrome.js @@ -5,9 +5,12 @@ Once you've implemented the logic, test your code by running - `npm run test-palindrome` */ - +const basic = (str) => String(str).toLowerCase().replace(/[^\w]/g, '') function isPalindrome(str) { - return true; + const str1 = basic(str); + const str2 = basic(str).split('').reverse().join('') + console.log(str1,str2) + return str1 ===str2; } module.exports = isPalindrome; diff --git a/week-1/Week-1-assignment-with-tests/01-js/medium/times.js b/week-1/Week-1-assignment-with-tests/01-js/medium/times.js index eb125cc26..3094554c3 100644 --- a/week-1/Week-1-assignment-with-tests/01-js/medium/times.js +++ b/week-1/Week-1-assignment-with-tests/01-js/medium/times.js @@ -8,5 +8,15 @@ Hint - use Date class exposed in JS */ function calculateTime(n) { - return 0.01; -} \ No newline at end of file + let start = Date.now() + let sum = 0 + for (let i = 1; i <= n; i++) { + sum += i + } + console.log(sum) + let timeTaken = (Date.now() - start) / 1000 + return timeTaken + } + + + console.log(calculateTime(100)) \ No newline at end of file From 89d05bae7fb63b864d8cd9c65f555501b2977c67 Mon Sep 17 00:00:00 2001 From: rohittrana Date: Sat, 25 Jan 2025 19:51:05 +0530 Subject: [PATCH 2/3] done with 02-async-js --- .../02-async-js/easy/1-counter.js | 6 +++ .../02-async-js/easy/1-counter.md | 3 +- .../02-async-js/easy/2-counter.js | 9 ++++ .../02-async-js/easy/3-read-from-file.js | 9 ++++ .../02-async-js/easy/4-write-to-file.js | 21 +++++++++ .../02-async-js/easy/a.txt | 1 + .../hard (promises)/1-promisify-setTimeout.js | 6 ++- .../hard (promises)/2-sleep-completely.js | 14 ++++-- .../hard (promises)/3-promise-all.js | 42 ++++++++++------- .../hard (promises)/4-promise-chain.js | 45 +++++++++++++------ .../02-async-js/medium/1-file-cleaner.js | 25 +++++++++++ .../02-async-js/medium/2-clock.js | 25 +++++++++++ .../02-async-js/medium/a.txt | 0 13 files changed, 172 insertions(+), 34 deletions(-) create mode 100644 week-1/Week-1-assignment-with-tests/02-async-js/easy/1-counter.js create mode 100644 week-1/Week-1-assignment-with-tests/02-async-js/easy/2-counter.js create mode 100644 week-1/Week-1-assignment-with-tests/02-async-js/easy/3-read-from-file.js create mode 100644 week-1/Week-1-assignment-with-tests/02-async-js/easy/4-write-to-file.js create mode 100644 week-1/Week-1-assignment-with-tests/02-async-js/easy/a.txt create mode 100644 week-1/Week-1-assignment-with-tests/02-async-js/medium/1-file-cleaner.js create mode 100644 week-1/Week-1-assignment-with-tests/02-async-js/medium/2-clock.js create mode 100644 week-1/Week-1-assignment-with-tests/02-async-js/medium/a.txt diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/easy/1-counter.js b/week-1/Week-1-assignment-with-tests/02-async-js/easy/1-counter.js new file mode 100644 index 000000000..c526d02cd --- /dev/null +++ b/week-1/Week-1-assignment-with-tests/02-async-js/easy/1-counter.js @@ -0,0 +1,6 @@ +let i = 1; + +setInterval(() => { + console.log(i); + i++; +}, 1000); diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/easy/1-counter.md b/week-1/Week-1-assignment-with-tests/02-async-js/easy/1-counter.md index 54483eabc..164e3b805 100644 --- a/week-1/Week-1-assignment-with-tests/02-async-js/easy/1-counter.md +++ b/week-1/Week-1-assignment-with-tests/02-async-js/easy/1-counter.md @@ -1,4 +1,5 @@ ## 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 + diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/easy/2-counter.js b/week-1/Week-1-assignment-with-tests/02-async-js/easy/2-counter.js new file mode 100644 index 000000000..bd0a9ab6e --- /dev/null +++ b/week-1/Week-1-assignment-with-tests/02-async-js/easy/2-counter.js @@ -0,0 +1,9 @@ +let i = 0; + +function counter() { + console.log(i); + i++; + setTimeout(counter, 1000); +} + +counter(); diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/easy/3-read-from-file.js b/week-1/Week-1-assignment-with-tests/02-async-js/easy/3-read-from-file.js new file mode 100644 index 000000000..a9884e8cb --- /dev/null +++ b/week-1/Week-1-assignment-with-tests/02-async-js/easy/3-read-from-file.js @@ -0,0 +1,9 @@ +const fs = require('fs'); +fs.readFile('a.txt','utf-8',function(err,data){ + if(err){ + console.log(err); + } + else{ + console.log(data); + } +}) \ No newline at end of file diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/easy/4-write-to-file.js b/week-1/Week-1-assignment-with-tests/02-async-js/easy/4-write-to-file.js new file mode 100644 index 000000000..ddb4f1505 --- /dev/null +++ b/week-1/Week-1-assignment-with-tests/02-async-js/easy/4-write-to-file.js @@ -0,0 +1,21 @@ +const fs = require('fs'); + +fs.writeFile('a.txt', 'This is the content written to the file.', 'utf-8', (error) => { + if (error) { + console.error('Error writing to file:', error); + return; + } + console.log('File has been written successfully.'); +}); + +console.log('This will execute before the write callback due to async nature.'); + + +console.log('Starting expensive operation...'); +let sum = 0; +for (let i = 0; i < 1e8; i++) { + sum += i; +} +console.log('Expensive operation completed. Sum:', sum); + +console.log('Code execution continues after write task is initiated.'); diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/easy/a.txt b/week-1/Week-1-assignment-with-tests/02-async-js/easy/a.txt new file mode 100644 index 000000000..a6e25399a --- /dev/null +++ b/week-1/Week-1-assignment-with-tests/02-async-js/easy/a.txt @@ -0,0 +1 @@ +This is the content written to the file. \ No newline at end of file diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/1-promisify-setTimeout.js b/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/1-promisify-setTimeout.js index cc0b7dd72..439463b6c 100644 --- a/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/1-promisify-setTimeout.js +++ b/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/1-promisify-setTimeout.js @@ -3,4 +3,8 @@ */ function wait(n) { -} \ No newline at end of file + return new Promise(resolve => { + setTimeout(resolve, n * 1000); + }); + } + \ No newline at end of file diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/2-sleep-completely.js b/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/2-sleep-completely.js index 499a56478..883f4cec5 100644 --- a/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/2-sleep-completely.js +++ b/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/2-sleep-completely.js @@ -2,7 +2,15 @@ * Write a function that halts the JS thread (make it busy wait) for a given number of milliseconds. * During this time the thread should not be able to do anything else. */ +function sleep(milliseconds) { + const start = Date.now(); + while (Date.now() - start < milliseconds) { + + } + } -function sleep (seconds) { - -} \ No newline at end of file + + console.log("Start"); + sleep(2000); + console.log("End"); + \ No newline at end of file diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/3-promise-all.js b/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/3-promise-all.js index 5028a0095..7abe7bf9b 100644 --- a/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/3-promise-all.js +++ b/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/3-promise-all.js @@ -4,19 +4,31 @@ * Print how long it took for all 3 promises to resolve. */ - function waitOneSecond() { - -} - -function waitTwoSecond() { - -} - -function waitThreeSecond() { - -} - -function calculateTime() { - -} \ No newline at end of file + return new Promise((resolve) => { + setTimeout(resolve, 1000); + }); + } + + function waitTwoSecond() { + return new Promise((resolve) => { + setTimeout(resolve, 2000); + }); + } + + function waitThreeSecond() { + return new Promise((resolve) => { + setTimeout(resolve, 3000); + }); + } + + function calculateTime() { + const start = Date.now(); + Promise.all([waitOneSecond(), waitTwoSecond(), waitThreeSecond()]).then(() => { + const end = Date.now(); + console.log(`Time taken: ${(end - start) / 1000} seconds`); + }); + } + + calculateTime(); + \ No newline at end of file diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/4-promise-chain.js b/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/4-promise-chain.js index 97da4f3c8..c0d1e71cd 100644 --- a/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/4-promise-chain.js +++ b/week-1/Week-1-assignment-with-tests/02-async-js/hard (promises)/4-promise-chain.js @@ -6,17 +6,34 @@ */ function waitOneSecond() { - -} - -function waitTwoSecond() { - -} - -function waitThreeSecond() { - -} - -function calculateTime() { - -} \ No newline at end of file + return new Promise(resolve => { + setTimeout(resolve, 1000); + }); + } + + function waitTwoSecond() { + return new Promise(resolve => { + setTimeout(resolve, 2000); + }); + } + + function waitThreeSecond() { + return new Promise(resolve => { + setTimeout(resolve, 3000); + }); + } + + function calculateTime() { + const start = Date.now(); + + waitOneSecond() + .then(() => waitTwoSecond()) + .then(() => waitThreeSecond()) + .then(() => { + const end = Date.now(); + console.log(`Time taken: ${(end - start) / 1000} seconds`); + }); + } + + calculateTime(); + \ No newline at end of file diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/medium/1-file-cleaner.js b/week-1/Week-1-assignment-with-tests/02-async-js/medium/1-file-cleaner.js new file mode 100644 index 000000000..2bef037fe --- /dev/null +++ b/week-1/Week-1-assignment-with-tests/02-async-js/medium/1-file-cleaner.js @@ -0,0 +1,25 @@ +const fs = require('fs'); + + +function cleanFile(filePath) { + + fs.readFile(filePath, 'utf-8', (err, data) => { + if (err) { + console.error('Error reading the file:', err); + return; + } + + + const cleanedData = data.replace(/\s+/g, ' ').trim(); + + fs.writeFile(filePath, cleanedData, 'utf-8', (err) => { + if (err) { + console.error('Error writing to the file:', err); + return; + } + console.log('File has been cleaned successfully!'); + }); + }); +} + +cleanFile('input.txt'); diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/medium/2-clock.js b/week-1/Week-1-assignment-with-tests/02-async-js/medium/2-clock.js new file mode 100644 index 000000000..17ca4a5af --- /dev/null +++ b/week-1/Week-1-assignment-with-tests/02-async-js/medium/2-clock.js @@ -0,0 +1,25 @@ +function updateTime() { + const now = new Date(); + + + let hours24 = now.getHours(); + let minutes = now.getMinutes(); + let seconds = now.getSeconds(); + + hours24 = hours24 < 10 ? '0' + hours24 : hours24; + minutes = minutes < 10 ? '0' + minutes : minutes; + seconds = seconds < 10 ? '0' + seconds : seconds; + + + let hours12 = hours24 % 12; + hours12 = hours12 === 0 ? 12 : hours12; + const ampm = hours24 >= 12 ? 'PM' : 'AM'; + + let time12hr = `${hours12}:${minutes}:${seconds} ${ampm}`; + + console.log(`24-hour format: ${hours24}:${minutes}:${seconds}`); + console.log(`12-hour format: ${time12hr}`); + } + + setInterval(updateTime, 1000); + \ No newline at end of file diff --git a/week-1/Week-1-assignment-with-tests/02-async-js/medium/a.txt b/week-1/Week-1-assignment-with-tests/02-async-js/medium/a.txt new file mode 100644 index 000000000..e69de29bb From a789b0b110f03fce7ee3ac47cca18b18968e0975 Mon Sep 17 00:00:00 2001 From: rohittrana Date: Sat, 25 Jan 2025 23:13:31 +0530 Subject: [PATCH 3/3] week-2 assignment --- .../02-nodejs/authenticationServer.js | 82 +++++++++++- .../02-nodejs/fileServer.js | 52 +++++++- .../02-nodejs/todoServer.js | 120 +++++++++++++++++- 3 files changed, 236 insertions(+), 18 deletions(-) diff --git a/week-2/Week-2-Assignments/02-nodejs/authenticationServer.js b/week-2/Week-2-Assignments/02-nodejs/authenticationServer.js index c5278b94f..866aae460 100644 --- a/week-2/Week-2-Assignments/02-nodejs/authenticationServer.js +++ b/week-2/Week-2-Assignments/02-nodejs/authenticationServer.js @@ -28,10 +28,78 @@ Testing the server - run `npm run test-authenticationServer` command in terminal */ - -const express = require("express") -const PORT = 3000; -const app = express(); -// write your logic here, DONT WRITE app.listen(3000) when you're running tests, the tests will automatically start the server - -module.exports = app; + const express = require("express") + const PORT = 3000; + const app = express(); + // write your logic here, DONT WRITE app.listen(3000) when you're running tests, the tests will automatically start the server + + var users = []; + + app.use(express.json()); + app.post("/signup", (req, res) => { + var user = req.body; + let userAlreadyExists = false; + for (var i = 0; i { + var user = req.body; + let userFound = null; + for (var i = 0; i { + var email = req.headers.email; + var password = req.headers.password; + let userFound = false; + for (var i = 0; i { + fs.readdir(filesDirectory, (err, files) => { + if (err) { + return res.status(500).json({ error: 'Unable to read files' }); + } + res.status(200).json(files); + }); + }); + + // Endpoint 2: GET /file/:filename - Returns content of the file by name + app.get('/file/:filename', (req, res) => { + const fileName = req.params.filename; + const filePath = path.join(filesDirectory, fileName); + + fs.readFile(filePath, 'utf-8', (err, data) => { + if (err) { + // File not found or any other error + return res.status(404).send('File not found'); + } + res.status(200).send(data); + }); + }); + + // Handle undefined routes - 404 error + app.use((req, res) => { + res.status(404).send('Not Found'); + }); + + // Export the app for testing or further usage + module.exports = app; + + // Run the server on port 3000 + if (require.main === module) { + app.listen(3000, () => { + console.log('Server is running on http://localhost:3000'); + }); + } + module.exports = app; diff --git a/week-2/Week-2-Assignments/02-nodejs/todoServer.js b/week-2/Week-2-Assignments/02-nodejs/todoServer.js index cffc7d600..085771f7d 100644 --- a/week-2/Week-2-Assignments/02-nodejs/todoServer.js +++ b/week-2/Week-2-Assignments/02-nodejs/todoServer.js @@ -39,11 +39,119 @@ Testing the server - run `npm run test-todoServer` command in terminal */ -const express = require('express'); -const bodyParser = require('body-parser'); - -const app = express(); - -app.use(bodyParser.json()); + const express = require('express'); + const bodyParser = require('body-parser'); + const fs = require('fs'); + const path = require('path'); + + const app = express(); + app.use(bodyParser.json()); + + const dataFilePath = path.join(__dirname, 'todos.json'); + + // Load todos from file or initialize an empty array + let todos = []; + if (fs.existsSync(dataFilePath)) { + const data = fs.readFileSync(dataFilePath, 'utf-8'); + todos = JSON.parse(data); + } + + // Save todos to file + const saveTodosToFile = () => { + fs.writeFileSync(dataFilePath, JSON.stringify(todos, null, 2)); + }; + + // Generate unique ID + const generateId = () => { + return todos.length > 0 ? Math.max(...todos.map((todo) => todo.id)) + 1 : 1; + }; + + // 1. GET /todos - Retrieve all todo items + app.get('/todos', (req, res) => { + res.status(200).json(todos); + }); + + // 2. GET /todos/:id - Retrieve a specific todo item by ID + app.get('/todos/:id', (req, res) => { + const id = parseInt(req.params.id, 10); + const todo = todos.find((todo) => todo.id === id); + + if (!todo) { + return res.status(404).send('Todo not found'); + } + + res.status(200).json(todo); + }); + + // 3. POST /todos - Create a new todo item + app.post('/todos', (req, res) => { + const { title, description } = req.body; + + if (!title || !description) { + return res.status(400).send('Title and description are required'); + } + + const newTodo = { + id: generateId(), + title, + description, + completed: false, + }; + + todos.push(newTodo); + saveTodosToFile(); + + res.status(201).json({ id: newTodo.id }); + }); + + // 4. PUT /todos/:id - Update an existing todo item by ID + app.put('/todos/:id', (req, res) => { + const id = parseInt(req.params.id, 10); + const { title, description, completed } = req.body; + + const todo = todos.find((todo) => todo.id === id); + + if (!todo) { + return res.status(404).send('Todo not found'); + } + + if (title) todo.title = title; + if (description) todo.description = description; + if (typeof completed === 'boolean') todo.completed = completed; + + saveTodosToFile(); + res.status(200).send('Todo updated successfully'); + }); + + // 5. DELETE /todos/:id - Delete a todo item by ID + app.delete('/todos/:id', (req, res) => { + const id = parseInt(req.params.id, 10); + const index = todos.findIndex((todo) => todo.id === id); + + if (index === -1) { + return res.status(404).send('Todo not found'); + } + + todos.splice(index, 1); + saveTodosToFile(); + + res.status(200).send('Todo deleted successfully'); + }); + + // Handle undefined routes - 404 error + app.use((req, res) => { + res.status(404).send('Not Found'); + }); + + // Export the app for testing or further usage + module.exports = app; + + // Run the server on port 3000 + if (require.main === module) { + app.listen(3000, () => { + console.log('Server is running on http://localhost:3000'); + }); + } + module.exports = app;