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

Completed week-2 assignments in 01-async-js folder #1154

Open
wants to merge 2 commits into
base: master
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
22 changes: 22 additions & 0 deletions week-2/01-async-js/easy/counter.js
Original file line number Diff line number Diff line change
@@ -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();

1 change: 1 addition & 0 deletions week-2/01-async-js/easy/output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
wfwvvscsadwqfdqfd
41 changes: 41 additions & 0 deletions week-2/01-async-js/easy/read-file-content.js
Original file line number Diff line number Diff line change
@@ -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();
48 changes: 48 additions & 0 deletions week-2/01-async-js/easy/write-file-content.js
Original file line number Diff line number Diff line change
@@ -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();
17 changes: 16 additions & 1 deletion week-2/01-async-js/hard (promises)/1-promisify-setTimeout.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
19 changes: 19 additions & 0 deletions week-2/01-async-js/hard (promises)/2-sleep-completely.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
27 changes: 22 additions & 5 deletions week-2/01-async-js/hard (promises)/3-promise-all.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
26 changes: 22 additions & 4 deletions week-2/01-async-js/hard (promises)/4-promise-chain.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
18 changes: 18 additions & 0 deletions week-2/01-async-js/medium/clock.js
Original file line number Diff line number Diff line change
@@ -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();
37 changes: 37 additions & 0 deletions week-2/01-async-js/medium/file-cleaner.js
Original file line number Diff line number Diff line change
@@ -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);
1 change: 1 addition & 0 deletions week-2/01-async-js/medium/file-cleaner.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
hello this is a sample text that needs to be cleaned
Loading