Skip to content
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
20 changes: 19 additions & 1 deletion 01-js/easy/anagram.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,27 @@
What's Anagram?
- A word, phrase, or name formed by rearranging the letters of another, such as spar, formed from rasp.
*/

// strings will be anagram if both contains the same number of letters and count of each alphabet should also be same, so that we can arrange the letters and form different strings
function isAnagram(str1, str2) {
if(str1.length !== str2.length) return false;

const count = {};
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
// strings in JS are iterable
// for of loop can be used on iterable
// will be using (for of) to iterate over string

for(let char of str1) {
count[char] = (count[char] || 0) + 1; // handling undefined case using ||
}

for(let char of str2) {
if(!count[char]) return false
count[char]-=1
}

return true
}

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

function calculateTotalSpentByCategory(transactions) {
return [];
if(transactions.length === 0 ){
return [];
}
const result = {};

transactions.forEach(element => {
result[element.category] = {
category: element.category,
totalSpent: result[element.category] ? result[element.category].totalSpent + element.price : element.price
}
})

const answer = [];

for(const [key, value] of Object.entries(result)){
answer.push(value);
}

return answer;
}

module.exports = calculateTotalSpentByCategory;
22 changes: 21 additions & 1 deletion 01-js/easy/findLargestElement.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,27 @@
*/

function findLargestElement(numbers) {

// string, arrays are iterables
// for of is used to iterate over iterables
// for of is used to iterate over arrays and string
if(numbers.length === 0){
return undefined;
}

let maxValue = -Number.MAX_VALUE;
for(let element of numbers) {
if(element > maxValue) {
maxValue = element
}
}

return maxValue;
}

// MAX_Value inside JS can be get using Number.MAX_VALUE (finite positive value)
// MIN_Value inside JS can be get using -NUmber.MAC_VALUE (fintite negative value)

// Number.POSITIVE_INFINITY / INFINITY
// Number.Negative_INFINITY / -INFINITY

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

class Calculator {}
class Calculator {
constructor() {
this.result = 0;
}

calculate(arithmeticString) {
const newStringArray = arithmeticString.split(" "); // all the spaces will be removed from the string will now contain numbers mathematical operations and invalid letters ( throw error in case of these)
// "10 + 2 * ( 6 - (4 + 1) / 2) + 7" -> "10+2*(6-(4+1)/2)+7" -> "10+2*("
let str = '';
newStringArray.forEach(element => {
str += element;
})
}

add(value) {
this.result += value;
}

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

multiply(value) {
this.result *= value
}

divide(value) {
this.result /= value
}

clear() {
this.result = 0
}

getResult() {
return this.result
}

}

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

class Todo {
// class provides us blueprint and we will implement objects from it, all the properties inside the object will be implemented using the constructor
constructor() {
this.allTodos = [];
}

// there are 3 ways to create methods inside teh class using normal function, arrow function and anonyamous function
add(todoName) {
this.allTodos.push(todoName);
}

remove(index) {
if(index >= this.allTodos.length) {
return;
}

const result = [];
for(let i = 0 ; i < this.allTodos.length ; i++) {
if(i === index) {
continue;
}

result.push(this.allTodos[i]);
}

this.allTodos = result;
}

update(index, updateTodo) {
if(index >= this.allTodos.length ) {
return
}

this.allTodos[index] = updateTodo;
}

getAll() {
return this.allTodos
}

get(index) {
if( index < 0 || index >= this.allTodos.length) {
return null; // if the index is invalid or array does not contains elements => return null
}

return this.allTodos[index];
}

clear() {
this.allTodos = []
}
}

module.exports = Todo;
11 changes: 10 additions & 1 deletion 01-js/medium/countVowels.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,16 @@
*/

function countVowels(str) {
// Your code here
// convert the into lowercase format
str = str.toLowerCase();
let result = 0;
for(let char of str) {
if(char === "a" || char === "e" || char === "i" || char === "o" || char === "u"){
result++
}
}

return result;
}

module.exports = countVowels;
41 changes: 40 additions & 1 deletion 01-js/medium/palindrome.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,46 @@
*/

