From 9d9a7efd4a99cc02a1e3e5572121906552f60be0 Mon Sep 17 00:00:00 2001 From: ankittttss Date: Fri, 10 May 2024 12:39:26 +0530 Subject: [PATCH 1/2] Javascript Practice --- Day1/Day1.js | 207 ++++++++++++++++++++++ Day1/Practiceday1.js | 179 +++++++++++++++++++ Day1/Task1.js | 50 ++++++ Day1/Task2.js | 29 +++ Day1/sample.js | 40 +++++ Day2/function.js | 26 +++ Day2/index.js | 56 ++++++ Day3/Closure.js | 12 ++ Day4/Array.js | 152 ++++++++++++++++ Day4/Object.js | 33 ++++ Task/Task1880.js | 46 +++++ Task/Task1887.js | 29 +++ Task/Task1888.js | 51 ++++++ Task/Task1889.js | 64 +++++++ Task/Task1891.js | 20 +++ Task/Task1892.js | 0 Task/Task1893and1890.js | 100 +++++++++++ Task/Task6625.js | 38 ++++ Task/Task6626.js | 0 node_modules/.package-lock.json | 35 ++++ node_modules/ansi-regex/index.js | 14 ++ node_modules/ansi-regex/license | 9 + node_modules/ansi-regex/package.json | 53 ++++++ node_modules/ansi-regex/readme.md | 87 +++++++++ node_modules/prompt-sync/LICENSE | 21 +++ node_modules/prompt-sync/README.md | 118 +++++++++++++ node_modules/prompt-sync/index.js | 243 ++++++++++++++++++++++++++ node_modules/prompt-sync/package.json | 40 +++++ node_modules/prompt-sync/test.js | 38 ++++ node_modules/strip-ansi/index.d.ts | 15 ++ node_modules/strip-ansi/index.js | 7 + node_modules/strip-ansi/license | 9 + node_modules/strip-ansi/package.json | 54 ++++++ node_modules/strip-ansi/readme.md | 61 +++++++ package-lock.json | 43 +++++ package.json | 14 ++ 36 files changed, 1993 insertions(+) create mode 100644 Day1/Day1.js create mode 100644 Day1/Practiceday1.js create mode 100644 Day1/Task1.js create mode 100644 Day1/Task2.js create mode 100644 Day1/sample.js create mode 100644 Day2/function.js create mode 100644 Day2/index.js create mode 100644 Day3/Closure.js create mode 100644 Day4/Array.js create mode 100644 Day4/Object.js create mode 100644 Task/Task1880.js create mode 100644 Task/Task1887.js create mode 100644 Task/Task1888.js create mode 100644 Task/Task1889.js create mode 100644 Task/Task1891.js create mode 100644 Task/Task1892.js create mode 100644 Task/Task1893and1890.js create mode 100644 Task/Task6625.js create mode 100644 Task/Task6626.js create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/ansi-regex/index.js create mode 100644 node_modules/ansi-regex/license create mode 100644 node_modules/ansi-regex/package.json create mode 100644 node_modules/ansi-regex/readme.md create mode 100644 node_modules/prompt-sync/LICENSE create mode 100644 node_modules/prompt-sync/README.md create mode 100644 node_modules/prompt-sync/index.js create mode 100644 node_modules/prompt-sync/package.json create mode 100644 node_modules/prompt-sync/test.js create mode 100644 node_modules/strip-ansi/index.d.ts create mode 100644 node_modules/strip-ansi/index.js create mode 100644 node_modules/strip-ansi/license create mode 100644 node_modules/strip-ansi/package.json create mode 100644 node_modules/strip-ansi/readme.md create mode 100644 package-lock.json create mode 100644 package.json diff --git a/Day1/Day1.js b/Day1/Day1.js new file mode 100644 index 0000000..8dfdf8b --- /dev/null +++ b/Day1/Day1.js @@ -0,0 +1,207 @@ +// Javascript use let,const and Var Keyword to store the data// + +// What is a Variable -: A variable is a container for a value, like a number we +// might use in a sum, or a string that we might use as part of a sentence. + + +// Try to prefer Let over var. Var was declared back and let is a new keyword // +// Var supports Hoisting but let don't// + +// Secondly, when you use var, you can declare the same variable as many times as you like, but with let you can't + +let x = 6 // Assigning the variables// +console.log(x); + +const y = 10; +// We Can't override this Value// + +//------------------------------------------------------------------------------------------------------------ + +// DataTypes in Javascript +// a)String b) Number c)BigInt d)Boolean e)Undefined f)Null g)Symbol h)Object + +let car1name = "Volvo"; +let car2name = "Chevrolet"; + +// String Datatype// + +let i = 20.00; +let number2 = 50; + +// Number Dataype; +//Stored in 64 Bit// +let xx = BigInt("123456789012345678901234567890"); + +//Primitive Data Type +//A primitive type has a fixed size in memory. For example, a number occupies eight bytes of memory, and a boolean value can be represented with only one bit. +//The number type is the largest of the primitive types. +// If each JavaScript variable reserves eight bytes of memory, the variable can directly hold any primitive value + +//Reference types are another matter, however. Objects, for example, can be of any length -- they do not have a fixed size. +//The same is true of arrays: an array can have any number of elements. Similarly, a function can contain any amount of JavaScript code. Since these types do not have a fixed size, their values cannot be stored directly in the eight bytes of memory associated with each variable. +//Instead, the variable stores a reference to the value. +//Typically, this reference is some form of pointer or memory address. +//It is not the data value itself, but it tells the variable where to look to find the value. + + +//Undefined and Null + +//Undefined-: When a variable is innitialise but no value assigned then it directlu takes undefined as its value +//Accessing it's Value will give you undefined as it's out put// +//It's primitive Value// + +//Example + +let xu; +console.log(xu); + +function hey(){ + // No return statement so the default value is Undefined +} + +//NULL + +//Deliberate assignment that represent the absense of any object Value +//It is also a primitive Value + +//Var -: Global and Local Scope, +//Local Scope -: while local scope is for variables declared inside functions. + +var num = 40; +function f(){ + var square = number*number; // Local Scope -: Declared Inside Functions// + console.log(square); // We can access it inside the Function +} + +f(); +//--------------------------------------------------------------------------------------- + +//Another Function to understand the Var and their Scope + +function ff(){ + var number = 40; + var square = number*number; + console.log(square); +} + +ff(); + +console.log(number) // Reference error as number have local scope -: Reference Error +//Variable with var keyword can be redclared and reassigned +//if any value is not assigned to the var variable the the default value it contains is undefined + + + + + + + + + + + + +//------------------------------------------------------------------------------------------------------- +//Arithmetic Operators -: +,-,*,/,%,**,++,-- +//Additional Operators +let numbr1 = 1; +let num2 = 4; +console.log(numbr1+num2); + +//subtraction Operator + +let yu = 10; +let uy = 50; +console.log(uy-yu); + +//Multiplying operator + +let initial1 = 0; +let initial2 = 0; +console.log(0*0); + +//Division Operator + +let div1 = 10; +let div2 = 2; +console.log(div1/div2); + +//Remainder Operator -: We will use modulus here + +let gh = 10; +let hg = 2; +console.log(gh%hg); + +// ** operator is called exponential and ** == Math.pow()// + +//Assignment Operator + +//a) = +//b) += +//c) -= +//d) *= +//e) /= +//f) %= +//g) **= + + +// Shift Assignment Operator +//a) <<= +//b) >>= +//c) >>>= + + +//Bitwise Assignment Operator +//a) &= +//b) ^= +//c) |= + +//Logical Assignment Operator +//a) &&= +//b) ||= +//c) ??= + + +//Example + +let answer = 10; // Simple Assignment Operator + +let answer2 = 0; //Addition Assignment Operator +answer2+=10; + +let answer3 = 10; //Subtraction Assignment Operator +answer3-=5; + +let answer4 = 19; // Multiplication assignment Operator// +answer4*=12; + +let answer5 = 10; // Exponentian Assignment Operator// +answer5**=5; + +let answer6 = 14; // Division Assignment Operator +answer4/=7 + +let answer7 = 19; // Modulo Assignment Operator// +answer7%=8; + +let answer8 = 100; // Left Shift Assignment Operator +answer8<<=5; + +let answer9 = 90; // Right Shift Assignment Operator// +answer9>>=8; + + +//------------------------------------------------------------------------------ + +//Comparison Operator + +//a) == equal to +//b) === equal value and equal Type +//c) !=not equal +//d) !== not equal or not equal Type +//e) > greater than +//f) < less than +//g) >= greater than equal to +//h) <= less than equal to + + diff --git a/Day1/Practiceday1.js b/Day1/Practiceday1.js new file mode 100644 index 0000000..e4254cf --- /dev/null +++ b/Day1/Practiceday1.js @@ -0,0 +1,179 @@ +const prompt = require('prompt-sync')(); +var x; // Genral way to define a Variable in Javascript// +var y; + +var x = 10; // Defining some value to variable called x; + +// To print or to get an output we use Console.log + +console.log(x); // printing the value of x// + +// Let,use and Const are the keywords. + +let var1 = 10; +var var2 = 20; +const var3 = 30; + +//-------------------------------------------------------------------------------- + + +//Primitive Data Type + +//Number Data Type + +let number1 = 10; +let number2 = 20; +let number3 = 4.5 // Floating Point Number. + +//String + +let string1 = "Ankit"; +let string2 = 'Saini'; +console.log(string1,"This is a String"); +console.log(string2,'Printing a string'); + +//String using Backticks// + +let string3 = `Hey there ${string1} how are you`; +console.log(string3); + +// Boolean -: return 1 or 0 based on the condiiton + +// const user1= prompt("Enter the Number"); + +// if(user1 >= 10){ +// console.log("True"); +// return true; +// } + +// else{ +// console.log("False"); +// return false; +// } + +//null - It basically means it is empty whereas undefined means it is not assigned// +//Big Int// +//Big int is a built in object in Javascript that provides a way to represent whole number greater than 253-1// + + +let bigbin = BigInt("0b1010101001010101001111111111111111"); +// console.log(bigbin); + +//------------------------------------------------------------------------- + +//Object is a Reference data type + +// JavaScript objects are fundamental data structures used to store collections of data. +// They consist of key-value pairs and can be created using curly braces {} or the new keyword + +//----------------------------------------------------------------------------------------- +//Understanding Var keyword -: +var variable1 = 10; +function f(){ + var variable2 = 95; + console.log(variable2,variable1); +} +f(); +// console.log(variable2); +var variable1 = 20; +console.log(yu); // Hoisting concept// +var yu = 20; +//---------------------------------------------------------------------------------------------- +//Let Keyword -: Introduced in 2016 and an improved Version of Var keyword// +//Let Keyword has the Block Scope// +// Re declaration is Allowed// + +let let1 = 10; //Global Scope// +function g(){ // Function Scope// + let2 = 11; + console.log(let1); // Can be accessed because let1 has Global Scope// + console.log(let2); +} +g(); + + +let func1 = 10; +function test2(){ + let temp1 = 20; + if(temp1>=20){ + let temp2 = 90; + } + console.log(temp2); // Reference error can't be accessed// +} + + +console.log(temp3); +let temp3 = 20; // Hoisting error// + + +// Const keyword -: Mainly used for those variables that will be constant throughout the process// +// Block Scope and const keyword can't be declared and reassign// + +const a = 10; +function f(){ + a = 9; // Can't be assigned// + console.log(a); +} +f(); + + +// Assignment Operators +//assign value + +let assign1 = 10; // Here = operator is used to assign the values// +assign1+=10// Addition assignment Operator// +assign1-=10;//Subtraction Assignment Operator// +assign1*=10;//Multiplication Assignment Operator// +assign1/=24;//Division Assignment Operator// +assign1**=2;//Exponentian Assignment Operator It's similar to Math.pow(a,b)// + + +// Shift Assignment Operator// +let variable6 = 24; +variable6>>=2;// Right Shift Assignment Operator// +variable6<<=2;//Left Shift Assignment Operator// + +//Bitwise Assignment Operator// + +variable6&=2;//And Operation// +variable6 |=4; // Or Operation +variable6^=4;//Bitwise Operation// +//---------------------------------------------------------------------------------------------------------- + +//Comparison Operators + +let variablee = 10; +let variablee2 = 20; + +if(variablee == variablee2){ // It will only evaluate value not type as it is not considering strictly equality + console.log("equal"); +} +else{ + console.log("Not equal"); +} + + +if(variablee === variablee2){ // Checking the type also// + console.log(""); +} +else{ + console.log("") +} + +if(variablee > variablee2){ + console.log("Variablee is greater than variablee2"); +} + +else if(variablee2 > variablee){ + console.log("Variablee2 is greater than variablee"); +} + + +//----------------------------------------------------------------------------------- + +//Logical Operators +//&&, ||, ! +// && -: This operator name is AND and it specify that if both of the +//value are correct then the statement will be executed +//|| -: Determines that if any of the condition is true then the statement will executed +// \ No newline at end of file diff --git a/Day1/Task1.js b/Day1/Task1.js new file mode 100644 index 0000000..96e6cb4 --- /dev/null +++ b/Day1/Task1.js @@ -0,0 +1,50 @@ +//Task -1893 && 1880// +const prompt = require('prompt-sync')(); // For The Input Line by default Input is String we will typecast It// +const calculator = (number1, number2, operation)=>{ + if (operation === "+") { // These are the cases that we use in Calculator// + return Number(number1) + Number(number2); + } else if(operation === '-') { // Subtraction + return Number(number1) - Number(number2); + } else if (operation === '*') { // Multiplication + return Number(number1) * Number(number2); + } else if (operation === '/') { // Division + return Number(number1) / Number(number2); + } else { + console.log("Invalid operation."); + } +} + +function perform(calculator,...args){ // To Validate the length. Here args.length give us the no of Argument we have passed + if(calculator.length!=args.length){ + return "The length is no suitable"; // Suupose the length is not equal then we will throw an error + } + + return calculator(...args); // if the length is equal then we will calculate the output using the calculator fn +} + + + + +const converttocelsius = (temperature) => { // *F to Celsius + return Number(temperature)*(9/5) + 32; +} + +const converttofahereinheit = (temperature)=>{ // Celsius to Fahrenheit + return (Number(temperature) - 32)*(5/9); +} + +const calculateareaoftriangle = (base,height)=>{ // To Calculate the area of Triangle// + return 1/2*Number(base)*Number(height); +} + + + +const x = prompt("Please Enter the Number1"); // Taking Input from Prompt/,number1/ +const y = prompt("Please enter the Number2"); // Taking Input from Prompt,numbr2// +let z = prompt("Enter the operation you want to Perform"); // Taking Input from Prompt,Operation// + + +console.log(perform(calculator,x,y,z,7)); +console.log(perform(converttocelsius,45)); +console.log(perform(converttofahereinheit,45)); +console.log(perform(calculateareaoftriangle,4,8)); diff --git a/Day1/Task2.js b/Day1/Task2.js new file mode 100644 index 0000000..891412c --- /dev/null +++ b/Day1/Task2.js @@ -0,0 +1,29 @@ +//Task 1891// +const calculator = (expression,...arguments) =>{ + let sum = 0; + if(String(expression) == "+"){ + for(const arg of arguments){ + sum = sum + arg; + } + return sum; + } + + else if(String(expression) == "-"){ + let subtract = 0; + for(const arg of arguments){ + subtract = subtract - arg; + } + return subtract; + } + + else if(String(expression) == "*"){ + let multiplication = 1; + for(const arg of arguments){ + multiplication = multiplication*arg; + } + return multiplication; + } +} + +let finalanswer = calculator("*",1,2,3,4,5,); +console.log(finalanswer); \ No newline at end of file diff --git a/Day1/sample.js b/Day1/sample.js new file mode 100644 index 0000000..71f710f --- /dev/null +++ b/Day1/sample.js @@ -0,0 +1,40 @@ +// Calculator function +const calculator = (func, ...args) => { + // Verify and validate the number of arguments allowed + const expectedArgs = func.length; // Number of expected arguments for the provided function + if (args.length !== expectedArgs) { + throw new Error(`Expected ${expectedArgs} arguments, got ${args.length}`); + } + + // Execute the provided function with the given arguments + return func(...args); + }; + + // Test functions + const add = (a, b) => a + b; + const subtract = (a, b) => a - b; + const multiply = (a, b) => a * b; + const divide = (a, b) => a / b; + + const celsiusToFahrenheit = celsius => (celsius * 9/5) + 32; + const fahrenheitToCelsius = fahrenheit => (fahrenheit - 32) * 5/9; + + const square = x => x * x; + const circleArea = radius => Math.PI * radius * radius; + + // Tests + try { + console.log(calculator(add, 5, 3)); // Output: 8 + console.log(calculator(subtract, 10, 4)); // Output: 6 + // console.log(calculator(multiply, 2, 6)); // Output: 12 + // console.log(calculator(divide, 20, 4)); // Output: 5 + + // console.log(calculator(celsiusToFahrenheit, 0)); // Output: 32 + // console.log(calculator(fahrenheitToCelsius, 32)); // Output: 0 + + // console.log(calculator(square, 4)); // Output: 16 + // console.log(calculator(circleArea, 5)); // Output: ~78.54 + } catch (error) { + console.error(error.message); + } + \ No newline at end of file diff --git a/Day2/function.js b/Day2/function.js new file mode 100644 index 0000000..f9415ff --- /dev/null +++ b/Day2/function.js @@ -0,0 +1,26 @@ +//We will learn about the functions +//JS Function -: JavaScript function is a set of statements that take inputs, +// do some specific computation, and produce output. + +//Basic JS Function// + +function multiply(a,b){ + return a*b; +} + +console.log(multiply(2,3)); + +//Function Expression// +// It is similar to a function declaration without the function name. +// Function expressions can be stored in a variable assignment. + +let x = function um(a,b){ + return a+b; +} + +//Arrow Function -: It is one of the most used and efficient methods +//to create a function in JavaScript because of its comparatively easy implementation. + +const dividing = (a,b)=>{ // a,b are parameters + return a/b; // Return Values // +} \ No newline at end of file diff --git a/Day2/index.js b/Day2/index.js new file mode 100644 index 0000000..ba79420 --- /dev/null +++ b/Day2/index.js @@ -0,0 +1,56 @@ +// Conditional Statements -: if else if// +//if statement -: + +let x = 10; +let y = 20; + +if(x>=y){ + console.log("Yes X is bigger"); +} +else{ + console.log("X is the smaller one"); +} + + +//If else If statement// + +if(x==y){ + console.log("Both are equal"); +} +else if(x>y){ + console.log("x is greatest"); +} + +else{ + console.log("y is greatest"); +} + + +//Logical Operator and their use in conditional Statement + +if(x==1 && y==1){ + console.log("") +} + +else{ + console.log(""); +} +//------------------------------------------------------------------------------------------ +//The JS loop provide concise way of Writing the loop structure +for(let i=0;i<=10;i++){ + console.log(i); +} + +// There are different loop also such as do do while , while and for each loop// +//for in loop -: used to iterate over the properties of an object + +//for-in loop-: +//loop used to iterate over the properties of an object + +let myobj = {x:1,y:2}; +for(let key in myobj){ + console.log(key,myobj[key]); +} + +//for off loop +//used to iterate over the iterable object// \ No newline at end of file diff --git a/Day3/Closure.js b/Day3/Closure.js new file mode 100644 index 0000000..06ac431 --- /dev/null +++ b/Day3/Closure.js @@ -0,0 +1,12 @@ +function makeFunc() { + const name = "Mozilla"; + function displayName() { + console.log(name); + } + return displayName; + } + + const myFunc = makeFunc(); + console.log(myFunc) // It will be a function// + myFunc(); // Calling of tha function// + \ No newline at end of file diff --git a/Day4/Array.js b/Day4/Array.js new file mode 100644 index 0000000..fc56568 --- /dev/null +++ b/Day4/Array.js @@ -0,0 +1,152 @@ +// const arr = [4,5,6,7]; +// arr.pop(); + +// console.log(arr); +// console.log(arr.length); + +// function f(value,index,array){ +// console.log(value); +// } + +// arr.forEach(f); +// let x = arr.join(); +// console.log(x); + +// const arr2 = [1,2,3,4]; +// arr.concat(arr2); +// console.log(arr2); + +// arr.push(89); + +// const temp = [1,2,3,4,5,6,7,8] + +// function check(value,index,array){ +// return value>3 +// } + +// const required = temp.some(check); +// console.log(required); + + +// //---------------------------------------------------------------------------- +// //Map Method +// const aarr = [1,2,3,4,5,6]; +// const newarrr = aarr.map(item=>item*2); +// console.log(newarrr); + +// //---------------------------------------------------------------------------- + +// //Filter Method + +// const a = [2,3,4,5,6,7]; +// const even = a.filter(item=>item%2==0); +// console.log(even); +// const odd = a.filter(item=>item%2!=0); +// console.log(odd); + +// //---------------------------------------------------------------------------- + +// //Map Method// + +// const sum = [1,2,3,4,5]; +// const anss = sum.reduce((x,y)=>x+y); +// console.log(anss); +//----------------------------------------------------------------------------- + + +// Array Properties------------------------------------------------ +// at method -: + +// const fruits = ['banana','lemon','kiwi']; +// console.log(fruits.at(2)); // 0,1,2 -: 0 based Indexing// + + +// //Concat Method --: Join Two Arrays.// + +// const fruit1 = ["kiwi","Lemon","Apple"]; +// const fruit2 = ["Dragonfruit","Mango"]; +// const children = fruit1.concat(fruit2); +// console.log(children); + +// //every -: Executes a Function for each array element, return true or false// + +// const ages = [20,2,3,4,4,5]; + +// function checkage(age){ +// return age>18 +// } +// const answer = ages.every(checkage); +// console.log(answer); + +// //fill -: Fill the array with the static element// +// const cars = ["Maruti","Lamborghini","Thar"]; +// cars.fill("Harley"); +// console.log(cars); + +// //Filter -: Filter the array with a specified condition. + +// function checkage(age){ +// return age>19; +// } + +// const age = [23,45,67,9,0]; +// const remaining = age.filter(checkage); +// console.log(remaining); + + +//Find and FindlastIndex -: Return the value for the first element that passes a test. + +// function checkage(age){ +// return age>199; +// } + +// const index = [23,90,12,34]; +// // const answerrr = index.find(checkage) +// // console.log(answerrr); + +// const temp = index.findLastIndex(checkage) +// console.log(temp); +// // + + +//For Each -: + +// function find(item,index,arr){ +// arr[index] = item*2; +// } + +// const squareofno = [9,3,4,5,]; + +// const numbers = [65, 44, 12, 4]; +// numbers.forEach(myFunction) +// squareofno.forEach(find) + +// function myFunction(item, index, arr) { +// arr[index] = item * 10; +// } +// console.log(numbers); +// console.log(squareofno); + + +// From method -: Returns an arrya from method object// + +// Includes -: find if the element is present// + +// const text = ["Hi"s,"Hello","How are you","Texting"] +// console.log(text.includes("Hi")); +// + +// isArray() -: Return if an object is an array +// const company = ["Microsoft","Apple","Cognizant"]; +// console.log(Array.isArray(company)); + + +//Join -: Return an array as string// + +const animals = ["monkey","tiger","Lion"]; +let result = animals.join("and"); +console.log(result); + +const no = [1,3,4,4,2]; +const arr = no.map(item=>item*2); +console.log(arr); \ No newline at end of file diff --git a/Day4/Object.js b/Day4/Object.js new file mode 100644 index 0000000..d9252df --- /dev/null +++ b/Day4/Object.js @@ -0,0 +1,33 @@ +// In JavaScript, almost "everything" is an object. +//Objects are Variables too but can contain values +//Object Values are Written in key -> value Pair +//It is a common practice to declare objects with the const keyword. + +// Creating a javascript Object// + +//a) Using Object Literal. +const person = {"name":"ankit","class":"12th","department":"Computer Science"} +console.log(person.class); +console.log(person.department); +console.log(person.name) + +//b)Using New Keyword + +const playerdescription = new Object(); +playerdescription.name = "Shashank Sing"; +playerdescription.age = 18; +playerdescription.role = "Batsman"; +playerdescription.teamname = "Kings XI Punjab"; +console.log(playerdescription); + +//Javascript Objects are Mutable// +// Objects are mutable: They are addressed by reference, not by value -: As they are Refrential Data Type +const x = person; // Any changes to x will also occur in Person// + +//c) Object.create method -: creates a new Object, using an +// existing object as the prototype of the newly created object// +const neww = Object.create(playerdescription); +console.log(neww); + +//properties are the value associated with a Javacsrip Object// +// A JavaScript object is a collection of unordered properties \ No newline at end of file diff --git a/Task/Task1880.js b/Task/Task1880.js new file mode 100644 index 0000000..e0e6325 --- /dev/null +++ b/Task/Task1880.js @@ -0,0 +1,46 @@ +const arr = ["*","/","+","-"]; +const check = (operand,num1,num2)=>{ + if(arr.includes(operand) == false){ + return false; + } + if(Number.isInteger(num1) == false || Number.isInteger(num2)==false){ + return false; + } + + else if(operand == '/' && num2 == 0){ + return false; + } + + else{ + return true; + } +} + +const calculatorr = (operand,num1,num2) =>{ + if(check(operand,num1,num2) == false){ + console.log("Can't Do Operation"); + } + + else{ + let ans = cal[operand](num1,num2); + console.log(ans); + return ans; + } + } + + +const cal={ + '+': (num1,num2)=>num1+num2, + '-':(num1,num2)=> num1 -num2, + '*':(num1,num2)=>num1*num2, + '/':(num1, num2)=>num1/num2 + } + + + calculatorr('+',3,4); + calculatorr('*',20,2); + calculatorr('/',0,0); + calculatorr('+','8',9); + calculatorr('$',8,9); + + \ No newline at end of file diff --git a/Task/Task1887.js b/Task/Task1887.js new file mode 100644 index 0000000..406a632 --- /dev/null +++ b/Task/Task1887.js @@ -0,0 +1,29 @@ + +const obj = { + "keyOne": "value One", + "keyTwo": "value Two", + "keyThree": "value Three", + } + + let url="https://localhost:400"; + + let condition = true; + + for(const x in obj){ + let value = obj[x]; + + if(condition == true){ + url = url + '?' + x + '=' + value; + condition = false; + } + + else{ + url = url + '&'; + url = url + x; + url = url + '='; + url = url + value; + } + } +// https://localhost:400?keyOne=value one&keyTwo=value Two&keyThree=value Three + + console.log(url); \ No newline at end of file diff --git a/Task/Task1888.js b/Task/Task1888.js new file mode 100644 index 0000000..b100859 --- /dev/null +++ b/Task/Task1888.js @@ -0,0 +1,51 @@ +function assertionobjectsequalEqual(expectedd, actuall,string) { + // Check if both arguments are objects + if (typeof expectedd === 'object' && typeof actuall === 'object') { + // Get the keys of both objects + const keys1 = Object.keys(expectedd); + const keys2 = Object.keys(actuall); + + // Check if the number of keys are the same + if (keys1.length !== keys2.length) { + return false; + } + + // Check if all keys in obj1 exist in obj2 + for (let key of keys1) { + if (!actuall.hasOwnProperty(key)) { + return false; + } + } + + // Recursively check each key-value pair + for (let key of keys1) { + if (!assertionobjectsequalEqual(expectedd[key], actuall[key],string)) { + return false; + } + } + + // If all checks pass, objects are equal + return true; + } + + // If arguments are not objects, compare them directly + return expectedd === actuall; +} + + + +const expected = {foo:6,bar:{bar2:244,car:22}}; +const actual = {foo:6,bar:{bar2:24,car:22}} + + +if(assertionobjectsequalEqual(actual, expected,"Find the two objects are equal") == true){ + console.log("Passed"); +} + +else{ + let expectedd = JSON.stringify(expected); + let actuall = JSON.stringify(actual); + let answerr = `FAILED EXPECTED ${expectedd}, but got ${actuall}`; + console.log(answerr); +} + diff --git a/Task/Task1889.js b/Task/Task1889.js new file mode 100644 index 0000000..01fd1db --- /dev/null +++ b/Task/Task1889.js @@ -0,0 +1,64 @@ +const square = (x) =>{ + return x*x; +} + +const squareroot = (x)=>{ + return Math.sqrt(x); +} + +const AreaoftheCircle = (x) =>{ + let radius = square(x); + 22/7*radius; +} + +const power = (x,y)=>{ + return Math.pow(x,y); +} + +const Sintheta = (x)=>{ + return Math.sin(x); +} + +const Tantheta = (x)=>{ + return Math.tan(x); +} + +const costheta = (x) =>{ + return Math.cos(x); +} + +const logarithmic = (x)=>{ + return Math.log(x); +} + +// console.log(squareroot(16)); +// console.log(square(4)); +// console.log(power(2,3)); +// console.log(AreaoftheCircle(4)); +// console.log(logarithmic(8)); + +function validate(typeofoperation,operation,...args){ + if(operation[typeofoperation].length!=args.length){ + console.log("Can't Perform Operation"); + } + else{ + return operation[typeofoperation](...args); + } +} + + +const operation = { + 'Cos' : (x)=>Math.cos(x), + 'logarithmic':(x)=>Math.log(x), + 'square':(x)=>x*x, + 'sqrt':(x)=>Math.sqrt(x), + 'AreaofCircle':(radius)=>Math.PI.radius*radius, + 'Power':(base,expo)=>Math.pow(base,expo), + 'Sin':(x)=>Math.sin(x), + 'Tan':(x)=>Math.tan(x) +} + +console.log(operation['Cos'](10)); +console.log(operation['Power'](2,3)); + +console.log(validate("Cos",operation,10,10)); \ No newline at end of file diff --git a/Task/Task1891.js b/Task/Task1891.js new file mode 100644 index 0000000..f6df4dc --- /dev/null +++ b/Task/Task1891.js @@ -0,0 +1,20 @@ +// Task 1891// +const calc = { + '+':(...args)=> args.reduce((acc,val)=>acc+val,0), + '-':(...args)=> args.reduce((acc,val)=>acc-val), + '/':(...args)=>{ + if(args.length == 0){ + console.log("Can't Do"); + } + else{ + return args.reduce((acc,val)=>acc/val); + } + }, + '*':(...args)=>args.reduce((acc,val)=>acc*val) +} + +// Example usage: +console.log(calc['+'](9, 4, 12, 16, 23, 43)); // Output: 107 +console.log(calc['-'](100, 10, 5)); // Output: 85 + + diff --git a/Task/Task1892.js b/Task/Task1892.js new file mode 100644 index 0000000..e69de29 diff --git a/Task/Task1893and1890.js b/Task/Task1893and1890.js new file mode 100644 index 0000000..abf6bb0 --- /dev/null +++ b/Task/Task1893and1890.js @@ -0,0 +1,100 @@ +//Task -1893 && 1880// +const prompt = require('prompt-sync')(); // For The Input Line by default Input is String we will typecast It// +const calculator = (number1, number2, operation)=>{ + if (operation === "+") { // These are the cases that we use in Calculator// + return Number(number1) + Number(number2); + } else if(operation === '-') { // Subtraction + return Number(number1) - Number(number2); + } else if (operation === '*') { // Multiplication + return Number(number1) * Number(number2); + } else if (operation === '/') { // Division + return Number(number1) / Number(number2); + } else { + console.log("Invalid operation."); + } +} + +function perform(calculator,...args){ // To Validate the length. Here args.length give us the no of Argument we have passed + if(calculator.length!=args.length){ + return "The length is no suitable"; // Suupose the length is not equal then we will throw an error + } + + else{ + + } + + return calculator(...args); // if the length is equal then we will calculate the output using the calculator fn +} + + + + +const converttocelsius = (temperature) => { // *F to Celsius + return Number(temperature)*(9/5) + 32; +} + +const converttofahereinheit = (temperature)=>{ // Celsius to Fahrenheit + return (Number(temperature) - 32)*(5/9); +} + +const calculateareaoftriangle = (base,height)=>{ // To Calculate the area of Triangle// + return 1/2*Number(base)*Number(height); +} + + + +const x = prompt("Please Enter the Number1"); // Taking Input from Prompt/,number1/ +const y = prompt("Please enter the Number2"); // Taking Input from Prompt,numbr2// +let z = prompt("Enter the operation you want to Perform"); // Taking Input from Prompt,Operation// + + +console.log(perform(calculator,x,y,z,7)); +console.log(perform(converttocelsius,45)); +console.log(perform(converttofahereinheit,45)); +console.log(perform(calculateareaoftriangle,4,8)); + + +let finalanswer = calculator("*",1,2,3,4,5,); +console.log(finalanswer); + +const arr = ["*","/","+","-"]; +const check = (operand,num1,num2)=>{ + if(arr.includes(operand) == false){ + return false; + } + if(Number.isInteger(num1) == false || Number.isInteger(num2)==false){ + return false; + } + + else if(operand == '/' && num2 == 0){ + return false; + } + + else{ + return true; + } +} +const cal={ + '+': (num1,num2)=>num1+num2, + '-':(num1,num2)=> num1 -num2, + '*':(num1,num2)=>num1*num2, + '/':(num1, num2)=>num1/num2 +} + + const calculatorr = (operand,num1,num2) =>{ + if(check(operand,num1,num2) == false){ + console.log("Can't Do Operation"); + } + + else{ + let ans = cal[operand](num1,num2); + console.log(ans); + return ans; + } + } + +// calculatorr('+',3,4); +// calculatorr('*',20,2); +// calculatorr('/',0,0); +// calculatorr('+','8',9); +// calculatorr('$',8,9); \ No newline at end of file diff --git a/Task/Task6625.js b/Task/Task6625.js new file mode 100644 index 0000000..589bd8c --- /dev/null +++ b/Task/Task6625.js @@ -0,0 +1,38 @@ +function findminimum(expression){ + let lengthofexpressiom = expression.length; + + if(lengthofexpressiom%2==1){ + return -1; + } + + const stack = []; + + for(let i=0;i=6" + } + }, + "node_modules/prompt-sync": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/prompt-sync/-/prompt-sync-4.2.0.tgz", + "integrity": "sha512-BuEzzc5zptP5LsgV5MZETjDaKSWfchl5U9Luiu8SKp7iZWD5tZalOxvNcZRwv+d2phNFr8xlbxmFNcRKfJOzJw==", + "dependencies": { + "strip-ansi": "^5.0.0" + } + }, + "node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + } + } +} diff --git a/node_modules/ansi-regex/index.js b/node_modules/ansi-regex/index.js new file mode 100644 index 0000000..9e37ec3 --- /dev/null +++ b/node_modules/ansi-regex/index.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = options => { + options = Object.assign({ + onlyFirst: false + }, options); + + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, options.onlyFirst ? undefined : 'g'); +}; diff --git a/node_modules/ansi-regex/license b/node_modules/ansi-regex/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/ansi-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/ansi-regex/package.json b/node_modules/ansi-regex/package.json new file mode 100644 index 0000000..66a43e1 --- /dev/null +++ b/node_modules/ansi-regex/package.json @@ -0,0 +1,53 @@ +{ + "name": "ansi-regex", + "version": "4.1.1", + "description": "Regular expression for matching ANSI escape codes", + "license": "MIT", + "repository": "chalk/ansi-regex", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava", + "view-supported": "node fixtures/view-codes.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern" + ], + "devDependencies": { + "ava": "^0.25.0", + "xo": "^0.23.0" + } +} diff --git a/node_modules/ansi-regex/readme.md b/node_modules/ansi-regex/readme.md new file mode 100644 index 0000000..d19c446 --- /dev/null +++ b/node_modules/ansi-regex/readme.md @@ -0,0 +1,87 @@ +# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex) + +> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- + + +## Install + +``` +$ npm install ansi-regex +``` + + +## Usage + +```js +const ansiRegex = require('ansi-regex'); + +ansiRegex().test('\u001B[4mcake\u001B[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); +//=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] +``` + + +## API + +### ansiRegex([options]) + +Returns a regex for matching ANSI escape codes. + +#### options + +##### onlyFirst + +Type: `boolean`
+Default: `false` *(Matches any ANSI escape codes in a string)* + +Match only the first ANSI escape. + + +## FAQ + +### Why do you test for codes not in the ECMA 48 standard? + +Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. + +On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. + + +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +## License + +MIT diff --git a/node_modules/prompt-sync/LICENSE b/node_modules/prompt-sync/LICENSE new file mode 100644 index 0000000..3f5ab36 --- /dev/null +++ b/node_modules/prompt-sync/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2019 Paolo Fragomeni & David Mark Clements + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/prompt-sync/README.md b/node_modules/prompt-sync/README.md new file mode 100644 index 0000000..2e72e71 --- /dev/null +++ b/node_modules/prompt-sync/README.md @@ -0,0 +1,118 @@ +# SYNOPSIS +A sync prompt for node. very simple. no C++ bindings and no bash scripts. + +Works on Linux, OS X and Windows. + +# BASIC MODE +```js + +var prompt = require('prompt-sync')(); +// +// get input from the user. +// +var n = prompt('How many more times? '); +``` +# WITH HISTORY + +History is an optional extra, to use simply install the history plugin. + +```sh +npm install --save prompt-sync-history +``` + +```js +var prompt = require('prompt-sync')({ + history: require('prompt-sync-history')() //open history file +}); +//get some user input +var input = prompt() +prompt.history.save() //save history back to file +``` + +See the [prompt-sync-history](http://npm.im/prompt-sync-history) module +for options, or fork it for customized behaviour. + +# API + +## `require('prompt-sync')(config) => prompt` + +Returns an instance of the `prompt` function. +Takes `config` option with the following possible properties + +`sigint`: Default is `false`. A ^C may be pressed during the input process to abort the text entry. If sigint it `false`, prompt returns `null`. If sigint is `true` the ^C will be handled in the traditional way: as a SIGINT signal causing process to exit with code 130. + +`eot`: Default is `false`. A ^D pressed as the first character of an input line causes prompt-sync to echo `exit` and exit the process with code 0. + +`autocomplete`: A completer function that will be called when user enters TAB to allow for autocomplete. It takes a string as an argument an returns an array of strings that are possible matches for completion. An empty array is returned if there are no matches. + +`history`: Takes an object that supplies a "history interface", see [prompt-sync-history](http://npm.im/prompt-sync-history) for an example. + +## `prompt(ask, value, opts)` + +`ask` is the label of the prompt, `value` is the default value +in absence of a response. + +The `opts` argument can also be in the first or second parameter position. + +Opts can have the following properties + +`echo`: Default is `'*'`. If set the password will be masked with the specified character. For hidden input, set echo to `''` (or use `prompt.hide`). + +`autocomplete`: Overrides the instance `autocomplete` function to allow for custom +autocompletion of a particular prompt. + +`value`: Same as the `value` parameter, the default value for the prompt. If `opts` +is in the third position, this property will *not* overwrite the `value` parameter. + +`ask`: Sames as the `value` parameter. The prompt label. If `opts` is not in the first position, the `ask` parameter will *not* be overridden by this property. + +## `prompt.hide(ask)` + +Convenience method for creating a standard hidden password prompt, +this is the same as `prompt(ask, {echo: ''})` + + +# LINE EDITING +Line editing is enabled in the non-hidden mode. (use up/down arrows for history and backspace and left/right arrows for editing) + +History is not set when using hidden mode. + +# EXAMPLES + +```js + //basic: + console.log(require('prompt-sync')()('tell me something about yourself: ')) + + var prompt = require('prompt-sync')({ + history: require('prompt-sync-history')(), + autocomplete: complete(['hello1234', 'he', 'hello', 'hello12', 'hello123456']), + sigint: false + }); + + var value = 'frank'; + var name = prompt('enter name: ', value); + console.log('enter echo * password'); + var pw = prompt({echo: '*'}); + var pwb = prompt('enter hidden password (or don\'t): ', {echo: '', value: '*pwb default*'}) + var pwc = prompt.hide('enter another hidden password: ') + var autocompleteTest = prompt('custom autocomplete: ', { + autocomplete: complete(['bye1234', 'by', 'bye12', 'bye123456']) + }); + + prompt.history.save(); + + console.log('\nName: %s\nPassword *: %s\nHidden password: %s\nAnother Hidden password: %s', name, pw, pwb, pwc); + console.log('autocomplete2: ', autocompleteTest); + + function complete(commands) { + return function (str) { + var i; + var ret = []; + for (i=0; i< commands.length; i++) { + if (commands[i].indexOf(str) == 0) + ret.push(commands[i]); + } + return ret; + }; + }; +``` diff --git a/node_modules/prompt-sync/index.js b/node_modules/prompt-sync/index.js new file mode 100644 index 0000000..076d9f8 --- /dev/null +++ b/node_modules/prompt-sync/index.js @@ -0,0 +1,243 @@ +'use strict' + +var fs = require('fs'); +var stripAnsi = require('strip-ansi'); +var term = 13; // carriage return + +/** + * create -- sync function for reading user input from stdin + * @param {Object} config { + * sigint: {Boolean} exit on ^C + * autocomplete: {StringArray} function({String}) + * history: {String} a history control object (see `prompt-sync-history`) + * } + * @returns {Function} prompt function + */ + + // for ANSI escape codes reference see https://en.wikipedia.org/wiki/ANSI_escape_code + +function create(config) { + + config = config || {}; + var sigint = config.sigint; + var eot = config.eot; + var autocomplete = config.autocomplete = + config.autocomplete || function(){return []}; + var history = config.history; + prompt.history = history || {save: function(){}}; + prompt.hide = function (ask) { return prompt(ask, {echo: ''}) }; + + return prompt; + + + /** + * prompt -- sync function for reading user input from stdin + * @param {String} ask opening question/statement to prompt for + * @param {String} value initial value for the prompt + * @param {Object} opts { + * echo: set to a character to be echoed, default is '*'. Use '' for no echo + * value: {String} initial value for the prompt + * ask: {String} opening question/statement to prompt for, does not override ask param + * autocomplete: {StringArray} function({String}) + * } + * + * @returns {string} Returns the string input or (if sigint === false) + * null if user terminates with a ^C + */ + + + function prompt(ask, value, opts) { + var insert = 0, savedinsert = 0, res, i, savedstr; + opts = opts || {}; + + if (Object(ask) === ask) { + opts = ask; + ask = opts.ask; + } else if (Object(value) === value) { + opts = value; + value = opts.value; + } + ask = ask || ''; + var echo = opts.echo; + var masked = 'echo' in opts; + autocomplete = opts.autocomplete || autocomplete; + + var fd = (process.platform === 'win32') ? + process.stdin.fd : + fs.openSync('/dev/tty', 'rs'); + + var wasRaw = process.stdin.isRaw; + if (!wasRaw) { process.stdin.setRawMode && process.stdin.setRawMode(true); } + + var buf = Buffer.alloc(3); + var str = '', character, read; + + savedstr = ''; + + if (ask) { + process.stdout.write(ask); + } + + var cycle = 0; + var prevComplete; + + while (true) { + read = fs.readSync(fd, buf, 0, 3); + if (read > 1) { // received a control sequence + switch(buf.toString()) { + case '\u001b[A': //up arrow + if (masked) break; + if (!history) break; + if (history.atStart()) break; + + if (history.atEnd()) { + savedstr = str; + savedinsert = insert; + } + str = history.prev(); + insert = str.length; + process.stdout.write('\u001b[2K\u001b[0G' + ask + str); + break; + case '\u001b[B': //down arrow + if (masked) break; + if (!history) break; + if (history.pastEnd()) break; + + if (history.atPenultimate()) { + str = savedstr; + insert = savedinsert; + history.next(); + } else { + str = history.next(); + insert = str.length; + } + process.stdout.write('\u001b[2K\u001b[0G'+ ask + str + '\u001b['+(insert+ask.length+1)+'G'); + break; + case '\u001b[D': //left arrow + if (masked) break; + var before = insert; + insert = (--insert < 0) ? 0 : insert; + if (before - insert) + process.stdout.write('\u001b[1D'); + break; + case '\u001b[C': //right arrow + if (masked) break; + insert = (++insert > str.length) ? str.length : insert; + process.stdout.write('\u001b[' + (insert+ask.length+1) + 'G'); + break; + default: + if (buf.toString()) { + str = str + buf.toString(); + str = str.replace(/\0/g, ''); + insert = str.length; + promptPrint(masked, ask, echo, str, insert); + process.stdout.write('\u001b[' + (insert+ask.length+1) + 'G'); + buf = Buffer.alloc(3); + } + } + continue; // any other 3 character sequence is ignored + } + + // if it is not a control character seq, assume only one character is read + character = buf[read-1]; + + // catch a ^C and return null + if (character == 3){ + process.stdout.write('^C\n'); + fs.closeSync(fd); + + if (sigint) process.exit(130); + + process.stdin.setRawMode && process.stdin.setRawMode(wasRaw); + + return null; + } + + // catch a ^D and exit + if (character == 4) { + if (str.length == 0 && eot) { + process.stdout.write('exit\n'); + process.exit(0); + } + } + + // catch the terminating character + if (character == term) { + fs.closeSync(fd); + if (!history) break; + if (!masked && str.length) history.push(str); + history.reset(); + break; + } + + // catch a TAB and implement autocomplete + if (character == 9) { // TAB + res = autocomplete(str); + + if (str == res[0]) { + res = autocomplete(''); + } else { + prevComplete = res.length; + } + + if (res.length == 0) { + process.stdout.write('\t'); + continue; + } + + var item = res[cycle++] || res[cycle = 0, cycle++]; + + if (item) { + process.stdout.write('\r\u001b[K' + ask + item); + str = item; + insert = item.length; + } + } + + if (character == 127 || (process.platform == 'win32' && character == 8)) { //backspace + if (!insert) continue; + str = str.slice(0, insert-1) + str.slice(insert); + insert--; + process.stdout.write('\u001b[2D'); + } else { + if ((character < 32 ) || (character > 126)) + continue; + str = str.slice(0, insert) + String.fromCharCode(character) + str.slice(insert); + insert++; + }; + + promptPrint(masked, ask, echo, str, insert); + + } + + process.stdout.write('\n') + + process.stdin.setRawMode && process.stdin.setRawMode(wasRaw); + + return str || value || ''; + }; + + + function promptPrint(masked, ask, echo, str, insert) { + if (masked) { + process.stdout.write('\u001b[2K\u001b[0G' + ask + Array(str.length+1).join(echo)); + } else { + process.stdout.write('\u001b[s'); + if (insert == str.length) { + process.stdout.write('\u001b[2K\u001b[0G'+ ask + str); + } else { + if (ask) { + process.stdout.write('\u001b[2K\u001b[0G'+ ask + str); + } else { + process.stdout.write('\u001b[2K\u001b[0G'+ str + '\u001b[' + (str.length - insert) + 'D'); + } + } + + // Reposition the cursor to the right of the insertion point + var askLength = stripAnsi(ask).length; + process.stdout.write(`\u001b[${askLength+1+(echo==''? 0:insert)}G`); + } + } +}; + +module.exports = create; diff --git a/node_modules/prompt-sync/package.json b/node_modules/prompt-sync/package.json new file mode 100644 index 0000000..b842943 --- /dev/null +++ b/node_modules/prompt-sync/package.json @@ -0,0 +1,40 @@ +{ + "name": "prompt-sync", + "version": "4.2.0", + "description": "a synchronous prompt for node.js", + "main": "index.js", + "scripts": { + "test": "node test" + }, + "repository": { + "type": "git", + "url": "https://github.com/heapwolf/prompt-sync.git" + }, + "keywords": [ + "prompt", + "sync", + "blocking", + "readline", + "input", + "getline", + "repl", + "history" + ], + "contributors": [ + { + "name": "Paolo Fragomeni", + "email": "paolo@async.ly" + }, + { + "name": "David Mark Clements", + "email": "david.clements@nearform.com" + } + ], + "license": "MIT", + "devDependencies": { + "prompt-sync-history": "^1.0.1" + }, + "dependencies": { + "strip-ansi": "^5.0.0" + } +} diff --git a/node_modules/prompt-sync/test.js b/node_modules/prompt-sync/test.js new file mode 100644 index 0000000..fc0df02 --- /dev/null +++ b/node_modules/prompt-sync/test.js @@ -0,0 +1,38 @@ +//basic: +console.log(require('./')()('tell me something about yourself: ')) + +// ANSI escape codes colored text test +require('./')()('\u001B[31mcolored text: \u001B[39m'); + +var prompt = require('./')({ + history: require('prompt-sync-history')(), + autocomplete: complete(['hello1234', 'he', 'hello', 'hello12', 'hello123456']), + sigint: false +}); + +var value = 'frank'; +var name = prompt('enter name: ', value); +console.log('enter echo * password'); +var pw = prompt({echo: '*'}); +var pwb = prompt('enter hidden password (or don\'t): ', {echo: '', value: '*pwb default*'}) +var pwc = prompt.hide('enter another hidden password: ') +var autocompleteTest = prompt('custom autocomplete: ', { + autocomplete: complete(['bye1234', 'by', 'bye12', 'bye123456']) +}); + +prompt.history.save(); + +console.log('\nName: %s\nPassword *: %s\nHidden password: %s\nAnother Hidden password: %s', name, pw, pwb, pwc); +console.log('autocomplete2: ', autocompleteTest); + +function complete(commands) { + return function (str) { + var i; + var ret = []; + for (i=0; i< commands.length; i++) { + if (commands[i].indexOf(str) == 0) + ret.push(commands[i]); + } + return ret; + }; +}; diff --git a/node_modules/strip-ansi/index.d.ts b/node_modules/strip-ansi/index.d.ts new file mode 100644 index 0000000..44e954d --- /dev/null +++ b/node_modules/strip-ansi/index.d.ts @@ -0,0 +1,15 @@ +/** +Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. + +@example +``` +import stripAnsi from 'strip-ansi'; + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` +*/ +export default function stripAnsi(string: string): string; diff --git a/node_modules/strip-ansi/index.js b/node_modules/strip-ansi/index.js new file mode 100644 index 0000000..9788c96 --- /dev/null +++ b/node_modules/strip-ansi/index.js @@ -0,0 +1,7 @@ +'use strict'; +const ansiRegex = require('ansi-regex'); + +const stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; + +module.exports = stripAnsi; +module.exports.default = stripAnsi; diff --git a/node_modules/strip-ansi/license b/node_modules/strip-ansi/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/strip-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/strip-ansi/package.json b/node_modules/strip-ansi/package.json new file mode 100644 index 0000000..7494fd7 --- /dev/null +++ b/node_modules/strip-ansi/package.json @@ -0,0 +1,54 @@ +{ + "name": "strip-ansi", + "version": "5.2.0", + "description": "Strip ANSI escape codes from a string", + "license": "MIT", + "repository": "chalk/strip-ansi", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd-check" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "strip", + "trim", + "remove", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "devDependencies": { + "ava": "^1.3.1", + "tsd-check": "^0.5.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/strip-ansi/readme.md b/node_modules/strip-ansi/readme.md new file mode 100644 index 0000000..8681fe8 --- /dev/null +++ b/node_modules/strip-ansi/readme.md @@ -0,0 +1,61 @@ +# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) + +> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string + +--- + +
+ + Get professional support for 'strip-ansi' with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- + +## Install + +``` +$ npm install strip-ansi +``` + + +## Usage + +```js +const stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` + + +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + +## Related + +- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module +- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes +- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +## License + +MIT diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..e33eb15 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,43 @@ +{ + "name": "javascript", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "javascript", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "prompt-sync": "^4.2.0" + } + }, + "node_modules/ansi-regex": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", + "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", + "engines": { + "node": ">=6" + } + }, + "node_modules/prompt-sync": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/prompt-sync/-/prompt-sync-4.2.0.tgz", + "integrity": "sha512-BuEzzc5zptP5LsgV5MZETjDaKSWfchl5U9Luiu8SKp7iZWD5tZalOxvNcZRwv+d2phNFr8xlbxmFNcRKfJOzJw==", + "dependencies": { + "strip-ansi": "^5.0.0" + } + }, + "node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..5775759 --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "name": "javascript", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "prompt-sync": "^4.2.0" + } +} From 424d7567b3dae89d804e233fe05a5b9ab2148322 Mon Sep 17 00:00:00 2001 From: ankittttss Date: Mon, 13 May 2024 13:31:42 +0530 Subject: [PATCH 2/2] Hi --- Day1/UnderstandingScope.js | 38 +++++++++++++++++ Day2/Loops.js | 31 ++++++++++++++ Day4/Object.js | 70 ++++++++++++++++++++++++-------- Day5/Destructering.js | 74 +++++++++++++++++++++++++++++++++ Day5/Spreadandrest.js | 24 +++++++++++ Task/Task1878.js | 71 ++++++++++++++++++++++++++++++++ Task/Task1879.js | 51 +++++++++++++++++++++++ Task/Task1887.js | 18 ++++----- Task/Task1889.js | 20 +++++---- Task/Task1892.js | 83 ++++++++++++++++++++++++++++++++++++++ Task/Task1893and1890.js | 34 +++++++++------- Task/Task4457 | 30 ++++++++++++++ Task/Task6626.js | 27 +++++++++++++ Task/result (1).json | 42 +++++++++++++++++++ Task/source (1).json | 37 +++++++++++++++++ 15 files changed, 604 insertions(+), 46 deletions(-) create mode 100644 Day1/UnderstandingScope.js create mode 100644 Day2/Loops.js create mode 100644 Day5/Destructering.js create mode 100644 Day5/Spreadandrest.js create mode 100644 Task/Task1878.js create mode 100644 Task/Task1879.js create mode 100644 Task/Task4457 create mode 100644 Task/result (1).json create mode 100644 Task/source (1).json diff --git a/Day1/UnderstandingScope.js b/Day1/UnderstandingScope.js new file mode 100644 index 0000000..8b3f3e1 --- /dev/null +++ b/Day1/UnderstandingScope.js @@ -0,0 +1,38 @@ +//Understanding Var + +// var variable1 = "hiii"; +// function f(){ +// var variable2 = "Hi"; +// console.log(variable1); //Global Scope +// function g(){ +// console.log(variable2); //Function Scope +// } +// g(); +// } + +// f(); +// var variable1 = "Hello"; +// console.log(variable1) +// console.log(variable2); + +// Let Keyword -: let can have global Scope and Function as well as Block Scope + +// console.log(x); //Let keyword give reference error when hoisted // +// let x = 10; + +// function f(){ +// let y = 6; +// console.log(x); +// } + +// console.log(y); +// x = 15// Reassignment// +// f(); + +//------------------------------------------------------------------------------------- + +//const-: variable declared with const can have global,function and block scope +//cannot be redeclared,and redesigned +//variables declared with const are hoisted to the top of the their global,local +//and block scope but without a default initialisation + diff --git a/Day2/Loops.js b/Day2/Loops.js new file mode 100644 index 0000000..8412b3e --- /dev/null +++ b/Day2/Loops.js @@ -0,0 +1,31 @@ +//for-off loop -: For off loop help you iterate the iterable objects that +// helps you to access the values without accessing the key// + +//for-in loop -: used to iterate over the enumerable properties of an objects. +//It allows you to access the keys of the object rather than the values + + +const user = { + name:"Anurag Saini", + age:20 +} + +const arr = [2,3,4,5,6,7,8]; + +// for(let x in arr){ +// console.log(x); // Indexing +// } + +// for(let x of arr){ +// console.log(x); // Values// +// } + +// for(let x in user){ +// console.log(x); +// } + +// for(let x of user){ +// console.log(x); +// } + +//user is the object name, name and age are the keys and corresponding of that are the values \ No newline at end of file diff --git a/Day4/Object.js b/Day4/Object.js index d9252df..8b06c87 100644 --- a/Day4/Object.js +++ b/Day4/Object.js @@ -5,29 +5,67 @@ // Creating a javascript Object// -//a) Using Object Literal. -const person = {"name":"ankit","class":"12th","department":"Computer Science"} -console.log(person.class); -console.log(person.department); -console.log(person.name) +// //a) Using Object Literal. +// const person = {"name":"ankit","class":"12th","department":"Computer Science"} +// console.log(person.class); +// console.log(person.department); +// console.log(person.name) -//b)Using New Keyword +// //b)Using New Keyword -const playerdescription = new Object(); -playerdescription.name = "Shashank Sing"; -playerdescription.age = 18; -playerdescription.role = "Batsman"; -playerdescription.teamname = "Kings XI Punjab"; -console.log(playerdescription); +// const playerdescription = new Object(); +// playerdescription.name = "Shashank Sing"; +// playerdescription.age = 18; +// playerdescription.role = "Batsman"; +// playerdescription.teamname = "Kings XI Punjab"; +// console.log(playerdescription); //Javascript Objects are Mutable// // Objects are mutable: They are addressed by reference, not by value -: As they are Refrential Data Type -const x = person; // Any changes to x will also occur in Person// +// const x = person; // Any changes to x will also occur in Person// //c) Object.create method -: creates a new Object, using an // existing object as the prototype of the newly created object// -const neww = Object.create(playerdescription); -console.log(neww); +// const neww = Object.create(playerdescription); +// console.log(neww); //properties are the value associated with a Javacsrip Object// -// A JavaScript object is a collection of unordered properties \ No newline at end of file +// A JavaScript object is a collection of unordered properties +//Accessing Javacsript Object -: +// the synatx is -:object.property name +//the synatx is -: object[i]; + + +// for(let x in person){ +// console.log(person[x]); +// } + +//Nested Objects + +const personn = { + fullName:"Spongebob,SquarePants", + age:30, + address:{ + state:"haryana", + city:"Panipat", + pincode:132103, + }, + Hobbies:["Karate","Football"], +} + + +function iteratingrecursively(obj){ + for(let x in obj){ + if(typeof obj[x] == 'object'){ + iteratingrecursively(obj[x]) + } + else{ + console.log(obj[x]); + } + } +} + +iteratingrecursively(personn) +function hello(){ + console.log("foo") +} diff --git a/Day5/Destructering.js b/Day5/Destructering.js new file mode 100644 index 0000000..bc1d499 --- /dev/null +++ b/Day5/Destructering.js @@ -0,0 +1,74 @@ +// // Destructering works with arrays and objects// + +// let person = { +// firstname:"Ankit", +// Seconname:"Saini" +// } + + +// const arr = [2,3,4,5]; +// const newarr = [...arr]; + +// console.log(newarr); + +// let {firstname,Seconname} = person // Destructering the objects// +// console.log(firstname); +// console.log(Seconname); + +// let {firstname:fname,Seconname:lname} = person; +// console.log(firstname); +// console.log(Seconname); + +// let {firstnamee,Seconnamee,middlename} = person; +// console.log(middlename); + +// let newperson = { +// first : "Ankit", +// Second : "Saini", +// cureentage:20 +// } + +// let {first,Second,cureentage:age=20,middlenamee = "notdefined"} = newperson +// console.log(middlenamee); + +//---------------------------------------------------------------------------------- +//Array Destrcutering// + +// const arr = [1,2,3]; +// let [x,...rest] = arr; + +// console.log(x); +// console.log(rest) // Spread operator// + +// // Skipping an item while Destructering// +// const arrvalue = ['one','two','three']; +// let [xx,,yy] = arrvalue; +// console.log(xx); +// console.log(yy); + + +// Important Tip -: The variable with the spread Syntax Comma Cannot have a trailing Comma You shoudl use this +//Rest Element as the last variable +// const arr = [2,3,4,5]; +// const [...x,y] = arr; // Showing Error// + +// let name1 = "Sonny"; +// let name2 = "Jay"; + +// [name1,name2] = [name2,name1]; // Swapping the Variable + +// console.log(name2); +// console.log(name1); + +let member = { + id:1, + name:{ + firstname:"Ankit", + secondname:"Saini" + } +} + +let {name:{firstname,secondname}} = member; +console.log(firstname); +console.log(secondname); + diff --git a/Day5/Spreadandrest.js b/Day5/Spreadandrest.js new file mode 100644 index 0000000..ba9bad7 --- /dev/null +++ b/Day5/Spreadandrest.js @@ -0,0 +1,24 @@ + +const arr = [1,2,3,4]; +const brr = [...arr]; + +console.log(brr); + + +const obj1 = { + name:"Microsoft", + owner:"Bill Gates" +} + +const obj2 = { + age:20 +} + +Object.assign(obj1,obj2); +console.log(JSON.stringify(obj1)) +console.log(Object.keys(obj1)); + + + + + diff --git a/Task/Task1878.js b/Task/Task1878.js new file mode 100644 index 0000000..95a7257 --- /dev/null +++ b/Task/Task1878.js @@ -0,0 +1,71 @@ + + +function Convert(source){ + const answer = {}; + + for(let x in source){ + // we Need to find the batch id if it's present then it's fine else no + + if(!(x.batch_id in source)){ + answer[x.batch_id] = [] // we will create an array of batch id. + } + + const allkeys = Object.keys(source); // We will find all of the keys and we will iterate + //The Object.keys() static method returns an array of a + //given object's own enumerable string-keyed property names. + + // Now as in our array we will store array of object with every batch id so we will create an another temp object + let temporary = {}; + + for(let x = 1;x{ @@ -51,14 +56,15 @@ const operation = { 'Cos' : (x)=>Math.cos(x), 'logarithmic':(x)=>Math.log(x), 'square':(x)=>x*x, - 'sqrt':(x)=>Math.sqrt(x), - 'AreaofCircle':(radius)=>Math.PI.radius*radius, + 'sqrt':(x)=>x<0?"Can't do":Math.sqrt(x), + 'AreaofCircle':(radius)=>radius<=0?"can't do":22/7*radius*radius, 'Power':(base,expo)=>Math.pow(base,expo), 'Sin':(x)=>Math.sin(x), 'Tan':(x)=>Math.tan(x) } -console.log(operation['Cos'](10)); -console.log(operation['Power'](2,3)); +// console.log(operation['Cos'](10)); +// console.log(operation['Power'](2,3)); -console.log(validate("Cos",operation,10,10)); \ No newline at end of file +// console.log(validate("Cos",operation,10,10)); +console.log(validate("sqrt",operation,9)); \ No newline at end of file diff --git a/Task/Task1892.js b/Task/Task1892.js index e69de29..5b7925e 100644 --- a/Task/Task1892.js +++ b/Task/Task1892.js @@ -0,0 +1,83 @@ +function ApplyTheoperation(a, b, operation) { // A Separate function to implement the different operations + switch (operation) { + case '+': return a + b; + case '-': return a - b; + case '*': return a * b; + case '/': return a / b; + } +} + + + +function checktheprecedence(operation) { // Checking the precedence because + and - have same and * and / have same// + if (operation === '+' || operation === '-') { + return 1; + } + + if (operation === '*' || operation === '/') { + return 2; + } +} + + + + + +function main(expression) { + const values = []; // Alternative of stack + const operations = [] + + for (let i = 0; i < expression.length; i++) { + if (expression[i] === ' ') { // Empty spaces and it's of no Use + continue; + } + + else if (expression[i] === '(') { // Opening Bracket push it into the operations + operations.push(expression[i]); + } + + else if (!isNaN(expression[i])) { // If we encounter an digit and if its a multi digit then convert it to a no// + let value = 0; + while (i < expression.length && !isNaN(expression[i])) { + value = (value * 10) + parseInt(expression[i]); // Parseint - converting it to integer// + i++; + } + values.push(value); // We will push it into over values stack// + i--; + } + + else if (expression[i] === ')') { // Now we have encountered the closing Bracket + //means we will evaluate the expression between a closing bracket and an opening Bracket// + while (operations.length !== 0 && operations[operations.length - 1] !== '(') { + const value2 = values.pop(); + const value1 = values.pop(); // For every two operands we will have single operator// + const operator = operations.pop(); + values.push(ApplyTheoperation(value1,value2,operator)); + } + if(operations.length!=0){ // Remove the opening brace// + operations.pop(); + } + } + else{ + while(operations.length!==0 && checktheprecedence(operations[operations.length-1])>=checktheprecedence(expression[i])){ + const value2 = values.pop(); // Now if we both of the operations arent matched + //we will check the precedence and we will evaluate// + const value1 = values.pop(); + const operation = operations.pop(); + values.push(ApplyTheoperation(value1,value2,operation)); + } + operations.push(expression[i]); + } + } + + while(operations.length!=0){ // Now the bracket has ben removed and we will evaluate simple expression + const value2 = values.pop(); + const value1 = values.pop(); + const operation = operations.pop(); + values.push(ApplyTheoperation(value1,value2,operation)); + } + + return values.pop(); +} + +console.log(main("1+(4*5)+(2+3)*4-10/2")); diff --git a/Task/Task1893and1890.js b/Task/Task1893and1890.js index abf6bb0..a804c52 100644 --- a/Task/Task1893and1890.js +++ b/Task/Task1893and1890.js @@ -1,5 +1,13 @@ //Task -1893 && 1880// const prompt = require('prompt-sync')(); // For The Input Line by default Input is String we will typecast It// + +const cal={ + '+': (num1,num2)=>num1+num2, + '-':(num1,num2)=> num1 -num2, + '*':(num1,num2)=>num1*num2, + '/':(num1, num2)=>num1/num2 +} + const calculator = (number1, number2, operation)=>{ if (operation === "+") { // These are the cases that we use in Calculator// return Number(number1) + Number(number2); @@ -20,10 +28,10 @@ function perform(calculator,...args){ // To Validate the length. Here args.lengt } else{ - + return calculator(...args); } - return calculator(...args); // if the length is equal then we will calculate the output using the calculator fn + // if the length is equal then we will calculate the output using the calculator fn } @@ -48,7 +56,7 @@ const y = prompt("Please enter the Number2"); // Taking Input from Prompt,numbr let z = prompt("Enter the operation you want to Perform"); // Taking Input from Prompt,Operation// -console.log(perform(calculator,x,y,z,7)); +console.log(cal) console.log(perform(converttocelsius,45)); console.log(perform(converttofahereinheit,45)); console.log(perform(calculateareaoftriangle,4,8)); @@ -58,6 +66,7 @@ let finalanswer = calculator("*",1,2,3,4,5,); console.log(finalanswer); const arr = ["*","/","+","-"]; + const check = (operand,num1,num2)=>{ if(arr.includes(operand) == false){ return false; @@ -74,14 +83,11 @@ const check = (operand,num1,num2)=>{ return true; } } -const cal={ - '+': (num1,num2)=>num1+num2, - '-':(num1,num2)=> num1 -num2, - '*':(num1,num2)=>num1*num2, - '/':(num1, num2)=>num1/num2 -} + + const calculatorr = (operand,num1,num2) =>{ + if(check(operand,num1,num2) == false){ console.log("Can't Do Operation"); } @@ -93,8 +99,8 @@ const cal={ } } -// calculatorr('+',3,4); -// calculatorr('*',20,2); -// calculatorr('/',0,0); -// calculatorr('+','8',9); -// calculatorr('$',8,9); \ No newline at end of file + calculatorr('+',3,4); + calculatorr('*',20,2); + calculatorr('/',0,0); + calculatorr('+','8',9); + calculatorr('$',8,9); \ No newline at end of file diff --git a/Task/Task4457 b/Task/Task4457 new file mode 100644 index 0000000..2a4245c --- /dev/null +++ b/Task/Task4457 @@ -0,0 +1,30 @@ +function deepCloneAnObject(object){ + if(typeof object!== 'object' || object === null){ // Base Condition in recurssion// + return object + } + + + let finalobject = Array.isArray(object)?[]:{} // To check whether the object has arrays, array is also an object + + + for(let x in object){ + finalobject[x] = deepCloneAnObject(object[x]); + console.log(finalobject[x]); + } + + return finalobject; +} + +const ankit = { + 'ankit':'saini', + 'age':'20', + item:{ + 'ankit':'saini', + 'age':'20' + }, + d:[2,3,{4:"ankit",5:"saini"}] +} + +deepCloneAnObject(ankit); +JSON.stringify(ankit); +console.log(ankit); diff --git a/Task/Task6626.js b/Task/Task6626.js index e69de29..eb48353 100644 --- a/Task/Task6626.js +++ b/Task/Task6626.js @@ -0,0 +1,27 @@ +function numberofways(arr, index, sum, target,memo) { + if (sum === target) { // If our sum is equal to the Target then return 1 as there is a Way we can achieve Target + return 1; + } + + + if (index >= arr.length) { // if the index is more than the array Length the return 0 we will never get the answer + return 0; + } + + + if(memo[index][sum+target]!=undefined){ + return memo[index][sum+target] + } + + return memo[index][sum+target] = numberofways(arr, index + 1, sum + arr[index], target,memo) + numberofways(arr, index + 1, sum - arr[index], target,memo) + numberofways(arr, index + 1, sum, target,memo); +} + +let arr = [-1, 9, 8, -3, 4]; +let sum = 0; +let target = 5; +let memo = Array.from({ length: arr.length + 1 }, () => Array(target * 2 + 1)); // Initialize memoization array with -1 +let ans = numberofways(arr, 0, sum, target,memo); +console.log(ans); + +// We can convert it into the Memoization just to optimise it// +// O(n * sum) Time Complexity of this code \ No newline at end of file diff --git a/Task/result (1).json b/Task/result (1).json new file mode 100644 index 0000000..8cd4f55 --- /dev/null +++ b/Task/result (1).json @@ -0,0 +1,42 @@ +[ + { + "123": [ + { + "name": "Tony", + "contact": "9872276210" + }, + { + "name": "Bruce", + "contact": "6776543210" + }, + { + "name": "Peter", + "contact": "7666543210" + } + ] + }, + { + "231": [ + { + "name": "Steve", + "contact": "7876543210" + }, + { + "name": "Phil", + "contact": "8896543210" + } + ] + }, + { + "321": [ + { + "name": "Nick", + "contact": "9876521210" + }, + { + "name": "Clint", + "contact": "8954643210" + } + ] + } +] diff --git a/Task/source (1).json b/Task/source (1).json new file mode 100644 index 0000000..0e487a3 --- /dev/null +++ b/Task/source (1).json @@ -0,0 +1,37 @@ +[ + { + "batch_id": "123", + "name": "Tony", + "contact": "9872276210" + }, + { + "batch_id": "231", + "name": "Steve", + "contact": "7876543210" + }, + { + "batch_id": "123", + "name": "Bruce", + "contact": "6776543210" + }, + { + "batch_id": "321", + "name": "Clint", + "contact": "8954643210" + }, + { + "batch_id": "123", + "name": "Peter", + "contact": "7666543210" + }, + { + "batch_id": "231", + "name": "Phil", + "contact": "8896543210" + }, + { + "batch_id": "321", + "name": "Nick", + "contact": "9876521210" + } +]