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 2 Async Assignments Completed #55

Open
wants to merge 16 commits into
base: main
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: 7 additions & 1 deletion week-1/problems/0-horizontal-align/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,20 @@
<title>Horizontal Align</title>
<style>
.container {
display: flex;
justify-content: center;
width: 1200px;
/* margin: 0px auto; */
margin: 0px auto;
background-color: red;
}

.content {
height: 500px;
}

h1{
margin: 0px;
}
</style>
</head>

Expand Down
6 changes: 6 additions & 0 deletions week-2/week-2-async-js/easy/1-counter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
let counter = 0;

setInterval(() => {
counter += 1;
console.log(counter);
}, 1000);
9 changes: 9 additions & 0 deletions week-2/week-2-async-js/easy/2-counter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
let count = 0;

function addCount(){
count = count + 1;
console.log(count);
setTimeout( addCount , 1000);
}

addCount();
7 changes: 7 additions & 0 deletions week-2/week-2-async-js/easy/3-readfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const fs = require("fs")

fs.readFile('./a.txt', 'utf-8', (err, data) => {
console.log(data);
});

for(i = 1; i < 1000000000; i++){}
12 changes: 12 additions & 0 deletions week-2/week-2-async-js/easy/4-writefile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const fs = require("fs")

const readFile = fs.readFileSync('./a.txt', 'utf-8')
console.log("File contents before writing ", readFile );

fs.writeFile('./a.txt', 'Hello Orca', (err) => {
if(err) throw new err;
console.log("File has been saved \n");

const afterWrite = fs.readFileSync('./a.txt', 'utf-8');
console.log(afterWrite);
});
1 change: 1 addition & 0 deletions week-2/week-2-async-js/easy/a.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello Orca
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
*/

function wait(n) {
const p = new Promise((resolve) => {
setTimeout(resolve, n * 1000);
});

return p
}

module.exports = wait;
module.exports = wait
5 changes: 5 additions & 0 deletions week-2/week-2-async-js/hard (promises)/2-sleep-completely.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
*/

function sleep(milliseconds) {
return new Promise((resolve) => {
let startTime = new Date().getTime();
while (new Date().getTime() < startTime + milliseconds);
resolve();
});
}

module.exports = sleep;
20 changes: 16 additions & 4 deletions week-2/week-2-async-js/hard (promises)/3-promise-all.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,30 @@
*/

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();

await Promise.all([wait1(t1), wait2(t2), wait3(t3)])

const end = Date.now();
return end - start;

}

Expand Down
23 changes: 19 additions & 4 deletions week-2/week-2-async-js/hard (promises)/4-promise-chain.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,34 @@
*/

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 = new Date();
await wait1(t1);
console.log(t1, " seconds have passed");
await wait2(t2);
console.log(t2, " seconds have passed");
await wait3(t3);
console.log(t3, " seconds have passed");

const end = new Date();

return end - start;
}

const t1 = 1;
const t2 = 2;
const t3 = 3;

calculateTime(t1, t2, t3);
module.exports = calculateTime;
19 changes: 19 additions & 0 deletions week-2/week-2-async-js/medium/clock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
function currentTime(){
const now = new Date();

const hr = now.getHours();
const mins = now.getMinutes().toString().padStart(2, '0');
const secs = now.getSeconds().toString().padStart(2, '0');

const ampm = hr >= 12 ? 'PM' : 'AM';
const ampmhr = (hr - 12).toString()
const hr12 = ampmhr+":"+mins+":"+secs+" "+ampm;
const hr24 = hr+":"+mins+":"+secs;

console.log(hr12);
console.log(hr24, "\n");

setTimeout(currentTime, 1000);
}

currentTime();
23 changes: 23 additions & 0 deletions week-2/week-2-async-js/medium/prob1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
The regular expression `/\s+/g` is used to match sequences of one or more whitespace characters in a string. Let’s break down its components:

- `/.../`: Delimiters for the regular expression in many programming languages like JavaScript.
- `\s`: A shorthand character class that matches any whitespace character (spaces, tabs, line breaks, etc.).
- `+`: A quantifier that means "one or more" of the preceding element. So, `\s+` matches one or more whitespace characters.
- `g`: A flag that stands for "global," meaning the pattern will be applied to the entire string, not just the first occurrence.

In summary, `/\s+/g` finds all sequences of whitespace characters in a string. For example, if you have the string `"Hello world! How are you?"`, using this regex would match `" "` (multiple spaces) and `" "` (two spaces), and you could use it to replace all such sequences with a single space or another character of your choice.
*/


const fs = require("fs")

fs.readFile('./prob1.txt', 'utf-8', (err, data) => {
console.log("data before: ", data);
const words = data.replace(/\s+/g, ' ').trim();
console.log(words);

fs.writeFile('./prob1.txt', words, (err) => {
console.log("Done!");
})
})
1 change: 1 addition & 0 deletions week-2/week-2-async-js/medium/prob1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello I am Raju
11 changes: 11 additions & 0 deletions week-2/week-2-js/easy/anagram.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,17 @@

function isAnagram(str1, str2) {

if(str1.length == str2.length){

let arr1 = str1.toLowerCase().split('').sort().join();
let arr2 = str2.toLowerCase().split('').sort().join();

return(arr1 === arr2);
}

return false;
}

console.log(isAnagram('spar', 'rasp'));

module.exports = isAnagram;
21 changes: 20 additions & 1 deletion week-2/week-2-js/easy/expenditure-analysis.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,26 @@
*/

function calculateTotalSpentByCategory(transactions) {
return [];

let output = [];

for(i = 0; i < transactions.length; i++){

const isIndex = output.findIndex(domain => domain.category === transactions[i].category)

if(isIndex != -1){
output[isIndex].totalSpent += transactions[i].price;
}
else{
output.push({
category: transactions[i].category,
totalSpent: transactions[i].price
})
}
}

return output;
}


module.exports = calculateTotalSpentByCategory;
15 changes: 14 additions & 1 deletion week-2/week-2-js/easy/findLargestElement.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,20 @@
*/

function findLargestElement(numbers) {

const size = numbers.length;
if(size <= 0) return;

var maxValue = Number.MIN_SAFE_INTEGER;

for(i = 0; i < size; i++){
if(numbers[i] > maxValue){
maxValue = numbers[i];
}
}

return maxValue;
}

console.log(findLargestElement([3, 7, 2, 9, 1]));

module.exports = findLargestElement;
57 changes: 56 additions & 1 deletion week-2/week-2-js/hard/calculator.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,61 @@
Once you've implemented the logic, test your code by running
*/

class Calculator {}
class Calculator {

constructor(){
this.result = 0;
}

add(num){
this.result = this.result + num;

}

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

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

divide(num){
if(num == 0){
throw new Error("Numbers cannot be divided by zero")
}
this.result = this.result / num;
}

clear(){
this.result = 0;
}

getResult(){
return this.result;
}

calculate(inputExpression){
const temp = inputExpression;
const cleanedExpression = temp.replace('/\s+/g', ' ');
const isNotExpression = /^[0-9+\-*/().]+$/.test(cleanedExpression);

if (isNotExpression) {
throw new Error("Invalid expression");
}

try {
this.result = eval(inputExpression);
} catch (error) {
throw new Error("Invalid expression.");
}

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

return this.result;
}
}

module.exports = Calculator;
35 changes: 35 additions & 0 deletions week-2/week-2-js/hard/todo-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,42 @@
*/

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];
}
else{
return null;
}
}

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

module.exports = Todo;
Loading