function isPalindrome(str) {
return true;
if(!str.length) {
return true;
}

// ignoring the special characters and only comparing the letters ig
const length = str.length;

str = str.toLowerCase();

let i = 0;
let j = str.length - 1; // pointing to the last element of string

while(i < j) {
const correctAsciiCode1Range = str[i].charCodeAt(0) >= 97 && str[i].charCodeAt(0) <= 122 ? true : false;
const correctAsciiCode2Range = str[j].charCodeAt(0) >= 97 && str[j].charCodeAt(0) <= 122 ? true : false;

if(!correctAsciiCode1Range) {
// not letter => will skip this iteration because we have to compare letters with only letters
i++;
continue
}

if(!correctAsciiCode2Range){
// not letter
j--;
continue
}

if(correctAsciiCode2Range && correctAsciiCode1Range && str[i] !== str[j]) {
return false
}

i++;
j--;

}

// simple way is to keep only the letter from the string and then apply the logic

return true
}

module.exports = isPalindrome;
19 changes: 17 additions & 2 deletions 01-js/medium/times.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,21 @@ Hint - use Date class exposed in JS
There is no automated test for this one, this is more for you to understand time goes up as computation goes up
*/


const beforeCallingFn = new Date().getTime(); // returns number of milliseconds from 1 Jan 1970 00:00:00
function calculateTime(n) {
return 0.01;
}
let answer = 0;

for(let index = 0 ; index <= n ; index++) {
answer += index
}

return answer;
}

calculateTime(1000000);

const afterCallingFn = new Date().getTime();

const totalSeconds = (afterCallingFn - beforeCallingFn) / 1000;
console.log(totalSeconds);
9 changes: 9 additions & 0 deletions week-2/01-async-js/easy/1-counter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// we will be creating counter using setInterval (call a function after every second provided)
let counter = 0;
function counterFn() {
console.log(counter)
counter+=1
}

// setInterval is a global asynchronous function using which we can delegate the task of putting the counterFn in the callbackQueue of the main thread after every 1 second / 1000 millisecond
setInterval(counterFn, 1000);
10 changes: 10 additions & 0 deletions week-2/01-async-js/easy/2-counter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
let counter = 0;

function counterFn() {
console.log(counter);
counter++;

setTimeout(counterFn, 1000);
}

setTimeout(counterFn, 1000);
69 changes: 69 additions & 0 deletions week-2/01-async-js/easy/3-read-from-file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
const fs = require("fs");

// we will be reading file using fs module that provides us readFile method that belongs to the asynchrnous programming - means we will delegate this to the other thread because it is an expensive operation and we does not want our thread to get hung up

// approach 1 directly passing the callback to the readFile which looks ugly and can lead to callback hell
function readData(path, succesCallback, errorCallback) {
if(!path) return "Provide a valid Path!!";

fs.readFile(path,"utf-8", function(err, data) {
if (err) {
errorCallback(err);
return
}

succesCallback(data);
})
}

// directly passing the callbacks
readData("./a.txt", function(err) {
console.log(err);
}, function(result) {
console.log(result);
});

// approach 2 Using Promise (will wrap the asynchronous code inside the Promise class) and providing the callback using .then and .catch syntax

function readDataPromised(path) {
return new Promise(function(resolve, reject) {
fs.readFile(path, "utf-8", function(err, data) {
if(err) {
reject(err);
return
}

resolve(data);
})
})
}


readDataPromised("./a.txt").then(function(data) {
console.log(data);
}).catch(function(err) {
console.log(err);
})


// approach 3 Promise version but instead of using .then and .catch we will be using async await syntax

async function getReadData(path) {
try {
const data = await readDataPromised(path);
// here add the logic of updating the UI or make new function that will update the UI
console.log(data);
return data
} catch(err) {
console.log(err);
throw err;
}
}

getReadData("./a.txt");



// await gets whatever is passed to resolve

// falsy values -> 0, -0, 0n (bright value), undefined, null, "", NaN, false
Loading