├── .DS_Store ├── resources ├── jsToMarkdown │ ├── readme.md │ └── jsToMarkdown.js ├── Arrow_Functions │ └── readme.md ├── Math │ └── readme.md ├── Currying │ └── readme.md ├── Spread │ └── readme.md ├── Recursive_Functions │ └── readme.md ├── Sets │ └── readme.md ├── Type_Conversion │ └── readme.md ├── Destructuring │ └── readme.md ├── Constructor_Function │ └── readme.md ├── Promise │ └── readme.md ├── Maps │ └── readme.md ├── Fetch_Api │ └── readme.md ├── Operators │ └── readme.md ├── Date │ └── readme.md ├── Loops │ └── readme.md ├── Timer_Function │ └── readme.md ├── RegEx │ └── readme.md └── Numbers │ └── readme.md └── readme.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beTop1PercentTechie/JS-Coding-Challenges/HEAD/.DS_Store -------------------------------------------------------------------------------- /resources/jsToMarkdown/readme.md: -------------------------------------------------------------------------------- 1 | ` Question 1: Convert a string to a valid number` 2 | 3 | Write a function to convert a string containing a number (e.g., "123") into an actual number. If it is not a valid number, return NaN. 4 | 5 | `Example:` 6 | 7 | ```javascript 8 | 9 | function convertToNumber(str) { 10 | // Your code here 11 | } 12 | 13 | console.log(convertToNumber("123")); // 123 14 | console.log(convertToNumber("abc")); // NaN 15 | 16 | ``` 17 | 18 | `Topics Covered:` 19 | Number methods i.e. Number(), isNaN() 20 | 21 | **Hints:** 22 | - [isNaN()](https://www.w3schools.com/jsref/jsref_isnan.asp), - [JS Numbers](https://www.w3schools.com/jsref/jsref_number.asp) 23 | 24 |
25 | Solution 26 | 27 | ### Let's look at the solution: 28 | 29 | ```javascript 30 | 31 | function convertToNumber(str) { 32 | const number = Number(str); // Try to convert the string to a number 33 | return isNaN(number) ? NaN : number; // If conversion fails, return NaN 34 | } 35 | 36 | console.log(convertToNumber("123")); // 123 37 | console.log(convertToNumber("abc")); // NaN 38 | console.log(convertToNumber("12.34")); // 12.34 39 | 40 | ``` 41 | 42 | **Explanation:** 43 | 44 | 45 | - Number(str): tries to convert the string to a number. 46 | - isNaN(number): checks if the result is not a valid number and returns NaN if it's invalid. 47 | 48 |
49 | 50 | ---- 51 | -------------------------------------------------------------------------------- /resources/jsToMarkdown/jsToMarkdown.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs"); 2 | 3 | function generateMarkdown(questionData) { 4 | const { 5 | title, 6 | description, 7 | example, 8 | topicsCovered, 9 | hints, 10 | solution, 11 | explanation, 12 | } = questionData; 13 | 14 | let markdown = `\` ${title}\`\n\n`; 15 | markdown += ` ${description}\n\n`; 16 | markdown += `\`Example:\`\n\n\`\`\`javascript\n${example}\n\`\`\`\n\n`; 17 | 18 | markdown += `\`Topics Covered:\`\n`; 19 | topicsCovered.forEach((topic, index) => { 20 | markdown += `${topic}`; 21 | if (index < topicsCovered.length - 1) { 22 | markdown += ", "; 23 | } 24 | }); 25 | markdown += `\n \n`; 26 | 27 | markdown += `**Hints:**\n`; 28 | hints.forEach((hint, index) => { 29 | markdown += `- [${hint.title}](${hint.link})`; 30 | if (index < hints.length - 1) { 31 | markdown += ", "; 32 | } 33 | }); 34 | markdown += `\n\n`; 35 | 36 | markdown += `
\n Solution\n\n`; 37 | markdown += `### Let's look at the solution:\n\n\`\`\`javascript\n${solution}\n\`\`\`\n\n`; 38 | markdown += `**Explanation:**\n\n${explanation}\n`; 39 | markdown += `
\n \n`; 40 | markdown += `---- \n`; 41 | 42 | return markdown; 43 | } 44 | 45 | // Question Data 46 | const questionData = { 47 | title: "Question 1: Convert a string to a valid number", 48 | 49 | description: 50 | 'Write a function to convert a string containing a number (e.g., "123") into an actual number. If it is not a valid number, return NaN.', 51 | example: ` 52 | function convertToNumber(str) { 53 | // Your code here 54 | } 55 | 56 | console.log(convertToNumber("123")); // 123 57 | console.log(convertToNumber("abc")); // NaN 58 | `, 59 | 60 | topicsCovered: ["Number methods i.e. Number()", "isNaN()"], 61 | 62 | hints: [ 63 | { 64 | title: "isNaN()", 65 | link: "https://www.w3schools.com/jsref/jsref_isnan.asp", 66 | }, 67 | { 68 | title: "JS Numbers", 69 | link: "https://www.w3schools.com/jsref/jsref_number.asp", 70 | }, 71 | ], 72 | 73 | solution: ` 74 | function convertToNumber(str) { 75 | const number = Number(str); // Try to convert the string to a number 76 | return isNaN(number) ? NaN : number; // If conversion fails, return NaN 77 | } 78 | 79 | console.log(convertToNumber("123")); // 123 80 | console.log(convertToNumber("abc")); // NaN 81 | console.log(convertToNumber("12.34")); // 12.34 82 | `, 83 | 84 | explanation: ` 85 | - Number(str): tries to convert the string to a number. 86 | - isNaN(number): checks if the result is not a valid number and returns NaN if it's invalid. 87 | `, 88 | 89 | }; 90 | 91 | // Generate Markdown 92 | const markdown = generateMarkdown(questionData); 93 | 94 | // Save Markdown to a file 95 | fs.appendFileSync("readme.md", markdown, "utf8"); 96 | 97 | console.log("Markdown file saved as question1.md"); 98 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Welcome to our JavaScript Coding Challenge Sheet! 🎉 2 | 3 | This thoughtfully curated collection is designed to help you strengthen your JavaScript skills, one question at a time. 4 | 5 | We've organized the challenges by topics, making it easy for you to focus on areas that matter most to you. Each category includes multiple questions, and every question comes with a title, description, example, topics covered, helpful hints, and finally, a detailed solution to guide you. 6 | 7 | 8 | ## Pre-Read Before You Begin: 9 | Please take a moment to carefully go through each question and fully understand the requirements. If you can figure it out, start building the solution confidently. No need to submit your solutions anywhere! 10 | 11 | If you're unable to solve the challenge initially: 12 | 13 | - Check out the topics covered for a hint or an idea of the approach. 14 | - Explore the helpful resources in the hints section to deepen your understanding. 15 | 16 | Make sure to give every challenge at least one try before looking at the solution. 17 | 18 | Once you're done, review the solution and give yourself a well-deserved treat—whether for getting the right answer or simply showing up! `Remember, consistent practice will eventually help you crack even the toughest problems.` 19 | 20 | 21 | Simply click on the link below to get started, and dive into a world of learning and growth. 22 | 23 | --- 24 | 25 | ### 1. [Numbers](/resources/Numbers/) 26 | ### 2. [String](/resources/String/) 27 | ### 3. [Operators](/resources/Operators/) 28 | ### 4. [Type Conversion](/resources/Type_Conversion/) 29 | ### 5. [Maps](/resources/Maps/) 30 | ### 6. [Sets](/resources/Sets/) 31 | ### 7. [Arrays](/resources/Array/) 32 | ### 8. [Objects](/resources/Objects/) 33 | ### 9. [Conditionals](/resources/Conditionals/) 34 | ### 10. [Ternary](/resources/Ternary/) 35 | ### 11. [Loops](/resources/Loops/) 36 | ### 12. [Regular Functions](/resources/Regular_Function/) 37 | ### 13. [Arrow Functions](/resources/Arrow_Functions/) 38 | ### 14. [Recursive Functions](/resources/Recursive_Functions/) 39 | ### 15. [Closure](/resources/Closure/) 40 | ### 16. [Currying](/resources/Currying/) 41 | ### 17. [Math](/resources/Math/) 42 | ### 18. [Date](/resources/Date/) 43 | ### 19. [Regex](/resources/RegEx/) 44 | ### 20. [Spread](/resources/Spread/) 45 | ### 21. [Rest](/resources/Rest_Parameter/) 46 | ### 22. [Destructuring](/resources/Destructuring/) 47 | ### 23. [Constructor Function](/resources/Constructor_Function/) 48 | ### 24. [Prototype](/resources/Prototype/) 49 | ### 25. [Error Handling](/resources/Error_Handling/) 50 | ### 26. [Promises](/resources/Promise/) 51 | ### 27. [Fetch API](/resources/Fetch_Api/) 52 | ### 28. [Browser APIs](/resources/Browser_API/) 53 | ### 29. [Timer Functions](/resources/Timer_Function/) 54 | ### 30. [DOM - CRUD Elements](/resources/DOM/) 55 | ### 31. [Events](/resources/Events/) 56 | 57 | --- 58 | 59 | #### We believe in you—best of luck as you tackle these challenges! 🌟 60 | 61 | `PS: Star the reporsitory if you found it useful` 62 | 63 | _Curated with ❤️ from Aimerz_ -------------------------------------------------------------------------------- /resources/Arrow_Functions/readme.md: -------------------------------------------------------------------------------- 1 | # Arrow Functions 2 | ##### `Question 1. Sum of Two Numbers` 3 | 4 | Write a program using an arrow function to calculate the sum of two numbers. 5 | 6 | `Example:` 7 | 8 | ```javascript 9 | 10 | const add = (a, b) => { 11 | 12 | // Your code here 13 | 14 | }; 15 | console.log(add(5, 3)); // Output: 8 16 | 17 | ``` 18 | 19 | `Topics Covered:` 20 | Arrow Function 21 | 22 | **Hints:** 23 | - [Arrow Function Syntax](https://www.programiz.com/javascript/arrow-function) 24 | 25 |
26 | Solution 27 | 28 | ### Let's look at the solution: 29 | 30 | ```javascript 31 | 32 | const add = (a, b) => a + b; 33 | console.log(add(5, 3)); // Output: 8 34 | 35 | ``` 36 | 37 | **Explanation:** 38 | 39 | 40 | - const add = (a, b) => a + b;: This is an arrow function that adds the values of a and b together. 41 | - console.log(add(5, 3));: This calls the add function with arguments 5 and 3, which returns 8, and console.log prints the result. 42 | 43 |
44 | 45 | ---- 46 | ###### ` Question 2. Find the Square of a Number` 47 | 48 | Write a program using an arrow function to calculate the square of a given number. 49 | 50 | `Example:` 51 | 52 | ```javascript 53 | 54 | const square = (a) => { 55 | 56 | // Your code here 57 | 58 | }; 59 | console.log(square(5)); // Output: 25 60 | 61 | ``` 62 | 63 | `Topics Covered:` 64 | Arrow Function 65 | 66 | **Hints:** 67 | - [Arrow Function](https://www.programiz.com/javascript/arrow-function) 68 | 69 |
70 | Solution 71 | 72 | ### Let's look at the solution: 73 | 74 | ```javascript 75 | 76 | const square = (a) => { 77 | a*a; 78 | }; 79 | console.log(square(5)); // Output: 25 80 | 81 | ``` 82 | 83 | **Explanation:** 84 | 85 | 86 | - The original function lacks a return statement, so it doesn't return any value, resulting in undefined when called. 87 | - Adding the return keyword ensures the function returns the result of a * a, so console.log(square(5)) outputs 25. 88 | 89 |
90 | 91 | ---- 92 | ###### ` Question 3. Check if a Number is Even` 93 | 94 | Write a program using an arrow function to check if a given number is even. Return true if even, otherwise false. 95 | 96 | `Example:` 97 | 98 | ```javascript 99 | 100 | const isEven = (n) =>{ 101 | 102 | // Your Code here 103 | 104 | } 105 | console.log(isEven(7)); // Output: false 106 | 107 | ``` 108 | 109 | `Topics Covered:` 110 | Arrow Function 111 | 112 | **Hints:** 113 | - [Arrow Function](https://www.programiz.com/javascript/arrow-function) 114 | 115 |
116 | Solution 117 | 118 | ### Let's look at the solution: 119 | 120 | ```javascript 121 | 122 | const isEven = (n) => n % 2 === 0; 123 | console.log(isEven(7)); // Output: false 124 | 125 | ``` 126 | 127 | **Explanation:** 128 | 129 | 130 | - The isEven function takes a parameter n and checks if it is even by using the modulus operator (%). 131 | - The expression n % 2 === 0 checks if the remainder when dividing n by 2 is 0, which means the number is even. 132 | 133 |
134 | 135 | ---- 136 | ###### ` Question 4. Filter Odd Numbers from an Array` 137 | 138 | Write a program using an arrow function to filter odd numbers from an array. 139 | 140 | `Example:` 141 | 142 | ```javascript 143 | 144 | const filterOdds = (arr) => { 145 | 146 | // Your Code here 147 | 148 | } 149 | console.log(filterOdds([1, 2, 3, 4, 5])); // Output: [1, 3, 5] 150 | 151 | ``` 152 | 153 | `Topics Covered:` 154 | Arrow Function 155 | 156 | **Hints:** 157 | - [Arrow Function](https://www.programiz.com/javascript/arrow-function) 158 | 159 |
160 | Solution 161 | 162 | ### Let's look at the solution: 163 | 164 | ```javascript 165 | 166 | const filterOdds = (arr) => arr.filter(num => num % 2 !== 0); 167 | console.log(filterOdds([1, 2, 3, 4, 5])); // Output: [1, 3, 5] 168 | 169 | ``` 170 | 171 | **Explanation:** 172 | 173 | 174 | - The filterOdds uses the filter() method to iterate over the array arr. 175 | - For each number (num), it checks if num % 2 !== 0, which returns true for odd numbers. 176 | 177 |
178 | 179 | ---- 180 | ###### ` Question 5. Convert Celsius to Fahrenheit` 181 | 182 | Write a program using an arrow function to convert a given temperature in Celsius to Fahrenheit. 183 | 184 | `Example:` 185 | 186 | ```javascript 187 | 188 | const celsiusToFahrenheit = (celsius) => 189 | { 190 | 191 | // your code here 192 | 193 | } 194 | console.log(celsiusToFahrenheit(25)); // Output: 195 | 196 | ``` 197 | 198 | `Topics Covered:` 199 | Arrow Function 200 | 201 | **Hints:** 202 | - [Arrow Function](https://www.programiz.com/javascript/arrow-function) 203 | 204 |
205 | Solution 206 | 207 | ### Let's look at the solution: 208 | 209 | ```javascript 210 | 211 | const celsiusToFahrenheit = (celsius) => (celsius * 9/5) + 32; 212 | console.log(celsiusToFahrenheit(25)); // Output: 77 213 | 214 | ``` 215 | 216 | **Explanation:** 217 | 218 | 219 | - The (celsius * 9/5) + 32 converts the Celsius temperature (celsius) to Fahrenheit. 220 | - (celsius * 9/5) + 32 converts the Celsius temperature (celsius) to Fahrenheit. 221 | 222 |
223 | 224 | ---- 225 | ###### ` Question 6. Enumerate a Map` 226 | 227 | Write a program using an arrow function to enumerate (loop through) a Map and print each key-value pair. 228 | 229 | `Example:` 230 | 231 | ```javascript 232 | 233 | const enumerateMap = (map) => { 234 | 235 | // Your Code here 236 | 237 | }; 238 | 239 | const myMap = new Map([["a", 1], ["b", 2], ["c", 3]]); 240 | enumerateMap(myMap); 241 | 242 | 243 | 244 | 245 | ``` 246 | 247 | `Topics Covered:` 248 | Arrow Function 249 | 250 | **Hints:** 251 | - [Arrow Function](https://www.programiz.com/javascript/arrow-function) 252 | 253 |
254 | Solution 255 | 256 | ### Let's look at the solution: 257 | 258 | ```javascript 259 | 260 | const enumerateMap = (map) => { 261 | map.forEach((value, key) => console.log("Key: " + key + ", Value: " + value)); 262 | }; 263 | 264 | const myMap = new Map([["a", 1], ["b", 2], ["c", 3]]); 265 | enumerateMap(myMap); 266 | 267 | 268 | ``` 269 | 270 | **Explanation:** 271 | 272 | 273 | - The arrow function enumerateMap takes a Map and uses the forEach() method to iterate through each key-value pair. It logs the key and value in each iteration. 274 | - The Map is passed to the enumerateMap function. 275 | 276 |
277 | 278 | ---- 279 | -------------------------------------------------------------------------------- /resources/Math/readme.md: -------------------------------------------------------------------------------- 1 | # Math 2 | ###### ` Question 1. Find the Factorial of a Number` 3 | 4 | Write a function to calculate the factorial of a given number. The factorial of n is the product of all positive integers less than or equal to n. 5 | 6 | `Example:` 7 | 8 | ```javascript 9 | 10 | function factorial(n) { 11 | 12 | // Your code here 13 | 14 | } 15 | 16 | console.log(factorial(5)); // Output: 120 17 | 18 | 19 | ``` 20 | 21 | `Topics Covered:` 22 | Factorial of a Number, Maths 23 | 24 | **Hints:** 25 | - [Factorial](https://www.freecodecamp.org/news/how-to-factorialize-a-number-in-javascript-9263c89a4b38/) 26 | - [Maths](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) 27 | 28 |
29 | Solution 30 | 31 | ### Let's look at the solution: 32 | 33 | ```javascript 34 | 35 | function factorial(n) { 36 | if (n === 0) { 37 | return 1; 38 | } else { 39 | return n * factorial(n - 1); 40 | } 41 | } 42 | 43 | console.log(factorial(5)); // Output: 120 44 | 45 | ``` 46 | 47 | **Explanation:** 48 | 49 | 50 | - The factorial function uses recursion to calculate the factorial of n. If n is 0, it returns 1 (base case). 51 | - It multiplies n by the factorial of n - 1. 52 | 53 |
54 | 55 | ---- 56 | ###### ` Question 2. Find the Greatest Common Divisor (GCD)` 57 | 58 | Write a function to find the GCD of two numbers using the Euclidean algorithm. The GCD is the largest number that divides both the numbers without leaving a remainder. 59 | 60 | `Example:` 61 | 62 | ```javascript 63 | 64 | function gcd(a, b) { 65 | 66 | // Your code here 67 | 68 | } 69 | 70 | console.log(gcd(56, 98)); // Output: 14 71 | 72 | 73 | 74 | ``` 75 | 76 | `Topics Covered:` 77 | GCD of a Number, Maths 78 | 79 | **Hints:** 80 | - [GCD](https://www.w3resource.com/javascript-exercises/javascript-math-exercise-8.php) 81 | - [Maths](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) 82 | 83 |
84 | Solution 85 | 86 | ### Let's look at the solution: 87 | 88 | ```javascript 89 | 90 | function gcd(a, b) { 91 | if (b === 0) { 92 | return a; 93 | } else { 94 | return gcd(b, a % b); 95 | } 96 | } 97 | 98 | console.log(gcd(56, 98)); // Output: 14 99 | 100 | ``` 101 | 102 | **Explanation:** 103 | 104 | 105 | - The gcd function uses recursion to find the greatest common divisor of a and b. 106 | - If b is 0, it returns a. Otherwise, it recursively calls gcd with b and a % b. 107 | 108 |
109 | 110 | ---- 111 | ###### ` Question 3. Calculate the Square Root of a Number` 112 | 113 | Write a function that returns the square root of a given number. If the number is negative, return an error message. 114 | 115 | `Example:` 116 | 117 | ```javascript 118 | 119 | function squareRoot(n) { 120 | 121 | // Your Code here 122 | 123 | } 124 | 125 | console.log(squareRoot(25)); // Output: 5 126 | 127 | ``` 128 | 129 | `Topics Covered:` 130 | Maths 131 | 132 | **Hints:** 133 | - [Maths](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) 134 | 135 |
136 | Solution 137 | 138 | ### Let's look at the solution: 139 | 140 | ```javascript 141 | 142 | function squareRoot(n) { 143 | if (n < 0) { 144 | return "Invalid input"; 145 | } else { 146 | return Math.sqrt(n); 147 | } 148 | } 149 | 150 | console.log(squareRoot(25)); // Output: 5 151 | 152 | 153 | ``` 154 | 155 | **Explanation:** 156 | 157 | 158 | - The squareRoot function checks if the input n is less than 0. 159 | - If true, it returns "Invalid input". Otherwise, it returns the square root of n using Math.sqrt(n). 160 | 161 |
162 | 163 | ---- 164 | ###### ` Question 4. Find the Power of a Number` 165 | 166 | Write a function to calculate the power of a number, i.e., base raised to the exponent. 167 | 168 | `Example:` 169 | 170 | ```javascript 171 | 172 | function power(base, exponent) { 173 | 174 | // Your code here 175 | 176 | } 177 | 178 | console.log(power(3, 4)); // Output: 81 179 | 180 | 181 | ``` 182 | 183 | `Topics Covered:` 184 | Maths 185 | 186 | **Hints:** 187 | - [Maths](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) 188 | 189 |
190 | Solution 191 | 192 | ### Let's look at the solution: 193 | 194 | ```javascript 195 | 196 | function power(base, exponent) { 197 | 198 | return Math.pow(base, exponent); 199 | 200 | } 201 | 202 | console.log(power(3, 4)); // Output: 81 203 | 204 | 205 | ``` 206 | 207 | **Explanation:** 208 | 209 | 210 | - The power function takes two arguments, base and exponent, and calculates the result using Math.pow(base, exponent). 211 | - For power(3, 4), it computes 3^4 , which equals 81. 212 | 213 |
214 | 215 | ---- 216 | ###### ` Question 5. Check if a Number is Prime` 217 | 218 | Write a function to check if a given number is a prime number. A prime number is a number greater than 1 that has no divisors other than 1 and itself. 219 | 220 | `Example:` 221 | 222 | ```javascript 223 | 224 | function isPrime(n) { 225 | 226 | // Your code here 227 | 228 | } 229 | 230 | console.log(isPrime(11)); // Output: true 231 | 232 | 233 | ``` 234 | 235 | `Topics Covered:` 236 | Maths 237 | 238 | **Hints:** 239 | - [Maths](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) 240 | 241 |
242 | Solution 243 | 244 | ### Let's look at the solution: 245 | 246 | ```javascript 247 | 248 | function isPrime(n) { 249 | if (n <= 1) { 250 | return false; 251 | } 252 | for (let i = 2; i <= Math.sqrt(n); i++) { 253 | if (n % i === 0) { 254 | return false; 255 | } 256 | } 257 | return true; 258 | } 259 | 260 | console.log(isPrime(11)); // Output: true 261 | 262 | 263 | 264 | ``` 265 | 266 | **Explanation:** 267 | 268 | 269 | - he isPrime function checks if n is less than or equal to 1 (not prime). 270 | - It then iterates from 2 to Math.sqrt(n) and checks if n is divisible by any number in that range. 271 | 272 |
273 | 274 | ---- 275 | ###### ` Question 6. Find the Least Common Multiple (LCM)` 276 | 277 | Write a function to calculate the LCM of two numbers. The LCM is the smallest positive integer that is divisible by both numbers. 278 | 279 | `Example:` 280 | 281 | ```javascript 282 | 283 | function gcd(a, b) { 284 | return b === 0 ? a : gcd(b, a % b); // Helper function to calculate GCD 285 | } 286 | 287 | function lcm(a, b) { 288 | 289 | // Your code here 290 | 291 | } 292 | 293 | console.log(lcm(4, 5)); // Output: 20 294 | 295 | 296 | 297 | ``` 298 | 299 | `Topics Covered:` 300 | Maths 301 | 302 | **Hints:** 303 | - [Maths](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) 304 | 305 |
306 | Solution 307 | 308 | ### Let's look at the solution: 309 | 310 | ```javascript 311 | 312 | function gcd(a, b) { 313 | return b === 0 ? a : gcd(b, a % b); // Helper function to calculate GCD 314 | } 315 | 316 | function lcm(a, b) { 317 | return (a * b) / gcd(a, b); 318 | } 319 | 320 | console.log(lcm(4, 5)); // Output: 20 321 | 322 | ``` 323 | 324 | **Explanation:** 325 | 326 | 327 | - LCM Function: The lcm function calculates the least common multiple using the formula. 328 | - Helper Function (gcd): The gcd function calculates the greatest common divisor using recursion. If b is 0, it returns a. 329 | 330 |
331 | 332 | ---- 333 | -------------------------------------------------------------------------------- /resources/Currying/readme.md: -------------------------------------------------------------------------------- 1 | # Currying 2 | 3 | ###### ` Question 1. Add Two Numbers` 4 | 5 | Write a curried function that accepts two numbers as arguments and returns their sum. The first argument is passed to the curried function, and the second argument is passed to the returned function. 6 | 7 | `Example:` 8 | 9 | ```javascript 10 | 11 | const add = function(a) { 12 | return function(b) { 13 | 14 | // Your Code here 15 | 16 | }; 17 | }; 18 | 19 | console.log(add(5)(3)); // Output: 8 20 | 21 | ``` 22 | 23 | `Topics Covered:` 24 | Function Currying 25 | 26 | **Hints:** 27 | - [Function Currying](https://www.geeksforgeeks.org/what-is-currying-function-in-javascript/) 28 | - [Currying]( https://javascript.info/currying-partials/) 29 | 30 |
31 | Solution 32 | 33 | ### Let's look at the solution: 34 | 35 | ```javascript 36 | 37 | const add = function(a) { 38 | return function(b) { 39 | return a + b; 40 | }; 41 | }; 42 | 43 | console.log(add(5)(3)); // Output: 8 44 | 45 | ``` 46 | 47 | **Explanation:** 48 | 49 | 50 | - The add function is an anonymous function that returns another function, which takes b and adds it to a. 51 | - When called as add(5)(3), it returns 5 + 3, resulting in 8. 52 | 53 |
54 | 55 | ---- 56 | ###### ` Question 2. Multiply Three Numbers with currying` 57 | 58 | Write a curried function that takes three numbers and returns their product. The curried function should handle each number step by step, with the first function accepting the first number, and the second and third functions handling the remaining numbers. 59 | 60 | `Example:` 61 | 62 | ```javascript 63 | 64 | function multiply(a) { 65 | 66 | // Write your code here 67 | 68 | } 69 | 70 | console.log(multiply(2)(3)(4)); // Output: 24 71 | 72 | ``` 73 | 74 | `Topics Covered:` 75 | Function Currying 76 | 77 | **Hints:** 78 | - [Function Currying](https://www.geeksforgeeks.org/what-is-currying-function-in-javascript/), - [Currying]( https://javascript.info/currying-partials/) 79 | 80 |
81 | Solution 82 | 83 | ### Let's look at the solution: 84 | 85 | ```javascript 86 | 87 | function multiply(a) { 88 | return function(b) { 89 | return function(c) { 90 | return a * b * c; 91 | }; 92 | }; 93 | } 94 | 95 | console.log(multiply(2)(3)(4)); // Output: 24 96 | 97 | ``` 98 | 99 | **Explanation:** 100 | 101 | 102 | - The multiply function returns another function for each parameter, b and c. 103 | - When called as multiply(2)(3)(4), it multiplies 2 * 3 * 4, resulting in 24. 104 | 105 |
106 | 107 | ---- 108 | ###### ` Question 3. Calculate Power` 109 | 110 | Write a curried function that calculates the power of a number, where the first argument is the base, and the second is the exponent. This function should return the result of raising the base to the power of the exponent. 111 | 112 | `Example:` 113 | 114 | ```javascript 115 | 116 | function power(a) { 117 | 118 | // Your code here 119 | 120 | } 121 | 122 | console.log(power(2)(3)); // Output: 8 123 | 124 | 125 | ``` 126 | 127 | `Topics Covered:` 128 | Function Currying 129 | 130 | **Hints:** 131 | - [Function Currying](https://www.geeksforgeeks.org/what-is-currying-function-in-javascript/), - [Currying]( https://javascript.info/currying-partials/) 132 | 133 |
134 | Solution 135 | 136 | ### Let's look at the solution: 137 | 138 | ```javascript 139 | 140 | function power(a) { 141 | return function(b) { 142 | return Math.pow(a, b); 143 | }; 144 | } 145 | 146 | console.log(power(2)(3)); // Output: 8 147 | 148 | 149 | ``` 150 | 151 | **Explanation:** 152 | 153 | 154 | - The power function returns another function that calculates a raised to the power of b using Math.pow(a, b). 155 | 156 |
157 | 158 | ---- 159 | ###### ` Question 4. String Concatenation` 160 | 161 | Write a curried function to concatenate two strings. The first function should accept the first string, and the second function should accept the second string. It should return the concatenated result of both strings. 162 | 163 | `Example:` 164 | 165 | ```javascript 166 | 167 | function concatStrings(str1) { 168 | 169 | // Your Code here 170 | 171 | } 172 | 173 | console.log(concatStrings("Hello")("World")); // Output: "HelloWorld" 174 | 175 | 176 | ``` 177 | 178 | `Topics Covered:` 179 | Function Currying 180 | 181 | **Hints:** 182 | - [Function Currying](https://www.geeksforgeeks.org/what-is-currying-function-in-javascript/), - [Currying]( https://javascript.info/currying-partials/) 183 | 184 |
185 | Solution 186 | 187 | ### Let's look at the solution: 188 | 189 | ```javascript 190 | 191 | function concatStrings(str1) { 192 | return function(str2) { 193 | return str1 + str2; 194 | }; 195 | } 196 | 197 | console.log(concatStrings("Hello")("World")); // Output: "HelloWorld" 198 | 199 | ``` 200 | 201 | **Explanation:** 202 | 203 | 204 | - The concatStrings function takes str1 and returns another function that takes str2 and concatenates both strings. 205 | - When called as concatStrings("Hello")("World"), it concatenates "Hello" and "World", resulting in "HelloWorld". 206 | 207 |
208 | 209 | ---- 210 | ###### ` Question 5. Subtract Two Numbers` 211 | 212 | Write a curried function that takes two numbers and returns their difference. The curried function will first accept one number, and then the second function will accept the second number to subtract from the first. 213 | 214 | `Example:` 215 | 216 | ```javascript 217 | 218 | function subtract(a) { 219 | 220 | // Your code here 221 | 222 | } 223 | 224 | console.log(subtract(10)(5)); // Output: 5 225 | 226 | ``` 227 | 228 | `Topics Covered:` 229 | Function Currying 230 | 231 | **Hints:** 232 | - [Function Currying](https://www.geeksforgeeks.org/what-is-currying-function-in-javascript/), - [Currying]( https://javascript.info/currying-partials/) 233 | 234 |
235 | Solution 236 | 237 | ### Let's look at the solution: 238 | 239 | ```javascript 240 | 241 | function subtract(a) { 242 | return function(b) { 243 | return a - b; 244 | }; 245 | } 246 | 247 | console.log(subtract(10)(5)); // Output: 5 248 | 249 | ``` 250 | 251 | **Explanation:** 252 | 253 | 254 | - The subtract function takes a and returns another function that subtracts b from a. 255 | - When called as subtract(10)(5), it performs 10 - 5, resulting in 5. 256 | 257 |
258 | 259 | ---- 260 | ###### ` Question 6. Calculate Final Price After Discount and Tax` 261 | 262 | Write a curried function that calculates the final price of a product after applying a discount and then adding tax. The first function will accept the original price of the product, the second function will accept the discount rate, and the third function will accept the tax rate. The function should return the final price after applying the discount and tax. 263 | 264 | `Example:` 265 | 266 | ```javascript 267 | 268 | function calculateFinalPrice(price) { 269 | 270 | // Your code here 271 | 272 | } 273 | 274 | console.log(calculateFinalPrice(1000)(20)(15)); // Output: 920 275 | 276 | 277 | 278 | ``` 279 | 280 | `Topics Covered:` 281 | Function Currying 282 | 283 | **Hints:** 284 | - [Function Currying](https://www.geeksforgeeks.org/what-is-currying-function-in-javascript/), - [Currying]( https://javascript.info/currying-partials/) 285 | 286 |
287 | Solution 288 | 289 | ### Let's look at the solution: 290 | 291 | ```javascript 292 | 293 | function calculateFinalPrice(price) { 294 | return function(discountRate) { 295 | return function(taxRate) { 296 | const discount = price * (discountRate / 100); 297 | const priceAfterDiscount = price - discount; 298 | const finalPrice = priceAfterDiscount * (1 + taxRate / 100); 299 | return finalPrice; 300 | }; 301 | }; 302 | } 303 | 304 | console.log(calculateFinalPrice(1000)(20)(15)); // Output: 920 305 | 306 | ``` 307 | 308 | **Explanation:** 309 | 310 | 311 | - The discount is subtracted from the original price, and then tax is added to the discounted price to calculate the final price. 312 | - For an original price of 1000, a 20% discount, and a 15% tax, the final price is 920. 313 | 314 |
315 | 316 | ---- 317 | -------------------------------------------------------------------------------- /resources/Spread/readme.md: -------------------------------------------------------------------------------- 1 | # Spread 2 | 3 | ###### ` Question 1. Merge Two Arrays` 4 | 5 | Write a program to merge two arrays into one using the spread operator. The spread operator should be used to combine both arrays without modifying the original arrays. 6 | 7 | `Example:` 8 | 9 | ```javascript 10 | 11 | function mergeArrays(arr1, arr2) { 12 | 13 | // Your Code here 14 | 15 | 16 | console.log(mergeArrays([1, 2, 3], [4, 5, 6])); 17 | // Output: [1, 2, 3, 4, 5, 6] 18 | 19 | ``` 20 | 21 | `Topics Covered:` 22 | Spread Operator 23 | 24 | **Hints:** 25 | - [Spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) 26 | 27 |
28 | Solution 29 | 30 | ### Let's look at the solution: 31 | 32 | ```javascript 33 | 34 | function mergeArrays(arr1, arr2) { 35 | return [...arr1, ...arr2]; 36 | } 37 | 38 | console.log(mergeArrays([1, 2, 3], [4, 5, 6])); 39 | // Output: [1, 2, 3, 4, 5, 6] 40 | 41 | ``` 42 | 43 | **Explanation:** 44 | 45 | 46 | - The mergeArrays function takes two arrays as arguments and merges them using the spread operator (...), which spreads the elements of both arrays into a new array. 47 | - For the inputs [1, 2, 3] and [4, 5, 6], the merged result is [1, 2, 3, 4, 5, 6]. 48 | 49 |
50 | 51 | ---- 52 | ###### ` Question 2. Clone an Object` 53 | 54 | Write a program to create a copy of an object using the spread operator. Ensure that the original object remains unchanged when modifications are made to the cloned object. 55 | 56 | `Example:` 57 | 58 | ```javascript 59 | 60 | function cloneObject(obj) { 61 | 62 | // Your code here 63 | 64 | } 65 | 66 | const original = { name: "Alice", age: 25 }; 67 | const cloned = cloneObject(original); 68 | console.log(cloned); 69 | // Output: { name: "Alice", age: 25 } 70 | 71 | ``` 72 | 73 | `Topics Covered:` 74 | Spread Operator 75 | 76 | **Hints:** 77 | - [Spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) 78 | 79 |
80 | Solution 81 | 82 | ### Let's look at the solution: 83 | 84 | ```javascript 85 | 86 | function cloneObject(obj) { 87 | const clonedObj = {}; 88 | for (const key in obj) { 89 | if (obj.hasOwnProperty(key)) { 90 | clonedObj[key] = obj[key]; 91 | } 92 | } 93 | return clonedObj; 94 | } 95 | 96 | const original = { name: "Alice", age: 25 }; 97 | const cloned = cloneObject(original); 98 | console.log(cloned); 99 | // Output: { name: "Alice", age: 25 } 100 | 101 | ``` 102 | 103 | **Explanation:** 104 | 105 | 106 | - Cloning Logic: The function iterates through the object's keys and copies its properties. 107 | - Property Check: hasOwnProperty ensures only the object's own properties are copied. 108 | - Output: Returns a new object (clonedObj) identical to the original. 109 | 110 |
111 | 112 | ---- 113 | ###### ` Question 3. Add Elements to an Array` 114 | 115 | Write a program to add elements to the beginning and end of an array using the spread operator. The spread operator should ensure the original array remains unchanged. 116 | 117 | `Example:` 118 | 119 | ```javascript 120 | 121 | function addElements(arr, start, end) { 122 | 123 | // Write your code here 124 | 125 | } 126 | 127 | console.log(addElements([2, 3, 4], 1, 5)); 128 | // Output: [1, 2, 3, 4, 5] 129 | 130 | 131 | ``` 132 | 133 | `Topics Covered:` 134 | Spread Operator 135 | 136 | **Hints:** 137 | - [Spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) 138 | 139 |
140 | Solution 141 | 142 | ### Let's look at the solution: 143 | 144 | ```javascript 145 | 146 | function cloneObject(obj) { 147 | function addElements(arr, start, end) { 148 | return [start, ...arr, end]; 149 | } 150 | 151 | console.log(addElements([2, 3, 4], 1, 5)); 152 | // Output: [1, 2, 3, 4, 5] 153 | 154 | ``` 155 | 156 | **Explanation:** 157 | 158 | 159 | - The addElements function adds start at the beginning and end at the end of arr. 160 | - Uses the spread operator (...) to insert arr between start and end. 161 | 162 |
163 | 164 | ---- 165 | ###### ` Question 4. Combine Two Objects` 166 | 167 | Write a program to combine the properties of two objects into one using the spread operator. Ensure the second object’s properties overwrite those of the first object if there are conflicts. 168 | 169 | `Example:` 170 | 171 | ```javascript 172 | 173 | function combineObjects(obj1, obj2) { 174 | 175 | // Your code here 176 | 177 | } 178 | 179 | console.log(combineObjects({ name: "Alice", age: 25 }, { age: 30, city: "New York" })); 180 | // Output: { name: "Alice", age: 30, city: "New York" } 181 | 182 | 183 | ``` 184 | 185 | `Topics Covered:` 186 | Spread Operator 187 | 188 | **Hints:** 189 | - [Spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) 190 | 191 |
192 | Solution 193 | 194 | ### Let's look at the solution: 195 | 196 | ```javascript 197 | 198 | function combineObjects(obj1, obj2) { 199 | return { ...obj1, ...obj2 }; 200 | } 201 | 202 | console.log(combineObjects({ name: "Alice", age: 25 }, { age: 30, city: "New York" })); 203 | // Output: { name: "Alice", age: 30, city: "New York" } 204 | 205 | 206 | ``` 207 | 208 | **Explanation:** 209 | 210 | 211 | - The combineObjects function merges two objects into one. 212 | - Uses the spread operator (...) to copy all properties from obj1 and obj2. 213 | 214 |
215 | 216 | ---- 217 | ###### ` Question 5. Remove Duplicates from an Array` 218 | 219 | Write a program to remove duplicate elements from an array using the spread operator and a Set. A Set automatically eliminates duplicates, and the spread operator converts it back to an array. 220 | 221 | `Example:` 222 | 223 | ```javascript 224 | 225 | function removeDuplicates(arr) { 226 | 227 | // Your code here 228 | 229 | } 230 | 231 | console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); 232 | // Output: [1, 2, 3, 4, 5] 233 | 234 | 235 | ``` 236 | 237 | `Topics Covered:` 238 | Spread Operator 239 | 240 | **Hints:** 241 | - [Spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) 242 | 243 |
244 | Solution 245 | 246 | ### Let's look at the solution: 247 | 248 | ```javascript 249 | 250 | function removeDuplicates(arr) { 251 | return [...new Set(arr)]; 252 | } 253 | 254 | console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); 255 | // Output: [1, 2, 3, 4, 5] 256 | 257 | ``` 258 | 259 | **Explanation:** 260 | 261 | 262 | - The removeDuplicates function removes duplicate elements from an array. 263 | - Converts the array to a Set, which automatically removes duplicates, then spreads it back into a new array. 264 | 265 |
266 | 267 | ---- 268 | ###### ` Question 6. Split an Object into Two Objects` 269 | 270 | Write a program to split an object into two smaller objects using the spread operator. Specify which keys should belong to the first object and assign the remaining keys to the second object. 271 | 272 | `Example:` 273 | 274 | ```javascript 275 | 276 | function splitObject(obj, keys) { 277 | 278 | // Your code here 279 | 280 | } 281 | 282 | const original = { name: "Alice", age: 25, city: "New York", country: "USA" }; 283 | console.log(splitObject(original, ["name", "age"])); 284 | // Output: [{ name: "Alice", age: 25 }, { city: "New York", country: "USA" }] 285 | 286 | 287 | 288 | ``` 289 | 290 | `Topics Covered:` 291 | Spread Operator 292 | 293 | **Hints:** 294 | - [Spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) 295 | 296 |
297 | Solution 298 | 299 | ### Let's look at the solution: 300 | 301 | ```javascript 302 | 303 | function splitObject(obj, keys) { 304 | const obj1 = keys.reduce(function (acc, key) { 305 | return { ...acc, [key]: obj[key] }; 306 | }, {}); 307 | 308 | const obj2 = { ...obj }; 309 | keys.forEach(function (key) { 310 | delete obj2[key]; 311 | }); 312 | 313 | return [obj1, obj2]; 314 | } 315 | 316 | const original = { name: "Alice", age: 25, city: "New York", country: "USA" }; 317 | console.log(splitObject(original, ["name", "age"])); 318 | // Output: [{ name: "Alice", age: 25 }, { city: "New York", country: "USA" }] 319 | 320 | 321 | ``` 322 | 323 | **Explanation:** 324 | 325 | 326 | - The function creates obj1 with specified keys using reduce and removes these keys from obj2 using delete. 327 | - Output: Returns an array with two objects: one containing the selected keys (obj1) and the other with the remaining keys (obj2). 328 | 329 |
330 | 331 | ---- 332 | -------------------------------------------------------------------------------- /resources/Recursive_Functions/readme.md: -------------------------------------------------------------------------------- 1 | # Recursive Functions 2 | ###### ` Question 1. Render Navigation menu` 3 | 4 | Write a JavaScript function that shows the menu structure which contain title and url.The menu should display:Top-level items like "Home," "About," "Contact," etc.Nested submenus under categories like "Services," where each category can have its own submenus (e.g., "Web Development," "App Development"). 5 | 6 | `Example:` 7 | 8 | ```javascript 9 | 10 | // Function to generate the menu 11 | function generateMenu(menu) { 12 | 13 | // Your code here 14 | 15 | 16 | } 17 | 18 | // menu array 19 | const menu = [ 20 | { title: "Home", url: "/home" }, 21 | { title: "About", url: "/about" }, 22 | { title: "Services", url: "/services", submenu: [ 23 | { title: "Web Development", url: "/services/web-development" }, 24 | { title: "App Development", url: "/services/app-development", submenu: [ 25 | { title: "iOS", url: "/services/app-development/ios" }, 26 | { title: "Android", url: "/services/app-development/android" } 27 | ]} 28 | ] 29 | }, 30 | { title: "Contact", url: "/contact" } 31 | ]; 32 | 33 | // Generate the menu 34 | generateMenu(menu); 35 | 36 | 37 | ``` 38 | 39 | `Topics Covered:` 40 | Recursive function 41 | 42 | **Hints:** 43 | - [Recursion](https://www.programiz.com/javascript/recursion) 44 | 45 |
46 | Solution 47 | 48 | ### Let's look at the solution: 49 | 50 | ```javascript 51 | 52 | // Function to generate the menu 53 | function generateMenu(menu) { 54 | menu.forEach(function(item) { 55 | console.log('Title: ' + item.title + ', URL: ' + item.url); 56 | if (item.submenu) { 57 | generateMenu(item.submenu); // Recursive call for submenu items 58 | } 59 | }); 60 | } 61 | 62 | // Shortened menu array 63 | const menu = [ 64 | { title: "Home", url: "/home" }, 65 | { title: "About", url: "/about" }, 66 | { title: "Services", url: "/services", submenu: [ 67 | { title: "Web Development", url: "/services/web-development" }, 68 | { title: "App Development", url: "/services/app-development", submenu: [ 69 | { title: "iOS", url: "/services/app-development/ios" }, 70 | { title: "Android", url: "/services/app-development/android" } 71 | ]} 72 | ] 73 | }, 74 | { title: "Contact", url: "/contact" } 75 | ]; 76 | 77 | // Generate the menu 78 | generateMenu(menu); 79 | 80 | 81 | 82 | ``` 83 | 84 | **Explanation:** 85 | 86 | 87 | - Loops through the menu array and logs the title and url of each item. If an item has a submenu, it recursively calls generateMenu to handle the submenu items. 88 | - The function continues to recursively process any submenus in the menu array. 89 | 90 |
91 | 92 | ---- 93 | ###### ` Question 2. Parsing Nested Comments` 94 | 95 | Write a program in javascript where create and array of comments where each comments have id, text and reply and reply recursively contains many reply. 96 | 97 | `Example:` 98 | 99 | ```javascript 100 | 101 | // Function to display comments and their nested replies 102 | function displayComments(comments) { 103 | 104 | // Your code here 105 | 106 | } 107 | 108 | // Simplified comments array 109 | const comments = [ 110 | { id: 1, text: "First comment", replies: [ 111 | { id: 2, text: "Reply to first", replies: [ 112 | { id: 4, text: "Nested reply" } 113 | ]} 114 | ]}, 115 | { id: 3, text: "Another comment" } 116 | ]; 117 | 118 | // Call the function 119 | displayComments(comments); 120 | 121 | ``` 122 | 123 | `Topics Covered:` 124 | Recursive function 125 | 126 | **Hints:** 127 | - [Recursion](https://www.programiz.com/javascript/recursion) 128 | 129 |
130 | Solution 131 | 132 | ### Let's look at the solution: 133 | 134 | ```javascript 135 | 136 | // Function to display comments and their nested replies 137 | function displayComments(comments) { 138 | comments.forEach(function(comment) { 139 | console.log('ID: ' + comment.id + ', Text: ' + comment.text); 140 | if (comment.replies) { 141 | displayComments(comment.replies); // Recursive call for replies 142 | } 143 | }); 144 | } 145 | 146 | // Simplified comments array 147 | const comments = [ 148 | { id: 1, text: "First comment", replies: [ 149 | { id: 2, text: "Reply to first", replies: [ 150 | { id: 4, text: "Nested reply" } 151 | ]} 152 | ]}, 153 | { id: 3, text: "Another comment" } 154 | ]; 155 | 156 | // Call the function 157 | displayComments(comments); 158 | 159 | ``` 160 | 161 | **Explanation:** 162 | 163 | 164 | - Simplified Comments Array: Shortened the text values to make the array concise. 165 | - Reduced Function Verbosity: Removed unnecessary comments and repetitive formatting logic. 166 | 167 |
168 | 169 | ---- 170 | ###### ` Question 3. Array Traversal` 171 | 172 | Write a program in javascript where create a array category with attribute name and subcategory and subcategory further contain name.The printCategories function traverses each node in the tree-like structure. If a category has subcategories, it calls itself recursively to process those subcategories. 173 | 174 | `Example:` 175 | 176 | ```javascript 177 | 178 | const categories = [ 179 | { name: "Electronics", subcategories: [ 180 | { name: "Mobile Phones", subcategories: [ 181 | { name: "Smartphones" }, { name: "Feature Phones" } 182 | ]}, 183 | { name: "Laptops" } 184 | ]}, 185 | { name: "Clothing", subcategories: [ 186 | { name: "Men's" }, { name: "Women's" } 187 | ]} 188 | ]; 189 | 190 | function printCategories(categories) { 191 | 192 | // Your code here 193 | 194 | } 195 | 196 | printCategories(categories); 197 | 198 | ``` 199 | 200 | `Topics Covered:` 201 | Recursive function 202 | 203 | **Hints:** 204 | - [Recursion](https://www.programiz.com/javascript/recursion) 205 | 206 |
207 | Solution 208 | 209 | ### Let's look at the solution: 210 | 211 | ```javascript 212 | 213 | const categories = [ 214 | { name: "Electronics", subcategories: [ 215 | { name: "Mobile Phones", subcategories: [ 216 | { name: "Smartphones" }, { name: "Feature Phones" } 217 | ]}, 218 | { name: "Laptops" } 219 | ]}, 220 | { name: "Clothing", subcategories: [ 221 | { name: "Men's" }, { name: "Women's" } 222 | ]} 223 | ]; 224 | 225 | function printCategories(categories) { 226 | categories.forEach(category => { 227 | console.log(category.name); 228 | if (category.subcategories) printCategories(category.subcategories); 229 | }); 230 | } 231 | 232 | printCategories(categories); 233 | 234 | ``` 235 | 236 | **Explanation:** 237 | 238 | 239 | - The function recursively prints all categories and subcategories without any excess details. 240 | - Each category is an object with a name and an optional subcategories array containing more categories. 241 | - Recursive Function: For each category, the function: Prints the category's name. If the category has subcategories, the function is called recursively to print those as well. 242 | 243 |
244 | 245 | ---- 246 | ###### ` Question 4. Generating Combinations` 247 | 248 | Write a program in javascript where create the function generateSubsets recursively generates all subsets of the input array.It first handles the base case where the array is empty by returning an empty.Then it splits the problem by considering subsets both with and without the first element of the array. 249 | 250 | `Example:` 251 | 252 | ```javascript 253 | 254 | // Recursive function to generate all subsets of an array 255 | function generateSubsets(arr) { 256 | 257 | // Your code here 258 | 259 | } 260 | 261 | // Example usage 262 | const subsets = generateSubsets([1, 2, 3]); 263 | console.log(subsets); 264 | // Output: [ [], [ 3 ], [ 2 ], [ 2, 3 ], [ 1 ], [ 1, 3 ], [ 1, 2 ], [ 1, 2, 3 ] ] 265 | 266 | ``` 267 | 268 | `Topics Covered:` 269 | Recursive function 270 | 271 | **Hints:** 272 | - [Recursion](https://www.programiz.com/javascript/recursion) 273 | 274 |
275 | Solution 276 | 277 | ### Let's look at the solution: 278 | 279 | ```javascript 280 | 281 | // Recursive function to generate all subsets of an array 282 | function generateSubsets(arr) { 283 | if (arr.length === 0) { 284 | return [[]]; 285 | // Base case: return empty subset when array is empty 286 | } 287 | 288 | const firstElement = arr[0]; 289 | const remainingElements = arr.slice(1); 290 | 291 | // Get all subsets of the remaining array 292 | const subsetsWithoutFirst = generateSubsets(remainingElements); 293 | 294 | // Add the first element to each of the subsets 295 | const subsetsWithFirst = subsetsWithoutFirst.map(subset => [firstElement, ...subset]); 296 | 297 | // Return the combined subsets: with and without the first element 298 | return [...subsetsWithoutFirst, ...subsetsWithFirst]; 299 | } 300 | 301 | // Example usage 302 | const subsets = generateSubsets([1, 2, 3]); 303 | console.log(subsets); 304 | // Output: [ [], [ 3 ], [ 2 ], [ 2, 3 ], [ 1 ], [ 1, 3 ], [ 1, 2 ], [ 1, 2, 3 ] ] 305 | 306 | ``` 307 | 308 | **Explanation:** 309 | 310 | 311 | - The function recursively splits the array into subsets with and without the first element. 312 | - It combines these subsets and returns all possible subsets of the array. 313 | 314 |
315 | 316 | ---- 317 | -------------------------------------------------------------------------------- /resources/Sets/readme.md: -------------------------------------------------------------------------------- 1 | # Sets 2 | 3 | ###### ` Question 1. Add Unique Elements to a Set` 4 | 5 | Write a program to create a Set from an array to store only unique elements. This demonstrates how duplicates are automatically removed by the Set. 6 | 7 | `Example:` 8 | 9 | ```javascript 10 | 11 | function addUniqueElements(arr) { 12 | 13 | // Your Code here 14 | 15 | } 16 | console.log(addUniqueElements([1, 2, 2, 3, 4, 4, 5])); 17 | // Output: Set(5) {1, 2, 3, 4, 5} 18 | 19 | 20 | ``` 21 | 22 | `Topics Covered:` 23 | Sets, Array 24 | 25 | **Hints:** 26 | - [Sets](https://www.w3schools.com/js/js_sets.asp) 27 | - [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) 28 | 29 |
30 | Solution 31 | 32 | ### Let's look at the solution: 33 | 34 | ```javascript 35 | 36 | function addUniqueElements(arr) { 37 | return new Set(arr); 38 | } 39 | console.log(addUniqueElements([1, 2, 2, 3, 4, 4, 5])); 40 | // Output: Set(5) {1, 2, 3, 4, 5} 41 | 42 | ``` 43 | 44 | **Explanation:** 45 | 46 | 47 | - The function addUniqueElements takes an array (arr) and uses the Set object to remove duplicate elements. 48 | - A Set only stores unique values. By passing the array to the Set constructor, it automatically filters out duplicates. 49 | 50 |
51 | 52 | ---- 53 | ###### ` Question 2. Remove an Element from a Set` 54 | 55 | Write a program to remove a specific element from a Set using the delete() method and return the updated Set. 56 | 57 | `Example:` 58 | 59 | ```javascript 60 | 61 | function removeElement(mySet, element) { 62 | 63 | // Write your code here 64 | 65 | } 66 | const mySet = new Set([1, 2, 3, 4, 5]); 67 | console.log(removeElement(mySet, 3)); // Output: Set(4) {1, 2, 4, 5} 68 | 69 | 70 | ``` 71 | 72 | `Topics Covered:` 73 | delete() in Javascript Sets, Sets 74 | 75 | **Hints:** 76 | - [delete() in Javascript Sets](https://www.geeksforgeeks.org/javascript-set-delete-method/), - [Sets](https://www.w3schools.com/js/js_sets.asp) 77 | 78 |
79 | Solution 80 | 81 | ### Let's look at the solution: 82 | 83 | ```javascript 84 | 85 | function removeElement(mySet, element) { 86 | mySet.delete(element); 87 | return mySet; 88 | } 89 | const mySet = new Set([1, 2, 3, 4, 5]); 90 | console.log(removeElement(mySet, 3)); // Output: Set(4) {1, 2, 4, 91 | 92 | ``` 93 | 94 | **Explanation:** 95 | 96 | 97 | - The removeElement function deletes a specified element from the given Set (mySet) using the delete method. 98 | - mySet.delete(element) removes the value 3 from the Set. 99 | - The updated Set is returned, and the output becomes Set(4) {1, 2, 4, 5}. 100 | 101 |
102 | 103 | ---- 104 | ###### ` Question 3. Check if a Set Contains an Element` 105 | 106 | Write a program to check whether a Set contains a specific element using the has() method. Return true if it exists, otherwise false. 107 | 108 | `Example:` 109 | 110 | ```javascript 111 | 112 | function containsElement(mySet, element) { 113 | return mySet.has(element); 114 | } 115 | const mySet = new Set([1, 2, 3, 4, 5]); 116 | console.log(containsElement(mySet, 3)); // Output: true 117 | 118 | 119 | ``` 120 | 121 | `Topics Covered:` 122 | Sets 123 | 124 | **Hints:** 125 | - [Sets](https://www.w3schools.com/js/js_sets.asp) 126 | 127 |
128 | Solution 129 | 130 | ### Let's look at the solution: 131 | 132 | ```javascript 133 | 134 | function containsElement(mySet, element) { 135 | return mySet.has(element); 136 | } 137 | const mySet = new Set([1, 2, 3, 4, 5]); 138 | console.log(containsElement(mySet, 3)); // Output: true 139 | 140 | ``` 141 | 142 | **Explanation:** 143 | 144 | 145 | - The containsElement function checks if a specific element exists in the Set (mySet). 146 | - It uses the has method of Set, which returns true if the element is present, otherwise false. 147 | - For mySet = new Set([1, 2, 3, 4, 5]) and element = 3, mySet.has(3) evaluates to true. 148 | 149 |
150 | 151 | ---- 152 | ###### ` Question 4. Count Elements in a Set` 153 | 154 | Write a program to find the total number of elements in a Set using the size property. 155 | 156 | `Example:` 157 | 158 | ```javascript 159 | 160 | function countElements(mySet) { 161 | 162 | // Your Code here 163 | 164 | } 165 | const mySet = new Set([1, 2, 3, 4, 5]); 166 | console.log(countElements(mySet)); // Output: 5 167 | 168 | ``` 169 | 170 | `Topics Covered:` 171 | Sets 172 | 173 | **Hints:** 174 | - [Sets](https://www.w3schools.com/js/js_sets.asp) 175 | 176 |
177 | Solution 178 | 179 | ### Let's look at the solution: 180 | 181 | ```javascript 182 | 183 | function countElements(mySet) { 184 | return mySet.size; 185 | } 186 | const mySet = new Set([1, 2, 3, 4, 5]); 187 | console.log(countElements(mySet)); // Output: 5 188 | 189 | ``` 190 | 191 | **Explanation:** 192 | 193 | 194 | - The function countElements(mySet) returns mySet.size, which is 5. 195 | - console.log displays 5 as the output. 196 | 197 |
198 | 199 | ---- 200 | ###### ` Question 5. Convert a Set to an Array` 201 | 202 | Write a program to transform a Set into an array for further operations such as sorting or iteration. 203 | 204 | `Example:` 205 | 206 | ```javascript 207 | 208 | function convertSetToArray(mySet) { 209 | 210 | // Your Code here 211 | 212 | } 213 | const mySet = new Set([1, 2, 3, 4, 5]); 214 | console.log(convertSetToArray(mySet)); // Output: [1, 2, 3, 4, 5] 215 | 216 | ``` 217 | 218 | `Topics Covered:` 219 | Sets 220 | 221 | **Hints:** 222 | - [Sets](https://www.w3schools.com/js/js_sets.asp) 223 | 224 |
225 | Solution 226 | 227 | ### Let's look at the solution: 228 | 229 | ```javascript 230 | 231 | function convertSetToArray(mySet) { 232 | return [...mySet]; 233 | } 234 | const mySet = new Set([1, 2, 3, 4, 5]); 235 | console.log(convertSetToArray(mySet)); // Output: [1, 2, 3, 4, 5] 236 | 237 | ``` 238 | 239 | **Explanation:** 240 | 241 | 242 | - The spread operator (...) expands the elements of mySet into an array. 243 | - return [...mySet]; creates a new array containing all elements from mySet. 244 | 245 |
246 | 247 | ---- 248 | ###### ` Question 6. Find the Union of Two Sets` 249 | 250 | Write a program to combine two Sets into one, containing all unique elements from both Sets. 251 | 252 | `Example:` 253 | 254 | ```javascript 255 | 256 | 257 | function unionOfSets(setA, setB) { 258 | 259 | // Your code here 260 | 261 | } 262 | const setA = new Set([1, 2, 3]); 263 | const setB = new Set([3, 4, 5]); 264 | console.log(unionOfSets(setA, setB)); // Output: Set(5) {1, 2, 3, 4, 5} 265 | 266 | ``` 267 | 268 | `Topics Covered:` 269 | Sets 270 | 271 | **Hints:** 272 | - [Sets](https://www.w3schools.com/js/js_sets.asp) 273 | 274 |
275 | Solution 276 | 277 | ### Let's look at the solution: 278 | 279 | ```javascript 280 | 281 | 282 | function unionOfSets(setA, setB) { 283 | return new Set([...setA, ...setB]); 284 | } 285 | const setA = new Set([1, 2, 3]); 286 | const setB = new Set([3, 4, 5]); 287 | console.log(unionOfSets(setA, setB)); // Output: Set(5) {1, 2, 3, 4, 5} 288 | 289 | ``` 290 | 291 | **Explanation:** 292 | 293 | 294 | - The spread operator (...) merges their elements into [1, 2, 3, 3, 4, 5]. 295 | - new Set([...setA, ...setB]) removes duplicates, resulting in {1, 2, 3, 4, 5}. 296 | 297 |
298 | 299 | ---- 300 | ###### ` Question 7. Find the Intersection of Two Sets` 301 | 302 | Write a program to identify elements that are common to both Sets using the filter() and has() methods. 303 | 304 | `Example:` 305 | 306 | ```javascript 307 | 308 | function intersectionOfSets(setA, setB) { 309 | 310 | // Your Code here 311 | 312 | } 313 | const setA = new Set([1, 2, 3]); 314 | const setB = new Set([3, 4, 5]); 315 | console.log(intersectionOfSets(setA, setB)); // Output: Set(1) {3} 316 | 317 | ``` 318 | 319 | `Topics Covered:` 320 | Sets 321 | 322 | **Hints:** 323 | - [Sets](https://www.w3schools.com/js/js_sets.asp) 324 | 325 |
326 | Solution 327 | 328 | ### Let's look at the solution: 329 | 330 | ```javascript 331 | 332 | function intersectionOfSets(setA, setB) { 333 | return new Set([...setA].filter(item => setB.has(item))); 334 | } 335 | const setA = new Set([1, 2, 3]); 336 | const setB = new Set([3, 4, 5]); 337 | console.log(intersectionOfSets(setA, setB)); // Output: Set(1) {3} 338 | 339 | ``` 340 | 341 | **Explanation:** 342 | 343 | 344 | - Convert setA to an array and use .filter() to keep elements that exist in setB (common elements). 345 | - Wrap the result in new Set() to return a set with the intersection: {3}. 346 | 347 |
348 | 349 | ---- 350 | ###### ` Question 8. Find the Difference Between Two Sets` 351 | 352 | Write a program to find elements that are in one Set but not in the other. 353 | 354 | `Example:` 355 | 356 | ```javascript 357 | 358 | function differenceOfSets(setA, setB) { 359 | 360 | // Your Codde here 361 | 362 | } 363 | const setA = new Set([1, 2, 3]); 364 | const setB = new Set([3, 4, 5]); 365 | console.log(differenceOfSets(setA, setB)); // Output: Set(2) {1, 2} 366 | 367 | ``` 368 | 369 | `Topics Covered:` 370 | Sets 371 | 372 | **Hints:** 373 | - [Sets](https://www.w3schools.com/js/js_sets.asp) 374 | 375 |
376 | Solution 377 | 378 | ### Let's look at the solution: 379 | 380 | ```javascript 381 | 382 | function differenceOfSets(setA, setB) { 383 | return new Set([...setA].filter(item => !setB.has(item))); 384 | } 385 | const setA = new Set([1, 2, 3]); 386 | const setB = new Set([3, 4, 5]); 387 | console.log(differenceOfSets(setA, setB)); // Output: Set(2) {1, 2} 388 | 389 | ``` 390 | 391 | **Explanation:** 392 | 393 | 394 | - Convert setA to an array and use .filter() to keep elements that are not in setB. 395 | - Wrap the result in new Set() to return a set with the difference: {1, 2}. 396 | 397 |
398 | 399 | ---- 400 | -------------------------------------------------------------------------------- /resources/Type_Conversion/readme.md: -------------------------------------------------------------------------------- 1 | # Type Conversion 2 | ###### ` Question 1:Age Validation` 3 | 4 | Write a program in javascript.where User input age as a string in variable ageInput. Write a program to check whether the input age is valid or not. 5 | 6 | `Example:` 7 | 8 | ```javascript 9 | 10 | function validateAge(ageInput) { 11 | //code here 12 | } 13 | 14 | // Example usage 15 | let ageInput = "25"; // User input as a string 16 | validateAge(ageInput); 17 | 18 | 19 | 20 | ``` 21 | 22 | `Topics Covered:` 23 | String parseInt() method 24 | 25 | **Hints:** 26 | - [parseInt()](https://www.w3schools.com/jsref/jsref_parseint.asp#:~:text=The%20parseInt%20method%20parses%20a,omitted%2C%20JavaScript%20assumes%20radix%2010.) 27 | 28 |
29 | Solution 30 | 31 | ### Let's look at the solution: 32 | 33 | ```javascript 34 | 35 | function validateAge(ageInput) { 36 | // Convert the input to an integer 37 | let age = parseInt(ageInput, 10); 38 | 39 | // Check if the age is a valid number and at least 18 40 | if (isNaN(age) || age < 18) { 41 | console.log("Age must be a number and at least 18."); 42 | } else { 43 | console.log("Age is valid."); 44 | } 45 | } 46 | 47 | // Example usage 48 | let ageInput = "25"; // User input as a string 49 | validateAge(ageInput); 50 | 51 | ``` 52 | 53 | **Explanation:** 54 | 55 | The validateAge function converts the input string to an integer and checks if it's a valid number and at least 18. 56 | -If not, it logs an error message, otherwise, it confirms that the age is valid. 57 | 58 |
59 | 60 | ---- 61 | ###### ` Question 2:Phone Number Validation` 62 | 63 | Write a program in javaScript where take a phone number as a input in variable phoneInput. Write a logic to validate weather the phone number is valid or not. 64 | 65 | `Example:` 66 | 67 | ```javascript 68 | 69 | function validatePhoneNumber(phoneInput) { 70 | //code here 71 | } 72 | 73 | // Example usage: 74 | let phoneInput = " 555-123-4567 "; 75 | validatePhoneNumber(phoneInput); 76 | 77 | 78 | 79 | ``` 80 | 81 | `Topics Covered:` 82 | String() method 83 | 84 | **Hints:** 85 | - [String()](https://www.w3schools.com/js/js_string_methods.asp) 86 | 87 |
88 | Solution 89 | 90 | ### Let's look at the solution: 91 | 92 | ```javascript 93 | 94 | // Convert to string and remove non-numeric characters 95 | let cleanedPhoneNumber = String(phoneInput).replace(/D/g, ''); 96 | 97 | // Ensure the phone number has exactly 10 digits 98 | if (cleanedPhoneNumber.length === 10) { 99 | console.log("Valid phone number:", cleanedPhoneNumber); // "5551234567" 100 | } else { 101 | console.log("Invalid phone number format"); 102 | } 103 | 104 | 105 | ``` 106 | 107 | **Explanation:** 108 | 109 | 110 | -If valid, prints the cleaned number ("5551234567")., 111 | -If invalid, prints "Invalid phone number format". 112 | 113 |
114 | 115 | ---- 116 | ###### ` Question 3:API Response Conversion` 117 | 118 | Write a program in javaScript where declare a object apiResponse which return a variable productId of integer type, productName string type, price string type, available boolean type.Write a program to convert the price from string to number.Formate price as a currency. 119 | 120 | `Example:` 121 | 122 | ```javascript 123 | 124 | function formatPriceFromApiResponse(apiResponse) { 125 | //code here 126 | } 127 | 128 | // Example usage: 129 | const apiResponse = { 130 | productId: 12345, 131 | productName: "Laptop", 132 | price: "999.99", // Price returned as a string 133 | available: true 134 | }; 135 | 136 | console.log(formatPriceFromApiResponse(apiResponse)); // "$999.99" 137 | 138 | 139 | 140 | 141 | ``` 142 | 143 | `Topics Covered:` 144 | parseFloat, toFixed() 145 | 146 | **Hints:** 147 | - [parseFloat()](https://www.w3schools.com/jsref/jsref_parsefloat.asp) 148 | 149 |
150 | Solution 151 | 152 | ### Let's look at the solution: 153 | 154 | ```javascript 155 | 156 | function formatPriceFromApiResponse(apiResponse) { 157 | // Convert the price from string to number 158 | const priceAsNumber = parseFloat(apiResponse.price); 159 | 160 | // Format price as a currency string 161 | const formattedPrice = `$${priceAsNumber.toFixed(2)}`; // Correct usage 162 | 163 | return formattedPrice; 164 | } 165 | 166 | // Example usage: 167 | const apiResponse = { 168 | productId: 12345, 169 | productName: "Laptop", 170 | price: "999.99", // Price returned as a string 171 | available: true 172 | }; 173 | 174 | console.log(formatPriceFromApiResponse(apiResponse)); // "$999.99" 175 | 176 | 177 | 178 | ``` 179 | 180 | **Explanation:** 181 | 182 | 183 | -The function formatPriceFromApiResponse converts the price from a string to a number using parseFloat() and formats it as a currency string with two decimal places using toFixed(2). 184 | -It then returns the formatted price prefixed with a dollar sign ($). 185 | 186 |
187 | 188 | ###### `Question 4:Storing Objects in Local Storage` 189 | 190 | Write a program in javaScript where declare a object with variable name, age and write a program to convert it into JSON string and store it in localstorage. 191 | 192 | `Example:` 193 | 194 | ```javascript 195 | 196 | function storeUserData(user) { 197 | //code here 198 | } 199 | 200 | // Example usage: 201 | let user = { name: "Alice", age: 30 }; 202 | storeUserData(user); 203 | 204 | 205 | 206 | ``` 207 | 208 | `Topics Covered:` 209 | String, stringify() 210 | 211 | **Hints:** 212 | - [stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) 213 | 214 |
215 | Solution 216 | 217 | ### Let's look at the solution: 218 | 219 | ```javascript 220 | 221 | function storeUserData(user) { 222 | // Convert the user object to a JSON string 223 | let userJson = JSON.stringify(user); 224 | 225 | // Store the JSON string in localStorage 226 | localStorage.setItem("user", userJson); 227 | 228 | console.log("User data stored in local storage."); 229 | } 230 | 231 | // Example usage: 232 | let user = { name: "Alice", age: 30 }; 233 | storeUserData(user); 234 | 235 | 236 | 237 | ``` 238 | 239 | **Explanation:** 240 | 241 | 242 | -storeUserData(user): This function accepts a user object, converts it into a JSON string using JSON.stringify(), 243 | and stores it in the browser's localStorage using setItem(). 244 | 245 |
246 | 247 | ---- 248 | 249 | ###### ` Question 5:Converting a Date Object to String` 250 | 251 | Write a program in javaScript where create a variable currentDate and declare the current date by using Date constructor.Write a program to convert the date in string formate 252 | 253 | `Example:` 254 | 255 | ```javascript 256 | 257 | function getCurrentDateString() { 258 | //code here 259 | } 260 | 261 | // Example usage: 262 | console.log(getCurrentDateString()); 263 | 264 | 265 | 266 | 267 | ``` 268 | 269 | `Topics Covered:` 270 | String, toString() 271 | 272 | **Hints:** 273 | - [toString()](https://www.w3schools.com/jsref/jsref_tostring_string.asp) 274 | 275 |
276 | Solution 277 | 278 | ### Let's look at the solution: 279 | 280 | ```javascript 281 | 282 | function getCurrentDateString() { 283 | // Get the current date and time 284 | let currentDate = new Date(); 285 | 286 | // Convert the current date to a string 287 | let currentDateString = currentDate.toString(); 288 | 289 | // Return the string representation of the current date 290 | return currentDateString; 291 | } 292 | 293 | // Example usage: 294 | console.log(getCurrentDateString()); 295 | 296 | 297 | 298 | 299 | ``` 300 | 301 | **Explanation:** 302 | 303 | 304 | -getCurrentDateString(): This function creates a new Date object to get the current date and time, 305 | converts it into a string using .toString(), and then returns the string. 306 | 307 |
308 | 309 | ---- 310 | ###### ` Question 6:Displaying a List of Users` 311 | 312 | Create an array of user objects, each containing name (string) age (number)email (string) Iterate through the array and display the user information in a formatted manner. 313 | 314 | `Example:` 315 | 316 | ```javascript 317 | 318 | // List of users 319 | const users = [ 320 | { name: "John Doe", age: 30,email: "john.doe@example.com" }, 321 | { name: "Jane Smith", age: 25,email: "jane.smith@example.com" }, 322 | { name: "Alice Johnson", age: 35,email: "alice.johnson@example.com" }, 323 | { name: "Bob Brown", age: 40, email: "bob.brown@example.com" } 324 | ]; 325 | 326 | // Function to display users 327 | function displayUsers(users) { 328 | //code here 329 | }; 330 | // Call the function to display users 331 | displayUsers(users); 332 | 333 | 334 | ``` 335 | 336 | `Topics Covered:` 337 | String 338 | 339 | **Hints:** 340 | - [String()](https://www.w3schools.com/js/js_type_conversion.asp) 341 | 342 |
343 | Solution 344 | 345 | ### Let's look at the solution: 346 | 347 | ```javascript 348 | 349 | // List of users 350 | const users = [ 351 | { name: "John Doe", age: 30,email: "john.doe@example.com" }, 352 | { name: "Jane Smith", age: 25,email: "jane.smith@example.com" }, 353 | { name: "Alice Johnson", age: 35,email: "alice.johnson@example.com" }, 354 | { name: "Bob Brown", age: 40, email: "bob.brown@example.com" } 355 | ]; 356 | 357 | // Function to display users 358 | function displayUsers(users) { 359 | console.log("List of Users:"); 360 | users.forEach((user, index) => { 361 | console.log(index + 1}:); 362 | console.log(user.name); 363 | console.log(user.age); 364 | console.log(user.email); 365 | console.log("------------------------"); 366 | }); 367 | } 368 | 369 | // Call the function to display users 370 | displayUsers(users); 371 | 372 | 373 | 374 | 375 | 376 | ``` 377 | 378 | **Explanation:** 379 | 380 | 381 | -The displayUsers function iterates over the users array and logs each user's name, age, and email to the console. 382 | - It formats the output with a label for each user and separates them with a dashed line. 383 | 384 |
385 | 386 | ---- 387 | -------------------------------------------------------------------------------- /resources/Destructuring/readme.md: -------------------------------------------------------------------------------- 1 | # Destructuring 2 | ###### ` Question 1. Extract Values from an Array` 3 | 4 | Write a program to extract specific values from an array using destructuring. For a given array, extract the first and third elements into separate variables. 5 | 6 | `Example:` 7 | 8 | ```javascript 9 | 10 | function getElements(arr) { 11 | 12 | // YOur code here 13 | 14 | } 15 | 16 | const arr = [10, 20, 30, 40, 50]; 17 | const { first, third } = getElements(arr); 18 | 19 | console.log(first); // Output: 10 20 | console.log(third); // Output: 30 21 | 22 | 23 | ``` 24 | 25 | `Topics Covered:` 26 | Destructuring in JS 27 | 28 | **Hints:** 29 | - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/) 30 | - [Array and Object destructuring](https://www.honeybadger.io/blog/javascript-destructuring/) 31 | 32 |
33 | Solution 34 | 35 | ### Let's look at the solution: 36 | 37 | ```javascript 38 | 39 | function getElements(arr) { 40 | const [first, , third] = arr; 41 | return { first, third }; 42 | } 43 | 44 | const arr = [10, 20, 30, 40, 50]; 45 | const { first, third } = getElements(arr); 46 | 47 | console.log(first); // Output: 10 48 | console.log(third); // Output: 30 49 | 50 | ``` 51 | 52 | **Explanation:** 53 | 54 | 55 | - The getElements function extracts specific elements (first and third) from the array using destructuring. 56 | - Destructuring is applied to assign first and third while skipping the second element using a comma. 57 | 58 | 59 |
60 | 61 | ---- 62 | ###### ` Question 2. Swap Two Variables` 63 | 64 | Write a program to swap the values of two variables using array destructuring. The program should not use a temporary variable for swapping. 65 | 66 | `Example:` 67 | 68 | ```javascript 69 | 70 | function swapValues(a, b) { 71 | 72 | // Your code here 73 | 74 | } 75 | 76 | let a = 5, b = 10; 77 | [a, b] = swapValues(a, b); 78 | 79 | console.log(a); // Output: 10 80 | console.log(b); // Output: 5 81 | 82 | ``` 83 | 84 | `Topics Covered:` 85 | Destructuring in JS 86 | 87 | **Hints:** 88 | - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/) 89 | 90 |
91 | Solution 92 | 93 | ### Let's look at the solution: 94 | 95 | ```javascript 96 | 97 | function swapValues(a, b) { 98 | return [b, a]; 99 | } 100 | 101 | let a = 5, b = 10; 102 | [a, b] = swapValues(a, b); 103 | 104 | console.log(a); // Output: 10 105 | console.log(b); // Output: 5 106 | 107 | ``` 108 | 109 | **Explanation:** 110 | 111 | 112 | - The swapValues function takes two parameters a and b and returns them in reversed order. 113 | - The function returns an array [b, a] to swap the values of a and b. 114 | 115 | 116 |
117 | 118 | ---- 119 | ###### ` Question 3. Extract Properties from an Object` 120 | 121 | Write a program to extract specific properties from an object using destructuring. Given an object, extract the name and age properties into variables. 122 | 123 | `Example:` 124 | 125 | ```javascript 126 | 127 | function getPersonDetails(person) { 128 | 129 | // Your code here 130 | 131 | } 132 | 133 | const person = { name: "Alice", age: 25, city: "New York" }; 134 | const { name, age } = getPersonDetails(person); 135 | 136 | console.log(name); // Output: Alice 137 | console.log(age); // Output: 25 138 | 139 | 140 | ``` 141 | 142 | `Topics Covered:` 143 | Destructuring in JS 144 | 145 | **Hints:** 146 | - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/), - [Object Destructuring](https://www.javascripttutorial.net/javascript-object-destructuring/) 147 | 148 |
149 | Solution 150 | 151 | ### Let's look at the solution: 152 | 153 | ```javascript 154 | 155 | function getPersonDetails(person) { 156 | const { name, age } = person; 157 | return { name, age }; 158 | } 159 | 160 | const person = { name: "Alice", age: 25, city: "New York" }; 161 | const { name, age } = getPersonDetails(person); 162 | 163 | console.log(name); // Output: Alice 164 | console.log(age); // Output: 25 165 | 166 | ``` 167 | 168 | **Explanation:** 169 | 170 | 171 | - The getPersonDetails function extracts the name and age properties from the person object using destructuring. 172 | - Destructuring is applied inside the function to extract the required properties. 173 | 174 | 175 |
176 | 177 | ---- 178 | ###### ` Question 4. Default Values in Destructuring` 179 | 180 | Write a program to use default values in destructuring. If the property or element does not exist, assign a default value. Extract a name and gender from the object, with gender defaulting to "Unknown". 181 | 182 | `Example:` 183 | 184 | ```javascript 185 | 186 | function getPersonDetails(person) { 187 | 188 | // Your code here 189 | 190 | } 191 | 192 | const person = { name: "Bob", age: 30 }; 193 | const { name, gender } = getPersonDetails(person); 194 | 195 | console.log(name); // Output: Bob 196 | console.log(gender); // Output: Unknown 197 | 198 | 199 | ``` 200 | 201 | `Topics Covered:` 202 | Destructuring in JS 203 | 204 | **Hints:** 205 | - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/), - [Object Destructuring](https://www.javascripttutorial.net/javascript-object-destructuring/) 206 | 207 |
208 | Solution 209 | 210 | ### Let's look at the solution: 211 | 212 | ```javascript 213 | 214 | function getPersonDetails(person) { 215 | const { name, gender = "Unknown" } = person; 216 | return { name, gender }; 217 | } 218 | 219 | const person = { name: "Bob", age: 30 }; 220 | const { name, gender } = getPersonDetails(person); 221 | 222 | console.log(name); // Output: Bob 223 | console.log(gender); // Output: Unknown 224 | 225 | ``` 226 | 227 | **Explanation:** 228 | 229 | 230 | - The getPersonDetails function extracts name and gender from the person object, providing a default value for gender if it's not present. 231 | - Destructuring is used to extract name and provide a default value "Unknown" for gender. 232 | 233 | 234 |
235 | 236 | ---- 237 | ###### ` Question 5. Nested Object Destructuring` 238 | 239 | Write a program to extract values from a nested object using destructuring. For a given object, extract the city property of the address. 240 | 241 | `Example:` 242 | 243 | ```javascript 244 | 245 | function getPersonDetails(person) { 246 | 247 | // Your code here 248 | 249 | } 250 | 251 | const person = { name: "Bob", age: 30 }; 252 | const { name, gender } = getPersonDetails(person); 253 | 254 | console.log(name); // Output: Bob 255 | console.log(gender); // Output: Unknown 256 | 257 | 258 | 259 | ``` 260 | 261 | `Topics Covered:` 262 | Destructuring in JS 263 | 264 | **Hints:** 265 | - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/), - [Object Destructuring](https://www.javascripttutorial.net/javascript-object-destructuring/) 266 | 267 |
268 | Solution 269 | 270 | ### Let's look at the solution: 271 | 272 | ```javascript 273 | 274 | function getPersonDetails(person) { 275 | const { name, gender = "Unknown" } = person; 276 | return { name, gender }; 277 | } 278 | 279 | const person = { name: "Bob", age: 30 }; 280 | const { name, gender } = getPersonDetails(person); 281 | 282 | console.log(name); // Output: Bob 283 | console.log(gender); // Output: Unknown 284 | 285 | ``` 286 | 287 | **Explanation:** 288 | 289 | 290 | - The getPersonDetails function extracts name and gender from the person object, providing a default value for gender if it's not present. 291 | - Destructuring is used to extract name and provide a default value "Unknown" for gender. 292 | 293 | 294 |
295 | 296 | ---- 297 | ###### ` Question 6. Rest Operator in Array Destructuring` 298 | 299 | Write a program to extract values from a nested object using destructuring. For a given object, extract the city property of the address. 300 | 301 | `Example:` 302 | 303 | ```javascript 304 | 305 | function splitArray(arr) { 306 | 307 | // Your code here 308 | 309 | } 310 | 311 | const arr = [1, 2, 3, 4, 5]; 312 | const { first, second, rest } = splitArray(arr); 313 | 314 | console.log(first, second); // Output: 1 2 315 | console.log(rest); // Output: [3, 4, 5] 316 | 317 | 318 | 319 | 320 | ``` 321 | 322 | `Topics Covered:` 323 | Destructuring in JS, Rest 324 | 325 | **Hints:** 326 | - [Rest](https://www.geeksforgeeks.org/javascript-rest-operator/), - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/) 327 | 328 |
329 | Solution 330 | 331 | ### Let's look at the solution: 332 | 333 | ```javascript 334 | 335 | function splitArray(arr) { 336 | const [first, second, ...rest] = arr; 337 | return { first, second, rest }; 338 | } 339 | 340 | const arr = [1, 2, 3, 4, 5]; 341 | const { first, second, rest } = splitArray(arr); 342 | 343 | console.log(first, second); // Output: 1 2 344 | console.log(rest); // Output: [3, 4, 5] 345 | 346 | ``` 347 | 348 | **Explanation:** 349 | 350 | 351 | - The splitArray function uses destructuring to extract first and second elements from the array, and gathers the remaining elements into rest. 352 | - The function splits the array into specific elements (first, second) and collects the rest into a new array (rest). 353 | 354 | 355 |
356 | 357 | ---- 358 | ###### ` Question 7. Function Parameter Destructuring` 359 | 360 | Write a program to destructure an object directly in a function’s parameters. Create a function that takes an object and extracts its name and age properties for use within the function. 361 | 362 | `Example:` 363 | 364 | ```javascript 365 | 366 | function displayInfo(person) { 367 | 368 | // Your code here 369 | 370 | } 371 | 372 | displayInfo({ name: "Charlie", age: 35, city: "London" }); 373 | // Output: Name: Charlie, Age: 35 374 | 375 | 376 | ``` 377 | 378 | `Topics Covered:` 379 | Destructuring in JS, Rest 380 | 381 | **Hints:** 382 | - [Rest](https://www.geeksforgeeks.org/javascript-rest-operator/), - [Destructuring](https://www.geeksforgeeks.org/destructuring-assignment-in-javascript/) 383 | 384 |
385 | Solution 386 | 387 | ### Let's look at the solution: 388 | 389 | ```javascript 390 | 391 | function displayInfo(person) { 392 | console.log("Name: " + person.name + ", Age: " + person.age); 393 | } 394 | 395 | displayInfo({ name: "Charlie", age: 35, city: "London" }); 396 | // Output: Name: Charlie, Age: 35 397 | 398 | 399 | ``` 400 | 401 | **Explanation:** 402 | 403 | 404 | - The displayInfo function takes an object person and accesses name and age properties to log them. 405 | - The + operator is used to concatenate the string and variables. 406 | 407 |
408 | 409 | ---- 410 | -------------------------------------------------------------------------------- /resources/Constructor_Function/readme.md: -------------------------------------------------------------------------------- 1 | # Constructor Function 2 | 3 | ###### ` Question 1: ChatMessage Constructor` 4 | 5 | Write a ChatMessage constructor function to represent messages in a chat app. Each message should have text, sender, and timestamp. Add a method formatMessage() to return a formatted string. 6 | 7 | `Example:` 8 | 9 | ```javascript 10 | 11 | function ChatMessage(text, sender, timestamp) { 12 | //Your code here 13 | } 14 | 15 | // Example Usage: 16 | const message = new ChatMessage("Hello!", "Deepak", new Date()); 17 | console.log(message.formatMessage()); // Output: Deepak [10:30 AM]: Hello! 18 | 19 | 20 | 21 | ``` 22 | 23 | `Topics Covered:` 24 | Constructor function, Date & time 25 | 26 | **Hints:** 27 | - [Constructor function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function), - [Date & time](https://www.w3schools.com/js/js_dates.asp) 28 | 29 |
30 | Solution 31 | 32 | ### Let's look at the solution: 33 | 34 | ```javascript 35 | 36 | function ChatMessage(text, sender, timestamp) { 37 | this.text = text; 38 | this.sender = sender; 39 | this.timestamp = timestamp; 40 | 41 | this.formatMessage = function () { 42 | const formattedTime = this.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); 43 | return `${this.sender} [${formattedTime}]: ${this.text}`; 44 | }; 45 | } 46 | 47 | // Example Usage: 48 | const message = new ChatMessage("Hello!", "Deepak", new Date()); 49 | console.log(message.formatMessage()); // Output: Deepak [10:30 AM]: Hello! 50 | 51 | 52 | ``` 53 | 54 | **Explanation:** 55 | 56 | ### Purpose 57 | Represents a chat message with text, sender, and timestamp. 58 | 59 | ### Steps 60 | 61 | 1. **ChatMessage Constructor Initializes:** 62 | - text: Message content. 63 | - sender: Message sender. 64 | - timestamp: Time of the message. 65 | 66 | 2. **formatMessage() Formats the Message as:** 67 | - Sender [Time]: Message. 68 | 69 | ### Example 70 | 71 | Creates a message object and logs the formatted message. 72 | 73 | **Output:** 74 | Deepak [10:30 AM]: Hello! 75 | 76 | 77 |
78 | 79 | ---- 80 | ###### ` Question 2: Real-Time Voting System` 81 | 82 | Create a Poll constructor function for a voting system. Each poll has a question, an array of options, and an object votes to track votes for each option. Add methods vote(option) to increment votes and getResults() to return the voting results. 83 | 84 | `Example:` 85 | 86 | ```javascript 87 | 88 | function Poll(question, options) { 89 | //Your code here 90 | } 91 | 92 | // Example Usage: 93 | const poll = new Poll("What's your favorite language?", ["JavaScript", "Python", "Java"]); 94 | poll.vote("JavaScript"); 95 | poll.vote("JavaScript"); 96 | poll.vote("Python"); 97 | console.log(poll.getResults()); // Output: { JavaScript: 2, Python: 1, Java: 0 } 98 | 99 | 100 | 101 | ``` 102 | 103 | `Topics Covered:` 104 | Constructor function 105 | 106 | **Hints:** 107 | - [Constructor function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) 108 | 109 |
110 | Solution 111 | 112 | ### Let's look at the solution: 113 | 114 | ```javascript 115 | 116 | function Poll(question, options) { 117 | this.question = question; 118 | this.options = options; 119 | this.votes = {}; 120 | 121 | // Initialize vote counts for each option 122 | options.forEach(option => { 123 | this.votes[option] = 0; 124 | }); 125 | 126 | this.vote = function (option) { 127 | if (this.votes.hasOwnProperty(option)) { 128 | this.votes[option]++; 129 | } 130 | }; 131 | 132 | this.getResults = function () { 133 | return this.votes; 134 | }; 135 | } 136 | 137 | // Example Usage: 138 | const poll = new Poll("What's your favorite language?", ["JavaScript", "Python", "Java"]); 139 | poll.vote("JavaScript"); 140 | poll.vote("JavaScript"); 141 | poll.vote("Python"); 142 | console.log(poll.getResults()); // Output: { JavaScript: 2, Python: 1, Java: 0 } 143 | 144 | 145 | ``` 146 | 147 | **Explanation:** 148 | 149 | 150 | ### Purpose: 151 | Represents a poll with a question, options, and votes. 152 | 153 | ### Steps: 154 | 155 | ### Poll Constructor Initializes: 156 | - question: The poll's question. 157 | - options: Array of answer options. 158 | - votes: An object to track votes for each option, initialized to 0. 159 | 160 | ### vote(option): 161 | - Increments the vote count for the specified option if it exists. 162 | 163 | ### getResults(): 164 | - Returns the current vote counts for all options. 165 | 166 | 167 |
168 | 169 | ---- 170 | ###### ` Question 3: Multi-Language Translator` 171 | 172 | Write a Translator constructor function that takes an object translations (key-value pairs of language codes and messages). Add a method translate(languageCode) that returns the message in the requested language. 173 | 174 | `Example:` 175 | 176 | ```javascript 177 | 178 | function Translator(translations) { 179 | //Your code here 180 | } 181 | 182 | // Example Usage: 183 | const translator = new Translator({ en: "Hello", es: "Hola", fr: "Bonjour" }); 184 | console.log(translator.translate("es")); // Output: Hola 185 | console.log(translator.translate("de")); // Output: Translation not available 186 | 187 | 188 | ``` 189 | 190 | `Topics Covered:` 191 | Constructor function 192 | 193 | **Hints:** 194 | - [Constructor function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) 195 | 196 |
197 | Solution 198 | 199 | ### Let's look at the solution: 200 | 201 | ```javascript 202 | 203 | function Translator(translations) { 204 | this.translations = translations; 205 | 206 | this.translate = function (languageCode) { 207 | return this.translations[languageCode] || "Translation not available"; 208 | }; 209 | } 210 | 211 | // Example Usage: 212 | const translator = new Translator({ en: "Hello", es: "Hola", fr: "Bonjour" }); 213 | console.log(translator.translate("es")); // Output: Hola 214 | console.log(translator.translate("de")); // Output: Translation not available 215 | 216 | 217 | ``` 218 | 219 | **Explanation:** 220 | 221 | 222 | ### Purpose 223 | Represents a translator that provides translations for different languages. 224 | 225 | ### Constructor 226 | Initializes with a translations object containing language codes and their corresponding translations. 227 | 228 | ### Parameters: 229 | - translations: An object where the keys are language codes (e.g., "en" for English, "es" for Spanish) and the values are their respective translations. 230 | 231 | ### Methods 232 | 233 | ### translate(languageCode) 234 | - **Purpose**: Returns the translation for the specified languageCode. 235 | - **Parameters**: 236 | - languageCode: The language code for which the translation is needed (e.g., "en" for English, "es" for Spanish). 237 | - **Returns**: 238 | - The translation for the given languageCode. 239 | - If the language code is not available, it returns "Translation not available.". 240 | 241 | 242 |
243 | 244 | ---- 245 | ###### ` Question 4: Notification Constructor with Priority` 246 | 247 | Write a Notification constructor function for a messaging system. Each notification has message, timestamp, and priority (e.g., "low", "high"). Add a method isHighPriority() to return true if the priority is "high". 248 | 249 | `Example:` 250 | 251 | ```javascript 252 | 253 | function Notification(message, timestamp, priority) { 254 | //Your code here 255 | } 256 | 257 | // Example Usage: 258 | const notification = new Notification("New comment received!", new Date(), "high"); 259 | console.log(notification.isHighPriority()); // Output: true 260 | 261 | 262 | ``` 263 | 264 | `Topics Covered:` 265 | Constructor function 266 | 267 | **Hints:** 268 | - [Constructor function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) 269 | 270 |
271 | Solution 272 | 273 | ### Let's look at the solution: 274 | 275 | ```javascript 276 | 277 | function Notification(message, timestamp, priority) { 278 | this.message = message; 279 | this.timestamp = timestamp; 280 | this.priority = priority; 281 | 282 | this.isHighPriority = function () { 283 | return this.priority === "high"; 284 | }; 285 | } 286 | 287 | // Example Usage: 288 | const notification = new Notification("New comment received!", new Date(), "high"); 289 | console.log(notification.isHighPriority()); // Output: true 290 | 291 | 292 | ``` 293 | 294 | **Explanation:** 295 | 296 | 297 | ### Purpose 298 | Defines a Notification object with a message, timestamp, and priority level. 299 | 300 | ### Constructor 301 | 302 | - message: The notification message (e.g., "New comment received!"). 303 | - timestamp: The time when the notification was created. 304 | - priority: The priority level of the notification (e.g., "high", "low"). 305 | 306 | ### Methods 307 | 308 | ### isHighPriority() 309 | - **Purpose**: Checks if the notification has a high priority. 310 | - **Returns**: true if the priority is "high", otherwise false. 311 | 312 |
313 | 314 | ---- 315 | ###### ` Question 5: Multi-Level Dropdown Menu` 316 | 317 | Create a Dropdown constructor function for multi-level dropdown menus. Each menu has label, items (array of submenus or options), and isOpen. Add methods toggle() to open/close the dropdown and render() to display the menu structure. 318 | 319 | `Example:` 320 | 321 | ```javascript 322 | 323 | function Dropdown(label, items) { 324 | //Your code here 325 | } 326 | 327 | // Example Usage: 328 | const dropdown = new Dropdown("File", ["New", { label: "Open", items: ["Recent", "Browse"] }]); 329 | dropdown.toggle(); 330 | dropdown.render(); 331 | // Output: 332 | // File (Open) 333 | // - New 334 | // - Open 335 | // - Recent 336 | // - Browse 337 | 338 | 339 | ``` 340 | 341 | `Topics Covered:` 342 | Constructor function, Array methods i.e forEach() 343 | 344 | **Hints:** 345 | - [Constructor function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function), - [Array methods i.e forEach()](https://www.w3schools.com/js/js_array_iteration.asp) 346 | 347 |
348 | Solution 349 | 350 | ### Let's look at the solution: 351 | 352 | ```javascript 353 | 354 | function Dropdown(label, items) { 355 | this.label = label; 356 | this.items = items; 357 | this.isOpen = false; 358 | 359 | this.toggle = function () { 360 | this.isOpen = !this.isOpen; 361 | }; 362 | 363 | this.render = function () { 364 | console.log(`${this.label} (${this.isOpen ? "Open" : "Closed"})`);; 365 | if (this.isOpen) { 366 | this.items.forEach(item => { 367 | if (typeof item === "string") { 368 | console.log(`- ${item}`); 369 | } else { 370 | console.log(`- ${item.label}`); 371 | if (item.items) { 372 | item.items.forEach(subItem => console.log(` - ${subItem}`)); 373 | } 374 | } 375 | }); 376 | } 377 | }; 378 | } 379 | 380 | // Example Usage: 381 | const dropdown = new Dropdown("File", ["New", { label: "Open", items: ["Recent", "Browse"] }]); 382 | dropdown.toggle(); 383 | dropdown.render(); 384 | 385 | ``` 386 | 387 | **Explanation:** 388 | 389 | 390 | ### Purpose 391 | Defines a Dropdown object with a label, a list of items, and an open/closed state. 392 | 393 | ### Constructor 394 | 395 | - label: The label displayed for the dropdown (e.g., "File"). 396 | - items: The list of items in the dropdown, which can be strings or objects (with sub-items). 397 | - isOpen: A boolean that tracks whether the dropdown is open or closed (initially set to false). 398 | 399 | ### Methods 400 | 401 | ### toggle() 402 | - **Purpose**: Toggles the dropdown's open/closed state. 403 | 404 | ### render() 405 | - **Purpose**: Displays the dropdown's label and items, showing sub-items if the dropdown is open. 406 | 407 | 408 |
409 | 410 | ---- 411 | -------------------------------------------------------------------------------- /resources/Promise/readme.md: -------------------------------------------------------------------------------- 1 | # Promise 2 | 3 | ##### ` Question 1: Convert a string to a valid number` 4 | 5 | Write a function to convert a string containing a number (e.g., "123") into an actual number. If it is not a valid number, return NaN. 6 | 7 | `Example:` 8 | 9 | ```javascript 10 | 11 | function convertToNumber(str) { 12 | // Your code here 13 | } 14 | 15 | console.log(convertToNumber("123")); // 123 16 | console.log(convertToNumber("abc")); // NaN 17 | 18 | ``` 19 | 20 | `Topics Covered:` 21 | Number methods i.e. Number(), isNaN() 22 | 23 | **Hints:** 24 | - [isNaN()](https://www.w3schools.com/jsref/jsref_isnan.asp), - [JS Numbers](https://www.w3schools.com/jsref/jsref_number.asp) 25 | 26 |
27 | Solution 28 | 29 | ### Let's look at the solution: 30 | 31 | ```javascript 32 | 33 | function convertToNumber(str) { 34 | const number = Number(str); // Try to convert the string to a number 35 | return isNaN(number) ? NaN : number; // If conversion fails, return NaN 36 | } 37 | 38 | console.log(convertToNumber("123")); // 123 39 | console.log(convertToNumber("abc")); // NaN 40 | console.log(convertToNumber("12.34")); // 12.34 41 | 42 | ``` 43 | 44 | **Explanation:** 45 | 46 | 47 | - Number(str): tries to convert the string to a number. 48 | - isNaN(number): checks if the result is not a valid number and returns NaN if it's invalid. 49 | 50 |
51 | 52 | ---- 53 | ##### ` Question 1. Quiz Timeout` 54 | 55 | Write a function quizWithTimeout(question, answer, timeout) that takes a question, expected answer, and timeout. If the answer is provided within the timeout, resolve with "Correct!". Otherwise, reject with "Time s up!". 56 | 57 | `Example:` 58 | 59 | ```javascript 60 | 61 | function quizWithTimeout(question, expectedAnswer, timeout) { 62 | //Your code here 63 | } 64 | 65 | // Example Usage 66 | quizWithTimeout("What is 2+2?", "4", 3000) 67 | .then(console.log) 68 | .catch(console.log); 69 | 70 | 71 | ``` 72 | 73 | `Topics Covered:` 74 | Promise 75 | 76 | **Hints:** 77 | - [Promise](https://www.w3schools.com/js/js_promise.asp) 78 | 79 |
80 | Solution 81 | 82 | ### Let's look at the solution: 83 | 84 | ```javascript 85 | 86 | function quizWithTimeout(question, expectedAnswer, timeout) { 87 | console.log(question); // Show the question to the user 88 | return new Promise((resolve, reject) => { 89 | const timer = setTimeout(() => { 90 | reject("Time's up!"); // If time runs out, reject the promise 91 | }, timeout); 92 | 93 | setTimeout(() => { 94 | const userAnswer = expectedAnswer; // Simulate user answering correctly 95 | if (userAnswer === expectedAnswer) { 96 | clearTimeout(timer); // Stop the timeout 97 | resolve("Correct!"); // Resolve the promise with "Correct!" 98 | } 99 | }, 1000); // Assume user answers within 1 second 100 | }); 101 | } 102 | 103 | // Example Usage 104 | quizWithTimeout("What is 2+2?", "4", 3000) 105 | .then(console.log) 106 | .catch(console.log); 107 | 108 | 109 | ``` 110 | 111 | **Explanation:** 112 | 113 | 114 | This function handles user responses with a timeout mechanism. Depending on the user's timing, the function resolves or rejects based on the outcome: 115 | 116 | 1. If the user answers correctly before the timeout, the promise resolves with the message: 117 | **"Correct!"** 118 | 2. If the timeout expires before the user responds, the promise rejects with the message: 119 | **"Time's up!"** 120 | 121 |
122 | 123 | ---- 124 | ##### ` Question 2. Promise Chain Calculator` 125 | 126 | Write a calculator function that takes a number and returns an object with methods add, subtract, multiply, and getResult. Each method returns a promise to allow chaining. 127 | 128 | `Example:` 129 | 130 | ```javascript 131 | 132 | function calculator(initialValue) { 133 | //Your code here 134 | } 135 | 136 | // Example Usage 137 | calculator(5) 138 | .add(10) 139 | .subtract(3) 140 | .multiply(2) 141 | .getResult() 142 | .then(console.log); 143 | 144 | 145 | ``` 146 | 147 | `Topics Covered:` 148 | Promise 149 | 150 | **Hints:** 151 | - [Promise](https://www.w3schools.com/js/js_promise.asp) 152 | 153 |
154 | Solution 155 | 156 | ### Let's look at the solution: 157 | 158 | ```javascript 159 | 160 | function calculator(initialValue) { 161 | let value = initialValue; 162 | 163 | return { 164 | add(num) { 165 | return new Promise((resolve) => { 166 | value += num; 167 | resolve(this); 168 | }); 169 | }, 170 | subtract(num) { 171 | return new Promise((resolve) => { 172 | value -= num; 173 | resolve(this); 174 | }); 175 | }, 176 | multiply(num) { 177 | return new Promise((resolve) => { 178 | value *= num; 179 | resolve(this); 180 | }); 181 | }, 182 | getResult() { 183 | return new Promise((resolve) => { 184 | resolve(value); 185 | }); 186 | }, 187 | }; 188 | } 189 | 190 | // Example Usage 191 | calculator(5) 192 | .add(10) 193 | .subtract(3) 194 | .multiply(2) 195 | .getResult() 196 | .then(console.log); 197 | 198 | 199 | ``` 200 | 201 | **Explanation:** 202 | 203 | 204 | Each method, such as add, subtract, etc., modifies the current value and returns a promise. This approach allows for chaining operations. The getResult method resolves the final value. 205 | 206 |
207 | 208 | ---- 209 | ##### ` Question 3. Online Food Order Status` 210 | 211 | Write a function trackOrder(orderId) that returns a promise to simulate tracking an online food order. Resolve with different statuses ("Preparing", "Out for delivery", "Delivered") at 1-second intervals. 212 | 213 | `Example:` 214 | 215 | ```javascript 216 | 217 | function trackOrder(orderId) { 218 | //Your code here 219 | } 220 | 221 | // Example Usage 222 | trackOrder(123).then(console.log); 223 | 224 | 225 | ``` 226 | 227 | `Topics Covered:` 228 | Promise 229 | 230 | **Hints:** 231 | - [Promise](https://www.w3schools.com/js/js_promise.asp) 232 | 233 |
234 | Solution 235 | 236 | ### Let's look at the solution: 237 | 238 | ```javascript 239 | 240 | function trackOrder(orderId) { 241 | const statuses = ["Preparing", "Out for delivery", "Delivered"]; 242 | return new Promise((resolve) => { 243 | let i = 0; 244 | 245 | const interval = setInterval(() => { 246 | console.log(statuses[i]); 247 | i++; 248 | 249 | if (i === statuses.length) { 250 | clearInterval(interval); 251 | resolve("Order Complete"); 252 | } 253 | }, 1000); 254 | }); 255 | } 256 | 257 | // Example Usage 258 | trackOrder(123).then(console.log); 259 | 260 | 261 | ``` 262 | 263 | **Explanation:** 264 | 265 | 266 | ## Purpose 267 | The trackOrder function simulates tracking the status of an order (Preparing, Out for delivery, Delivered) over time. 268 | 269 | ## How it works 270 | 1. It creates a Promise that resolves when the order is complete. 271 | 2. An interval logs the order statuses one by one every second. 272 | 3. When all statuses are logged, the interval stops, and the Promise resolves with "Order Complete." 273 | 274 |
275 | 276 | ---- 277 | ##### ` Question 4. Flight Booking System` 278 | 279 | Write a function bookFlight(ticketDetails) that simulates a flight booking process. Return a promise that resolves after 3 seconds with the message "Booking confirmed for [Passenger Name]". 280 | 281 | `Example:` 282 | 283 | ```javascript 284 | 285 | function bookFlight(ticketDetails) { 286 | //Your code here 287 | } 288 | 289 | // Example Usage 290 | bookFlight({ passenger: "Pinkee", flight: "AI-202" }).then(console.log); 291 | 292 | ``` 293 | 294 | `Topics Covered:` 295 | Promise 296 | 297 | **Hints:** 298 | - [Promise](https://www.w3schools.com/js/js_promise.asp) 299 | 300 |
301 | Solution 302 | 303 | ### Let's look at the solution: 304 | 305 | ```javascript 306 | 307 | function bookFlight(ticketDetails) { 308 | return new Promise((resolve) => { 309 | setTimeout(() => { 310 | resolve(`Booking confirmed for ${ticketDetails.passenger}`); 311 | }, 3000); 312 | }); 313 | } 314 | 315 | // Example Usage 316 | bookFlight({ passenger: "Pinkee", flight: "AI-202" }).then(console.log); 317 | 318 | ``` 319 | 320 | **Explanation:** 321 | 322 | 323 | ## Purpose 324 | The bookFlight function simulates booking a flight for a passenger and confirms the booking after a delay. 325 | 326 | ## How it works 327 | 1. It takes ticketDetails as input. 328 | 2. It returns a Promise that resolves after 3 seconds (3000ms) with a confirmation message. 329 | 330 | ## Example Usage 331 | When you call bookFlight, it resolves with a message like: 332 | "Booking confirmed for Pinkee" after 3 seconds. 333 | 334 |
335 | 336 | ---- 337 | ##### ` Question 5. File Upload Simulation` 338 | 339 | Write a function simulateFileUpload(fileName, size) that simulates uploading a file. Return a promise that resolves after a delay based on the file size, logging the upload progress every second. 340 | 341 | `Example:` 342 | 343 | ```javascript 344 | 345 | function simulateFileUpload(fileName, size) { 346 | //Your code here 347 | } 348 | 349 | // Example Usage 350 | simulateFileUpload("photo.jpg", 3).then(console.log); 351 | 352 | 353 | ``` 354 | 355 | `Topics Covered:` 356 | Promise 357 | 358 | **Hints:** 359 | - [Promise](https://www.w3schools.com/js/js_promise.asp) 360 | 361 |
362 | Solution 363 | 364 | ### Let's look at the solution: 365 | 366 | ```javascript 367 | 368 | function simulateFileUpload(fileName, size) { 369 | return new Promise((resolve) => { 370 | let progress = 0; 371 | const interval = setInterval(() => { 372 | progress += Math.ceil(100 / size); 373 | console.log(`Uploading ${fileName}: ${progress}%`); 374 | 375 | if (progress >= 100) { 376 | clearInterval(interval); 377 | resolve("File uploaded successfully!"); 378 | } 379 | }, 1000); 380 | }); 381 | } 382 | 383 | // Example Usage 384 | simulateFileUpload("photo.jpg", 3).then(console.log); 385 | 386 | 387 | ``` 388 | 389 | **Explanation:** 390 | 391 | 392 | ## Purpose 393 | The simulateFileUpload function mimics the process of uploading a file by showing progress updates and completing after a simulated delay. 394 | 395 | ## How It Works 396 | 397 | 1. **Input Parameters**: 398 | - fileName: The name of the file being uploaded. 399 | - size: The size of the file (in arbitrary units). 400 | 401 | 2. **Process**: 402 | - A Promise is returned to simulate an asynchronous upload process. 403 | - Every second, the progress of the upload increases. 404 | - The progress percentage is calculated based on the file size: (100 / size). 405 | - When the progress reaches or exceeds 100%, the interval stops and the Promise resolves with a success message. 406 | 407 |
408 | 409 | ---- 410 | ##### ` Question 6. Online Movie Streaming` 411 | 412 | Create a function streamMovie(movieName) that simulates streaming a movie. If the movie is unavailable, reject with "Movie not found". Otherwise, resolve with "Streaming [movieName]..." 413 | 414 | `Example:` 415 | 416 | ```javascript 417 | 418 | function streamMovie(movieName) { 419 | //Your code here 420 | } 421 | 422 | // Example Usage 423 | streamMovie("Inception") 424 | .then(console.log) 425 | .catch(console.log); 426 | 427 | ``` 428 | 429 | `Topics Covered:` 430 | Promise 431 | 432 | **Hints:** 433 | - [Promise](https://www.w3schools.com/js/js_promise.asp) 434 | 435 |
436 | Solution 437 | 438 | ### Let's look at the solution: 439 | 440 | ```javascript 441 | 442 | function streamMovie(movieName) { 443 | const availableMovies = ["Inception", "Interstellar", "The Matrix"]; 444 | 445 | return new Promise((resolve, reject) => { 446 | setTimeout(() => { 447 | if (availableMovies.includes(movieName)) { 448 | resolve(`Streaming ${movieName}...`); 449 | } else { 450 | reject("Movie not found"); 451 | } 452 | }, 2000); 453 | }); 454 | } 455 | 456 | // Example Usage 457 | streamMovie("Inception") 458 | .then(console.log) 459 | .catch(console.log); 460 | 461 | ``` 462 | 463 | **Explanation:** 464 | 465 | 466 | ## Purpose 467 | The streamMovie function simulates streaming a movie by checking if it exists in a predefined list of available movies. 468 | 469 | ## How It Works 470 | 1. **Input Parameter**: 471 | - movieName: The name of the movie you want to stream. 472 | 473 | 2. **Process**: 474 | - The function checks if the movieName exists in the list ["Inception", "Interstellar", "The Matrix"]. 475 | - If the movie is found, the function resolves with a message stating that it is streaming the movie. 476 | - If the movie is not found, the function rejects with a message saying "Movie not found". 477 | - A 2-second delay is simulated using setTimeout. 478 | 479 |
480 | 481 | ---- 482 | -------------------------------------------------------------------------------- /resources/Maps/readme.md: -------------------------------------------------------------------------------- 1 | # Maps 2 | 3 | ###### ` Question 1: Find Events Within a Latitude and Longitude Range` 4 | 5 | Suppose that you are developing an event management application. Given an array of event data with latitude and longitude coordinates, find all events that are within a specified range of latitude and longitude. 6 | 7 | `Example:` 8 | 9 | ```javascript 10 | 11 | function findEventsInRange(events, latRange, lngRange) { 12 | 13 | // Your code here 14 | 15 | } 16 | 17 | // Example usage: 18 | const events = [ 19 | { name: "Concert", city: "New York", lat: 40.730610, lng: -73.935242 }, 20 | { name: "Festival", city: "Los Angeles", lat: 34.0522, lng: -118.2437 }, 21 | { name: "Parade", city: "London", lat: 51.5074, lng: -0.1278 } 22 | ]; 23 | const latRange = [34.0, 40.0]; // Latitude range 24 | const lngRange = [-120.0, -70.0]; // Longitude range 25 | 26 | const filteredEvents = findEventsInRange(events, latRange, lngRange); 27 | console.log(filteredEvents); 28 | // Output: [{ name: "Festival", city: "Los Angeles", lat: 34.0522, lng: -118.2437 }] 29 | 30 | 31 | ``` 32 | 33 | `Topics Covered:` 34 | Javascript Maps 35 | 36 | **Hints:** 37 | - [Maps in JS](https://www.w3schools.com/js/js_maps.asp) 38 | 39 |
40 | Solution 41 | 42 | ### Let's look at the solution: 43 | 44 | ```javascript 45 | 46 | function findEventsInRange(events, latRange, lngRange) { 47 | return events.filter(event => 48 | event.lat >= latRange[0] && event.lat <= latRange[1] && 49 | event.lng >= lngRange[0] && event.lng <= lngRange[1] 50 | ); 51 | } 52 | 53 | // Example usage: 54 | const events = [ 55 | { name: "Concert", city: "New York", lat: 40.730610, lng: -73.935242 }, 56 | { name: "Festival", city: "Los Angeles", lat: 34.0522, lng: -118.2437 }, 57 | { name: "Parade", city: "London", lat: 51.5074, lng: -0.1278 } 58 | ]; 59 | const latRange = [34.0, 40.0]; // Latitude range 60 | const lngRange = [-120.0, -70.0]; // Longitude range 61 | 62 | const filteredEvents = findEventsInRange(events, latRange, lngRange); 63 | console.log(filteredEvents); 64 | // Output: [{ name: "Festival", city: "Los Angeles", lat: 34.0522, lng: -118.2437 }] 65 | 66 | ``` 67 | 68 | **Explanation:** 69 | 70 | 71 | - The findEventsInRange function filters events whose lat and lng values fall within the specified latRange and lngRange. 72 | - It uses the filter method to return an array of matching events. 73 | 74 |
75 | 76 | ---- 77 | ###### ` Question 2: Group Events by City` 78 | 79 | Create a map that groups events based on their city. 80 | 81 | `Example:` 82 | 83 | ```javascript 84 | 85 | function groupEventsByCity(events) { 86 | 87 | // Your Code here 88 | 89 | } 90 | 91 | // Example usage: 92 | const events = [ 93 | { name: "Concert", city: "New York", lat: 40.730610, lng: -73.935242 }, 94 | { name: "Festival", city: "Los Angeles", lat: 34.0522, lng: -118.2437 }, 95 | { name: "Parade", city: "New York", lat: 40.730610, lng: -73.935242 } 96 | ]; 97 | 98 | const groupedEvents = groupEventsByCity(events); 99 | 100 | // Display the grouped events 101 | for (const city in groupedEvents) { 102 | console.log(city + ": [" + groupedEvents[city].join(", ") + "]"); 103 | } 104 | 105 | 106 | 107 | ``` 108 | 109 | `Topics Covered:` 110 | Javascript Maps 111 | 112 | **Hints:** 113 | - [Maps in JS](https://www.w3schools.com/js/js_maps.asp) 114 | 115 |
116 | Solution 117 | 118 | ### Let's look at the solution: 119 | 120 | ```javascript 121 | 122 | function groupEventsByCity(events) { 123 | return events.reduce((acc, event) => { 124 | // If the city doesn't exist in the accumulator, initialize it as an empty array 125 | if (!acc[event.city]) { 126 | acc[event.city] = []; 127 | } 128 | // Add the event name to the corresponding city group 129 | acc[event.city].push(event.name); 130 | return acc; 131 | }, {}); 132 | } 133 | 134 | // Example usage: 135 | const events = [ 136 | { name: "Concert", city: "New York", lat: 40.730610, lng: -73.935242 }, 137 | { name: "Festival", city: "Los Angeles", lat: 34.0522, lng: -118.2437 }, 138 | { name: "Parade", city: "New York", lat: 40.730610, lng: -73.935242 } 139 | ]; 140 | 141 | const groupedEvents = groupEventsByCity(events); 142 | 143 | // Display the grouped events 144 | for (const city in groupedEvents) { 145 | console.log(city + ": [" + groupedEvents[city].join(", ") + "]"); 146 | 147 | } 148 | 149 | 150 | ``` 151 | 152 | **Explanation:** 153 | 154 | 155 | - The groupEventsByCity function groups events based on their city. 156 | - It uses reduce to accumulate events into a map, where each city is a key, and the value is an array of event names. 157 | 158 |
159 | 160 | ---- 161 | ###### ` Question 3: Event Planning` 162 | 163 | You are building an event management application. Create a map that shows all the events happening in a city on a particular date, displaying them with markers and event details. 164 | 165 | `Example:` 166 | 167 | ```javascript 168 | 169 | function filterEventsByDate(events, eventDate) { 170 | 171 | //Your code here 172 | 173 | } 174 | 175 | // Example usage: 176 | const events = [ 177 | { name: "Concert", date: "2024-12-31", lat: 40.730610, lng: -73.935242 }, 178 | { name: "Festival", date: "2024-12-31", lat: 34.0522, lng: -118.2437 }, 179 | { name: "Parade", date: "2024-12-31", lat: 51.5074, lng: -0.1278 } 180 | ]; 181 | 182 | const eventDate = "2024-12-31"; 183 | const eventsOnDate = filterEventsByDate(events, eventDate); 184 | 185 | // Display the filtered events with their details 186 | eventsOnDate.forEach(event => { 187 | console.log(event.name + " is happening at [" + event.lat + ", " + event.lng + "]"); 188 | }); 189 | 190 | ``` 191 | 192 | `Topics Covered:` 193 | Javascript Maps 194 | 195 | **Hints:** 196 | - [Maps in JS](https://www.w3schools.com/js/js_maps.asp) 197 | 198 |
199 | Solution 200 | 201 | ### Let's look at the solution: 202 | 203 | ```javascript 204 | 205 | function filterEventsByDate(events, eventDate) { 206 | // Filter events happening on the specified date 207 | return events.filter(event => event.date === eventDate); 208 | } 209 | 210 | // Example usage: 211 | const events = [ 212 | { name: "Concert", date: "2024-12-31", lat: 40.730610, lng: -73.935242 }, 213 | { name: "Festival", date: "2024-12-31", lat: 34.0522, lng: -118.2437 }, 214 | { name: "Parade", date: "2024-12-31", lat: 51.5074, lng: -0.1278 } 215 | ]; 216 | 217 | const eventDate = "2024-12-31"; 218 | const eventsOnDate = filterEventsByDate(events, eventDate); 219 | 220 | // Display the filtered events with their details 221 | eventsOnDate.forEach(event => { 222 | console.log(event.name + " is happening at [" + event.lat + ", " + event.lng + "]"); 223 | }); 224 | 225 | 226 | ``` 227 | 228 | **Explanation:** 229 | 230 | 231 | - The filterEventsByDate function filters events that occur on the given eventDate. 232 | - It returns an array of events that match the provided date and then logs their details using string concatenation. 233 | 234 |
235 | 236 | ---- 237 | ###### ` Question 4: Check if a City is in the Northern Hemisphere` 238 | 239 | Write a programme to check if a city is in the Northern Hemisphere based on its latitude using maps. 240 | 241 | `Example:` 242 | 243 | ```javascript 244 | 245 | // Function to check the hemisphere based on latitude 246 | const checkHemisphere = (latitude) => { 247 | 248 | // Your code here 249 | 250 | }; 251 | 252 | // Example usage 253 | const latitude = 40.730610; // Replace with the latitude of the city 254 | console.log(checkHemisphere(latitude)); 255 | 256 | 257 | ``` 258 | 259 | `Topics Covered:` 260 | Javascript Maps, Conditional statements 261 | 262 | **Hints:** 263 | - [Conditional Statements](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/Conditionals), - [Maps in JS](https://www.w3schools.com/js/js_maps.asp) 264 | 265 |
266 | Solution 267 | 268 | ### Let's look at the solution: 269 | 270 | ```javascript 271 | 272 | // Function to check the hemisphere based on latitude 273 | const checkHemisphere = (latitude) => { 274 | if (latitude > 0) { 275 | return "Northern Hemisphere"; 276 | } else if (latitude < 0) { 277 | return "Southern Hemisphere"; 278 | } else { 279 | return "On the Equator"; 280 | } 281 | }; 282 | 283 | // Example usage 284 | const latitude = 40.730610; // Replace with the latitude of the city 285 | console.log(checkHemisphere(latitude)); 286 | 287 | 288 | ``` 289 | 290 | **Explanation:** 291 | 292 | 293 | - The checkHemisphere function determines the hemisphere based on latitude. 294 | - If the latitude is greater than 0, it returns "Northern Hemisphere". 295 | - If the latitude is less than 0, it returns "Southern Hemisphere", and if it's 0, it returns "On the Equator". 296 | 297 |
298 | 299 | ---- 300 | ###### ` Question 5: Count Events by Date` 301 | 302 | Write a program to count the number of events happening on a specific date. 303 | 304 | `Example:` 305 | 306 | ```javascript 307 | 308 | function countEventsByDate(events, eventDate) { 309 | 310 | // Your code here 311 | 312 | } 313 | 314 | // Example usage: 315 | const events = [ 316 | { name: "Concert", date: "2024-12-31", lat: 40.730610, lng: -73.935242 }, 317 | { name: "Festival", date: "2024-12-31", lat: 34.0522, lng: -118.2437 }, 318 | { name: "Parade", date: "2025-01-01", lat: 51.5074, lng: -0.1278 } 319 | ]; 320 | 321 | const eventDate = "2024-12-31"; 322 | const eventCount = countEventsByDate(events, eventDate); 323 | 324 | console.log("Number of events on " + eventDate + ": " + eventCount); 325 | 326 | ``` 327 | 328 | `Topics Covered:` 329 | Array filtering, Javascript Maps, Conditional statements 330 | 331 | **Hints:** 332 | - [Conditional Statements](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/Conditionals), - [Maps in JS](https://www.w3schools.com/js/js_maps.asp) 333 | 334 |
335 | Solution 336 | 337 | ### Let's look at the solution: 338 | 339 | ```javascript 340 | 341 | function countEventsByDate(events, eventDate) { 342 | // Filter events happening on the specified date and return the count 343 | return events.filter(event => event.date === eventDate).length; 344 | } 345 | 346 | // Example usage: 347 | const events = [ 348 | { name: "Concert", date: "2024-12-31", lat: 40.730610, lng: -73.935242 }, 349 | { name: "Festival", date: "2024-12-31", lat: 34.0522, lng: -118.2437 }, 350 | { name: "Parade", date: "2025-01-01", lat: 51.5074, lng: -0.1278 } 351 | ]; 352 | 353 | const eventDate = "2024-12-31"; 354 | const eventCount = countEventsByDate(events, eventDate); 355 | 356 | console.log("Number of events on " + eventDate + ": " + eventCount); 357 | 358 | ``` 359 | 360 | **Explanation:** 361 | 362 | 363 | - The countEventsByDate function filters events by the given date and returns the count of matching events. 364 | - It uses filter to find events that match the specified date and then counts them using .length. 365 | 366 |
367 | 368 | ---- 369 | ###### ` Question 6: Find Events Happening Now` 370 | 371 | Write a program to identify events that are happening on the current date. 372 | 373 | `Example:` 374 | 375 | ```javascript 376 | 377 | // Sample input: Array of event objects 378 | const events = [ 379 | { name: "Music Festival", date: "2024-12-24", lat: 40.7128, lng: -74.0060 }, 380 | { name: "Art Exhibition", date: "2024-12-23", lat: 34.0522, lng: -118.2437 }, 381 | { name: "Tech Meetup", date: "2024-12-24", lat: 37.7749, lng: -122.4194 }, 382 | ]; 383 | 384 | // Function to find events happening today 385 | function findEventsHappeningToday(events) { 386 | 387 | // Your code here 388 | 389 | } 390 | 391 | // Call the function and log the result 392 | const todayEvents = findEventsHappeningToday(events); 393 | console.log("Events happening today:", todayEvents); 394 | 395 | 396 | ``` 397 | 398 | `Topics Covered:` 399 | Array filtering, Javascript Maps, Conditional statements 400 | 401 | **Hints:** 402 | - [Conditional Statements](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/Conditionals), - [Maps in JS](https://www.w3schools.com/js/js_maps.asp) 403 | 404 |
405 | Solution 406 | 407 | ### Let's look at the solution: 408 | 409 | ```javascript 410 | 411 | // Sample input: Array of event objects 412 | const events = [ 413 | { name: "Music Festival", date: "2024-12-24", lat: 40.7128, lng: -74.0060 }, 414 | { name: "Art Exhibition", date: "2024-12-23", lat: 34.0522, lng: -118.2437 }, 415 | { name: "Tech Meetup", date: "2024-12-24", lat: 37.7749, lng: -122.4194 }, 416 | ]; 417 | 418 | // Function to find events happening today 419 | function findEventsHappeningToday(events) { 420 | const today = new Date().toISOString().split("T")[0]; // Get current date in "YYYY-MM-DD" format 421 | 422 | // Use map to create a new array of events where the date matches today's date 423 | const mappedEvents = events.map(event => { 424 | if (event.date === today) { 425 | return event; // If the event is happening today, return it 426 | } 427 | return null; // Otherwise, return null 428 | }).filter(event => event !== null); // Filter out null values 429 | 430 | return mappedEvents; 431 | } 432 | 433 | // Call the function and log the result 434 | const todayEvents = findEventsHappeningToday(events); 435 | console.log("Events happening today:", todayEvents); 436 | 437 | ``` 438 | 439 | **Explanation:** 440 | 441 | 442 | - We use map to iterate over the events array and create a new array. If the event's date matches the current date, we return the event; otherwise, we return null. 443 | - After using map, we filter out the null values, leaving only the events that are happening today. 444 | 445 |
446 | 447 | ---- 448 | -------------------------------------------------------------------------------- /resources/Fetch_Api/readme.md: -------------------------------------------------------------------------------- 1 | # Fetch Api 2 | 3 | ###### ` Question 1: Fetch Data from API` 4 | 5 | Write a function fetchData that fetches data from the following URL and returns the JSON response. 6 | 7 | `Example:` 8 | 9 | ```javascript 10 | 11 | async function fetchData() { 12 | const url = "https://jsonplaceholder.typicode.com/posts"; 13 | //Your code here 14 | } 15 | 16 | // Example usage 17 | fetchData().then(data => console.log(data)); 18 | 19 | 20 | ``` 21 | 22 | `Topics Covered:` 23 | Error handling, Async/Await, fetch api 24 | 25 | **Hints:** 26 | - [Error handling](https://www.w3schools.com/js/js_errors.asp), - [Async/Await](https://www.w3schools.com/js/js_async.asp), - [fetch api](https://www.w3schools.com/jsref/api_fetch.asp) 27 | 28 |
29 | Solution 30 | 31 | ### Let's look at the solution: 32 | 33 | ```javascript 34 | 35 | async function fetchData() { 36 | const url = "https://jsonplaceholder.typicode.com/posts"; 37 | 38 | try { 39 | const response = await fetch(url); // Fetch data from the API 40 | const data = await response.json(); // Parse JSON response 41 | return data; // Return the array of objects 42 | } catch (error) { 43 | console.error("Error fetching data:", error); 44 | } 45 | } 46 | 47 | // Example usage 48 | fetchData().then(data => console.log(data)); 49 | 50 | 51 | ``` 52 | 53 | **Explanation:** 54 | 55 | 56 | ### Function: fetchData() 57 | 58 | **Purpose**: Fetches data from the API (https://jsonplaceholder.typicode.com/posts). 59 | 60 | #### Steps: 61 | 1. Sends a request to the specified URL using fetch(). 62 | 2. Waits for the response and parses it as JSON using response.json(). 63 | 3. Returns the parsed data (array of objects). 64 | 65 | #### Error Handling: 66 | - If there's an error during the fetch operation, it logs the error message to the console. 67 | 68 | ### Usage: 69 | - The fetchData() function is called and the resulting data is logged to the console using .then(data => console.log(data)). 70 | 71 | 72 |
73 | 74 | ---- 75 | ###### ` Question 2: Fetch with Query Parameters` 76 | 77 | Write a function fetchPostsByUser that fetches posts by a specific user ID from the following URL: 78 | API URL:https://jsonplaceholder.typicode.com/posts?userId=USER_ID 79 | 80 | `Example:` 81 | 82 | ```javascript 83 | 84 | async function fetchPostsByUser(userId) { 85 | const url = `https://jsonplaceholder.typicode.com/posts?userId=${userId}`; // Add query parameter 86 | //Your code here 87 | } 88 | 89 | // Example usage 90 | fetchPostsByUser(1).then(posts => console.log(posts)); 91 | 92 | 93 | 94 | ``` 95 | 96 | `Topics Covered:` 97 | Error handling, Async/Await, fetch api 98 | 99 | **Hints:** 100 | - [Error handling](https://www.w3schools.com/js/js_errors.asp), - [Async/Await](https://www.w3schools.com/js/js_async.asp), - [fetch api](https://www.w3schools.com/jsref/api_fetch.asp) 101 | 102 |
103 | Solution 104 | 105 | ### Let's look at the solution: 106 | 107 | ```javascript 108 | 109 | async function fetchPostsByUser(userId) { 110 | const url = `https://jsonplaceholder.typicode.com/posts?userId=${userId}`; // Add query parameter 111 | 112 | try { 113 | const response = await fetch(url); // Fetch posts for the specific user 114 | const posts = await response.json(); // Parse JSON response 115 | return posts; // Return the array of posts 116 | } catch (error) { 117 | console.error("Error fetching posts:", error); 118 | } 119 | } 120 | 121 | // Example usage 122 | fetchPostsByUser(1).then(posts => console.log(posts)); 123 | 124 | 125 | 126 | ``` 127 | 128 | **Explanation:** 129 | 130 | 131 | ## Function: fetchPostsByUser(userId) 132 | 133 | ## Purpose: 134 | Fetches posts for a specific user from the API [https://jsonplaceholder.typicode.com/posts](https://jsonplaceholder.typicode.com/posts). 135 | 136 | ## Steps: 137 | 1. Constructs the API URL with the provided userId as a query parameter: 138 | `https://jsonplaceholder.typicode.com/posts?userId=${userId}`; 139 | 2. Sends a request to the URL using fetch(). 140 | 3. Waits for the response and parses it as JSON using response.json(). 141 | 4. Returns the parsed data (an array of posts). 142 | 143 | ## Error Handling: 144 | - If there's an error during the fetch operation, it logs the error message to the console. 145 | 146 | ## Usage: 147 | - The fetchPostsByUser(1) function is called with userId = 1, and the resulting posts are logged to the console using .then(posts => console.log(posts)). 148 | 149 | 150 |
151 | 152 | ---- 153 | ###### ` Question 3: Cancel Fetch Request` 154 | 155 | Write a function cancelRequest that uses the Fetch API and AbortController to cancel a request to this URL after 3 seconds if it doesn't complete. 156 | API URL:https://jsonplaceholder.typicode.com/posts 157 | 158 | `Example:` 159 | 160 | ```javascript 161 | 162 | async function cancelRequest() { 163 | //Your code here 164 | } 165 | 166 | // Example usage: 167 | cancelRequest().then(console.log).catch(console.error); 168 | 169 | 170 | ``` 171 | 172 | `Topics Covered:` 173 | Error handling, Async/Await, fetch api 174 | 175 | **Hints:** 176 | - [Error handling](https://www.w3schools.com/js/js_errors.asp), - [Async/Await](https://www.w3schools.com/js/js_async.asp), - [fetch api](https://www.w3schools.com/jsref/api_fetch.asp) 177 | 178 |
179 | Solution 180 | 181 | ### Let's look at the solution: 182 | 183 | ```javascript 184 | 185 | async function cancelRequest() { 186 | const controller = new AbortController(); // Create AbortController 187 | const signal = controller.signal; 188 | 189 | setTimeout(() => { 190 | controller.abort(); // Cancel the request after 3 seconds 191 | }, 3000); 192 | 193 | try { 194 | const response = await fetch('https://jsonplaceholder.typicode.com/posts', { signal }); 195 | const data = await response.json(); 196 | return data; 197 | } catch (error) { 198 | if (error.name === 'AbortError') { 199 | return 'Request canceled'; // Handle request cancellation 200 | } 201 | throw error; 202 | } 203 | } 204 | 205 | // Example usage: 206 | cancelRequest().then(console.log).catch(console.error); 207 | 208 | 209 | ``` 210 | 211 | **Explanation:** 212 | 213 | 214 | ## Function: cancelRequest() 215 | 216 | ## Purpose: 217 | Cancels an API request after 3 seconds using AbortController. 218 | 219 | ## Steps: 220 | 1. Creates an AbortController and sets a 3-second timeout to abort the request. 221 | 2. Sends a fetch request to the API with the signal from the controller. 222 | 3. Handles responses: 223 | - If completed, parses and returns the data. 224 | - If aborted, returns "Request canceled." 225 | 4. Logs or handles other errors if they occur. 226 | 227 | ## Usage: 228 | 1. Calls cancelRequest(). 229 | 2. Logs either the API data or "Request canceled" to the console. 230 | 231 |
232 | 233 | ---- 234 | ###### ` Question 4: Fetch and Update DOM` 235 | 236 | Write a function fetchAndUpdateDOM that fetches a list of users and dynamically creates a