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

01-js done #277

Open
wants to merge 3 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
18 changes: 18 additions & 0 deletions week-1/Week-1-assignment-with-tests/01-js/easy/anagram.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Original file line number Diff line number Diff line change
Expand Up @@ -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;
47 changes: 46 additions & 1 deletion week-1/Week-1-assignment-with-tests/01-js/hard/calculator.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
27 changes: 26 additions & 1 deletion week-1/Week-1-assignment-with-tests/01-js/hard/todo-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Original file line number Diff line number Diff line change
Expand Up @@ -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;
14 changes: 12 additions & 2 deletions week-1/Week-1-assignment-with-tests/01-js/medium/times.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,15 @@ Hint - use Date class exposed in JS
*/

function calculateTime(n) {
return 0.01;
}
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))
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
let i = 1;

setInterval(() => {
console.log(i);
i++;
}, 1000);
Original file line number Diff line number Diff line change
@@ -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
It should go up as time goes by in intervals of 1 second

Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
let i = 0;

function counter() {
console.log(i);
i++;
setTimeout(counter, 1000);
}

counter();
Original file line number Diff line number Diff line change
@@ -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);
}
})
Original file line number Diff line number Diff line change
@@ -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.');
1 change: 1 addition & 0 deletions week-1/Week-1-assignment-with-tests/02-async-js/easy/a.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
This is the content written to the file.
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,8 @@
*/

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

Original file line number Diff line number Diff line change
Expand Up @@ -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) {

}

console.log("Start");
sleep(2000);
console.log("End");

Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,31 @@
* Print how long it took for all 3 promises to resolve.
*/


function waitOneSecond() {

}

function waitTwoSecond() {

}

function waitThreeSecond() {

}

function calculateTime() {

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

Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,34 @@
*/

function waitOneSecond() {

}

function waitTwoSecond() {

}

function waitThreeSecond() {

}

function calculateTime() {

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

Original file line number Diff line number Diff line change
@@ -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');
Loading