From 1f9477746822ceb36f13ed8906708ed984abedf0 Mon Sep 17 00:00:00 2001 From: Shivam Date: Thu, 7 Nov 2024 07:46:23 +0530 Subject: [PATCH 1/2] Completed week-2 assignments in 01-async-js folder --- week-2/01-async-js/easy/counter.js | 22 +++++++++ week-2/01-async-js/easy/output.txt | 1 + week-2/01-async-js/easy/read-file-content.js | 41 ++++++++++++++++ week-2/01-async-js/easy/write-file-content.js | 48 +++++++++++++++++++ .../hard (promises)/1-promisify-setTimeout.js | 17 ++++++- .../hard (promises)/2-sleep-completely.js | 19 ++++++++ .../hard (promises)/3-promise-all.js | 27 +++++++++-- .../hard (promises)/4-promise-chain.js | 26 ++++++++-- week-2/01-async-js/medium/clock.js | 18 +++++++ week-2/01-async-js/medium/file-cleaner.js | 37 ++++++++++++++ week-2/01-async-js/medium/file-cleaner.txt | 1 + 11 files changed, 247 insertions(+), 10 deletions(-) create mode 100644 week-2/01-async-js/easy/counter.js create mode 100644 week-2/01-async-js/easy/output.txt create mode 100644 week-2/01-async-js/easy/read-file-content.js create mode 100644 week-2/01-async-js/easy/write-file-content.js create mode 100644 week-2/01-async-js/medium/clock.js create mode 100644 week-2/01-async-js/medium/file-cleaner.js create mode 100644 week-2/01-async-js/medium/file-cleaner.txt diff --git a/week-2/01-async-js/easy/counter.js b/week-2/01-async-js/easy/counter.js new file mode 100644 index 0000000000..ddf82eadd2 --- /dev/null +++ b/week-2/01-async-js/easy/counter.js @@ -0,0 +1,22 @@ +// ## 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 + +let count = 0; + +function counter(){ + setInterval(() =>{ + count++; + console.log(count); + }, 1000); +} + +function counter(){ + count++; + console.log(count); + + setTimeout(counter, 1000); +} +counter(); + diff --git a/week-2/01-async-js/easy/output.txt b/week-2/01-async-js/easy/output.txt new file mode 100644 index 0000000000..34b2fe2de1 --- /dev/null +++ b/week-2/01-async-js/easy/output.txt @@ -0,0 +1 @@ +wfwvvscsadwqfdqfd \ No newline at end of file diff --git a/week-2/01-async-js/easy/read-file-content.js b/week-2/01-async-js/easy/read-file-content.js new file mode 100644 index 0000000000..3f06be6cc0 --- /dev/null +++ b/week-2/01-async-js/easy/read-file-content.js @@ -0,0 +1,41 @@ +const fs = require ('fs').promises; +const prompt = require('prompt-sync')(); + +async function expensiveOperation(n){ + let res = 0; + for(let i = 0; i< n; i++){ + + res += Math.sqrt(i) * Math.random(); + } + + console.log(`Expensive computation result: ${res}`); +} +async function readFileContent(){ + + const FILE_PATH = "3-read-from-file.md"; + + try{ + const data = await fs.readFile(FILE_PATH, "utf-8"); + console.log("File Content: "); + console.log(data); + } + catch(err){ + console.error("Error Reading the file content: ", err.message); + } + +} + +async function main(){ + + const iterations = prompt('How Many Iterations? '); + console.log(`No of Iterations are , ${iterations}!`); + try{ + await Promise.all([readFileContent(), expensiveOperation(iterations)]); + } + catch(err){ + console.error('Program error:', error.message); + } + +} + +main(); diff --git a/week-2/01-async-js/easy/write-file-content.js b/week-2/01-async-js/easy/write-file-content.js new file mode 100644 index 0000000000..4b2bc8edf9 --- /dev/null +++ b/week-2/01-async-js/easy/write-file-content.js @@ -0,0 +1,48 @@ +const fs = require ('fs').promises; +const prompt = require('prompt-sync')(); + +async function expensiveOperation(n){ + let res = 0; + for(let i = 0; i< n; i++){ + + res += Math.sqrt(i) * Math.random(); + } + + console.log(`Expensive computation result: ${res}`); +} +async function writeFileContent(content){ + + const FILE_PATH = "output.txt"; + + try{ + await fs.writeFile(FILE_PATH, content, "utf-8"); + + console.log("Succesfully wrote to the file"); + + const data = await fs.readFile(FILE_PATH, "utf-8"); + console.log('File Content: '); + console.log(data); + } + catch(err){ + console.error("Error Writing to the file: ", err.message); + } + +} + +async function main() { + const content = prompt('Enter File Content to write to the file: '); + const iterations = parseInt(prompt('How Many Iterations? ')); + + try { + await Promise.all([ + writeFileContent(content), + expensiveOperation(iterations) + ]); + console.log('All operations completed successfully.'); + } catch (err) { + console.error('Program error:', err.message); + } + } + + +main(); diff --git a/week-2/01-async-js/hard (promises)/1-promisify-setTimeout.js b/week-2/01-async-js/hard (promises)/1-promisify-setTimeout.js index 32a99c83fc..07101aaa12 100644 --- a/week-2/01-async-js/hard (promises)/1-promisify-setTimeout.js +++ b/week-2/01-async-js/hard (promises)/1-promisify-setTimeout.js @@ -3,6 +3,21 @@ */ function wait(n) { + + return new Promise((resolve) =>{ + setTimeout(resolve, n * 1000); + }); } -module.exports = wait; + +async function main(){ + console.log('Start'); + + await wait(5); + + console.log('After 5 seconds'); +} + +main(); + +module.exports = wait; \ No newline at end of file diff --git a/week-2/01-async-js/hard (promises)/2-sleep-completely.js b/week-2/01-async-js/hard (promises)/2-sleep-completely.js index a171170b09..ecbbbad8d8 100644 --- a/week-2/01-async-js/hard (promises)/2-sleep-completely.js +++ b/week-2/01-async-js/hard (promises)/2-sleep-completely.js @@ -5,6 +5,25 @@ */ function sleep(milliseconds) { + + return new Promise((resolve) =>{ + // setTimeout(resolve, milliseconds); + // console.log('After resolve'); + + const start = Date.now(); + while(Date.now() - start < milliseconds){ + continue; + } + resolve(); + }) +} + +async function main(n){ + console.log('Before Sleep'); + await sleep(n); + console.log(`After Sleep for ${n} milliseconds`); + } +main(2000); module.exports = sleep; diff --git a/week-2/01-async-js/hard (promises)/3-promise-all.js b/week-2/01-async-js/hard (promises)/3-promise-all.js index a57838ade0..abffd6b073 100644 --- a/week-2/01-async-js/hard (promises)/3-promise-all.js +++ b/week-2/01-async-js/hard (promises)/3-promise-all.js @@ -5,19 +5,36 @@ */ function wait1(t) { - + return new Promise((resolve) =>{ + setTimeout(resolve, t*1000); + }) } function wait2(t) { - + return new Promise((resolve) =>{ + setTimeout(resolve, t*1000); + }) } function wait3(t) { - + return new Promise((resolve) =>{ + setTimeout(resolve, t*1000); + }) } -function calculateTime(t1, t2, t3) { - +async function calculateTime(t1, t2, t3) { + const start = Date.now(); + return Promise.all([ + wait1(t1), + wait2(t2), + wait3(t3) + ]).then(() =>{ + const end = Date.now(); + return end - start; + }); } +calculateTime(1,2,3).then((time)=>{ + console.log(`Time Take: ${time} ms`); +}); module.exports = calculateTime; diff --git a/week-2/01-async-js/hard (promises)/4-promise-chain.js b/week-2/01-async-js/hard (promises)/4-promise-chain.js index 6044e241f7..9d71529733 100644 --- a/week-2/01-async-js/hard (promises)/4-promise-chain.js +++ b/week-2/01-async-js/hard (promises)/4-promise-chain.js @@ -5,20 +5,38 @@ * Compare it with the results from 3-promise-all.js */ -function wait1(t) { +function wait1(t) { + return new Promise((resolve) =>{ + setTimeout(resolve, t*1000); + }) } function wait2(t) { - + return new Promise((resolve) =>{ + setTimeout(resolve, t*1000); + }) } function wait3(t) { - + return new Promise((resolve) =>{ + setTimeout(resolve, t*1000); + }) } function calculateTime(t1, t2, t3) { + const start = Date.now(); + return wait1(t1) + .then(() => wait2(t2) + .then(() =>wait3(t3) + .then(() =>{ + const end = Date.now(); + return end - start; + }))); } - +calculateTime(1,2,3) +.then((time)=>{ + console.log(`Time taken: ${time}`); +}); module.exports = calculateTime; diff --git a/week-2/01-async-js/medium/clock.js b/week-2/01-async-js/medium/clock.js new file mode 100644 index 0000000000..e5e1f9f4ac --- /dev/null +++ b/week-2/01-async-js/medium/clock.js @@ -0,0 +1,18 @@ +function updateClock() { + const now = new Date(); + + // Format for 24-hour time (HH:MM:SS) + const time24 = now.toTimeString().split(' ')[0]; + + // Format for 12-hour time (HH:MM:SS AM/PM) + const time12 = now.toLocaleTimeString('en-US', { + hour12: true, + hour: '2-digit', + minute: '2-digit', + second: '2-digit' + }); + + setTimeout(updateClock, 1000); +} + +updateClock(); diff --git a/week-2/01-async-js/medium/file-cleaner.js b/week-2/01-async-js/medium/file-cleaner.js new file mode 100644 index 0000000000..f8d1bda9d9 --- /dev/null +++ b/week-2/01-async-js/medium/file-cleaner.js @@ -0,0 +1,37 @@ +// ## File cleaner +// Read a file, remove all the extra spaces and write it back to the same file. + +// For example, if the file input was +// ``` +// hello world my name is raman +// ``` + +// After the program runs, the output should be + +// ``` +// hello world my name is raman +// ``` + + +const fs = require('fs').promises; + +const FILE_PATH = 'file-cleaner.txt'; + +async function cleanContent(filepath){ + try{ + const data = await fs.readFile(filepath, 'utf-8'); + const replacedContent = data.replace(/\s+/g, ' ').trim(); + await fs.writeFile(filepath, replacedContent); + + console.log('File Content Has Been Cleaned !!'); + + const newData = await fs.readFile(filepath, 'utf-8'); + console.log('New Content of the File: '); + console.log(newData); + } + catch(err){ + console.error('Error Processing the file: ', err.message); + } +} + +cleanContent(FILE_PATH); \ No newline at end of file diff --git a/week-2/01-async-js/medium/file-cleaner.txt b/week-2/01-async-js/medium/file-cleaner.txt new file mode 100644 index 0000000000..1a2e9e6283 --- /dev/null +++ b/week-2/01-async-js/medium/file-cleaner.txt @@ -0,0 +1 @@ +hello this is a sample text that needs to be cleaned \ No newline at end of file From ede6cc72a57818b9580e83557a4133ae5ea6c1cb Mon Sep 17 00:00:00 2001 From: Shivam Date: Sun, 10 Nov 2024 04:08:32 +0530 Subject: [PATCH 2/2] completed backend for Todolist routes --- week-2/02-nodejs/todoServer.js | 172 +++++++++++++++++++++++---------- 1 file changed, 123 insertions(+), 49 deletions(-) diff --git a/week-2/02-nodejs/todoServer.js b/week-2/02-nodejs/todoServer.js index 4b55de9f9e..d0c459e263 100644 --- a/week-2/02-nodejs/todoServer.js +++ b/week-2/02-nodejs/todoServer.js @@ -1,49 +1,123 @@ -/** - You need to create an express HTTP server in Node.js which will handle the logic of a todo list app. - - Don't use any database, just store all the data in an array to store the todo list data (in-memory) - - Hard todo: Try to save responses in files, so that even if u exit the app and run it again, the data remains (similar to databases) - - Each todo has a title and a description. The title is a string and the description is a string. - Each todo should also get an unique autogenerated id every time it is created - The expected API endpoints are defined below, - 1.GET /todos - Retrieve all todo items - Description: Returns a list of all todo items. - Response: 200 OK with an array of todo items in JSON format. - Example: GET http://localhost:3000/todos - - 2.GET /todos/:id - Retrieve a specific todo item by ID - Description: Returns a specific todo item identified by its ID. - Response: 200 OK with the todo item in JSON format if found, or 404 Not Found if not found. - Example: GET http://localhost:3000/todos/123 - - 3. POST /todos - Create a new todo item - Description: Creates a new todo item. - Request Body: JSON object representing the todo item. - Response: 201 Created with the ID of the created todo item in JSON format. eg: {id: 1} - Example: POST http://localhost:3000/todos - Request Body: { "title": "Buy groceries", "completed": false, description: "I should buy groceries" } - - 4. PUT /todos/:id - Update an existing todo item by ID - Description: Updates an existing todo item identified by its ID. - Request Body: JSON object representing the updated todo item. - Response: 200 OK if the todo item was found and updated, or 404 Not Found if not found. - Example: PUT http://localhost:3000/todos/123 - Request Body: { "title": "Buy groceries", "completed": true } - - 5. DELETE /todos/:id - Delete a todo item by ID - Description: Deletes a todo item identified by its ID. - Response: 200 OK if the todo item was found and deleted, or 404 Not Found if not found. - Example: DELETE http://localhost:3000/todos/123 - - - For any other route not defined in the server return 404 - - 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()); - - module.exports = app; \ No newline at end of file +const express = require('express'); +const fs = require('fs').promises; +const app = express(); +const path = require('path'); +app.use(express.json()); + +const TODOS_FILE_PATH = path.join(__dirname, 'todos.json'); + +async function readTodos() { + try { + const data = await fs.readFile(TODOS_FILE_PATH, 'utf-8'); + return JSON.parse(data); + } catch (err) { + if (err.code === 'ENOENT') { + return []; + } + throw err; + } +} + + +async function writeTodos(todos) { + try { + await fs.writeFile(TODOS_FILE_PATH, JSON.stringify(todos, null, 2)); + } catch (err) { + console.error('Error writing todos:', err); + throw err; + } +} + +app.get("/todos", async function (req, res) { + + todos = await readTodos(); + res.status(200).json(todos) +}); + +app.get("/todos/:id", async function (req, res) { + try { + const todoID = parseInt(req.params.id); + const todos = await readTodos(); + const todo = todos.find(t => t.id === todoID); + + if (!todo) { + return res.status(404).json({ message: `Todo not found for id ${todoID}` }); + } + + res.status(200).json(todo); + } catch (err) { + res.status(500).json({ message: 'Internal server error' }); + } +}); + +app.post('/todos', async function (req, res) { + const todo = req.body; + + if (!todo['title'] || !todo['description']) { + return res.status(400).json({ message: 'Title and description are required' }); + } + + const todos = await readTodos(); + + let maxID = todos.length > 0 ? Math.max(...todos.map(t => t.id)) : 0; + const newTodo = { + id: maxID + 1, + title: todo['title'], + description: todo['description'], + completed: todo['completed'] + }; + todos.push(newTodo); + await writeTodos(todos); + + res.status(201).json({ id: newTodo.id }); + +}); + +app.delete('/todos/:id', async function (req, res) { + const todos = await readTodos(); + const id = parseInt(req.params.id); + const todoIndex = todos.findIndex(t => t.id === id); + + if (todoIndex === -1) { + return res.status(404).json({ message: 'requested id not found' }); + } + + todos.splice(todoIndex, 1); + await writeTodos(todos); + res.status(200).json({ message: 'Todo deleted successfully' }); +}); + +app.put('/todos/:id', async function (req, res) { + const id = parseInt(req.params.id); + const { title, description, completed } = req.body; + const todos = await readTodos(); + const todoIndex = todos.findIndex(t => t.id === id); + + if (todoIndex === -1) { + return res.status(404).json({ message: 'requested id not found' }); + } + + todos[todoIndex] = { + ...todos[todoIndex], + title: title || todos[todoIndex].title, + description: description || todos[todoIndex].description, + completed: completed !== undefined ? completed : todos[todoIndex].completed + }; + + await writeTodos(todos); + res.status(200).json(todos[todoIndex]); +}); + + +const PORT = 3000; + +app.listen(PORT, () => { + console.log(`App listening on port ${PORT}!`); +}); +function startServer(port) { + return app.listen(port, () => { + console.log(`App listening on port ${port}!`); + }); +} + +module.exports = { app, startServer };