` element with the ID user-list to display the fetched user data.
338 |
339 | ---
340 |
341 | ## Function: fetchAndUpdateDOM()
342 |
343 | ### **Purpose:**
344 | Fetches user data from an API and updates the DOM with the user list.
345 |
346 | ### **Steps:**
347 | 1. Fetches data from https://jsonplaceholder.typicode.com/users.
348 | 2. Parses the response as JSON to get an array of user objects.
349 | 3. Selects the user-list container from the DOM.
350 | 4. Creates a `
` element to list the user details.
351 | 5. Iterates through the user array:
352 | - Creates `
` elements for each user's name and email in the format Name (Email).
353 | - Appends each `
`to the `
`.
354 | 6. Appends the `
` to the user-list container.
355 | # Error Handling
356 | - Logs an error message if the fetch operation fails.
357 | # Execution:
358 | - Calls fetchAndUpdateDOM() to fetch user data and update the DOM when the script runs.
359 |
360 |
361 |
362 |
363 | ----
364 | ###### ` Question 5: Fetch and Cache Data`
365 |
366 | Write a function fetchWithCache that fetches data from the API. If the data has already been fetched before, return the cached data instead of making another network request.
367 | API URL:https://jsonplaceholder.typicode.com/posts
368 |
369 | `Example:`
370 |
371 | ```javascript
372 |
373 | const cache = {}; // Object to store cached data
374 |
375 | async function fetchWithCache() {
376 | //Your code here
377 | }
378 |
379 | // Example usage
380 | fetchWithCache().then(data => console.log(data));
381 |
382 |
383 | ```
384 |
385 | `Topics Covered:`
386 | Error handling, Async/Await, fetch api
387 |
388 | **Hints:**
389 | - [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)
390 |
391 |
392 | Solution
393 |
394 | ### Let's look at the solution:
395 |
396 | ```javascript
397 |
398 | const cache = {}; // Object to store cached data
399 |
400 | async function fetchWithCache() {
401 | const url = "https://jsonplaceholder.typicode.com/posts";
402 |
403 | // Check if data is already cached
404 | if (cache[url]) {
405 | console.log("Returning cached data");
406 | return cache[url]; // Return cached data
407 | }
408 |
409 | try {
410 | const response = await fetch(url); // Fetch data from the API
411 | const data = await response.json(); // Parse JSON response
412 | cache[url] = data; // Store data in cache
413 | return data; // Return the fetched data
414 | } catch (error) {
415 | console.error("Error fetching data:", error);
416 | }
417 | }
418 |
419 | // Example usage
420 | fetchWithCache().then(data => console.log(data));
421 |
422 |
423 | ```
424 |
425 | **Explanation:**
426 |
427 |
428 | ## Function: fetchWithCache
429 |
430 | ### Purpose:
431 | Efficiently fetch data from an API, caching results to avoid redundant requests.
432 |
433 | ### Steps:
434 |
435 | 1. **Initialize Cache**:
436 | - An empty cache object is created to store cached data.
437 |
438 | 2. **Check Cache**:
439 | - If the URL data is already in the cache, log "Returning cached data" and return the cached result.
440 |
441 | 3. **Fetch Data**:
442 | - If not cached, send a fetch request to the API (https://jsonplaceholder.typicode.com/posts).
443 | - Parse the response as JSON and store it in the cache for future use.
444 | - Return the fetched data.
445 |
446 | 4. **Error Handling**:
447 | - Logs any errors encountered during the fetch process.
448 |
449 | ### Usage:
450 | - Calls fetchWithCache(), which either retrieves cached data or fetches and caches the data before logging it to the console.
451 |
452 |
453 |
454 |
455 | ----
456 |
--------------------------------------------------------------------------------
/resources/Operators/readme.md:
--------------------------------------------------------------------------------
1 | # Operators
2 |
3 | ###### ` Question 1: Calculate Total Price with Tax`
4 |
5 | Write a function calculateTotalPrice that takes the price of an item and the tax rate, and returns the total price after tax.
6 |
7 | `Example:`
8 |
9 | ```javascript
10 |
11 | function calculateTotalPrice(price, taxRate) {
12 | // Your code here
13 | }
14 |
15 | // Example usage:
16 | console.log(calculateTotalPrice(100, 0.05)); // Output: 105
17 | console.log(calculateTotalPrice(50, 0.1)); // Output: 55
18 |
19 | ```
20 |
21 | `Topics Covered:`
22 | Operators in JS
23 |
24 | **Hints:**
25 | - [Operators in JS](https://www.w3schools.com/js/js_operators.asp)
26 |
27 |
28 | Solution
29 |
30 | ### Let's look at the solution:
31 |
32 | ```javascript
33 |
34 | function calculateTotalPrice(price, taxRate) {
35 | const tax = price * taxRate;
36 | const totalPrice = price + tax;
37 | return totalPrice;
38 | }
39 |
40 | // Example usage:
41 | console.log(calculateTotalPrice(100, 0.05)); // Output: 105
42 | console.log(calculateTotalPrice(50, 0.1)); // Output: 55
43 |
44 | ```
45 |
46 | **Explanation:**
47 |
48 |
49 | - Multiplies price by taxRate to calculate the tax.
50 | - Adds the tax to the price to get the totalPrice.
51 |
52 |
53 |
54 | ----
55 | ###### ` Question 2: Convert Fahrenheit to Celsius`
56 |
57 | Write a function convertToFahrenheit that takes a temperature in Celsius and converts it to Fahrenheit.
58 |
59 | `Example:`
60 |
61 | ```javascript
62 |
63 | function convertToFahrenheit(celsius) {
64 |
65 | // Your Code Here
66 |
67 | }
68 |
69 | // Example usage:
70 | console.log(convertToFahrenheit(0)); // Output: 32
71 | console.log(convertToFahrenheit(100)); // Output: 212
72 |
73 |
74 | ```
75 |
76 | `Topics Covered:`
77 | Operators in JS
78 |
79 | **Hints:**
80 | - [Operators in JS](https://www.w3schools.com/js/js_operators.asp)
81 |
82 |
83 | Solution
84 |
85 | ### Let's look at the solution:
86 |
87 | ```javascript
88 |
89 | function convertToFahrenheit(celsius) {
90 | const fahrenheit = (celsius * 9/5) + 32;
91 | return fahrenheit;
92 | }
93 |
94 | // Example usage:
95 | console.log(convertToFahrenheit(0)); // Output: 32
96 | console.log(convertToFahrenheit(100)); // Output: 212
97 |
98 | ```
99 |
100 | **Explanation:**
101 |
102 |
103 | - The function convertToFahrenheit(celsius) converts a temperature from Celsius to Fahrenheit using the formula: Fahrenheit = (Celsius × 9/5) + 32.
104 | - Multiplies the Celsius value by 9/5 and adds 32 to calculate Fahrenheit then returns the result.
105 |
106 |
107 |
108 | ----
109 | ###### ` Question 3: Calculate Tip`
110 |
111 | Write a function calculateTip that takes the total bill amount and the tip percentage, and returns the tip amount.
112 |
113 | `Example:`
114 |
115 | ```javascript
116 |
117 | function calculateTip(billAmount, tipPercentage) {
118 |
119 | // Your Code Here
120 | }
121 |
122 | // Example usage:
123 | console.log(calculateTip(200, 15)); // Output: 30
124 | console.log(calculateTip(50, 10)); // Output: 5
125 |
126 |
127 |
128 | ```
129 |
130 | `Topics Covered:`
131 | Operators in JS
132 |
133 | **Hints:**
134 | - [Operators in JS](https://www.w3schools.com/js/js_operators.asp)
135 |
136 |
137 | Solution
138 |
139 | ### Let's look at the solution:
140 |
141 | ```javascript
142 |
143 | function calculateTip(billAmount, tipPercentage) {
144 | const tip = billAmount * (tipPercentage / 100);
145 | return tip;
146 | }
147 |
148 | // Example usage:
149 | console.log(calculateTip(200, 15)); // Output: 30
150 | console.log(calculateTip(50, 10)); // Output: 5
151 |
152 | ```
153 |
154 | **Explanation:**
155 |
156 |
157 | - It multiplies the billAmount by tipPercentage/100 to calculate the tip.
158 | - Returns the tip value for any given inputs.
159 |
160 |
161 |
162 | ----
163 | ###### ` Question 4: Calculate Age`
164 |
165 | Write a function calculateAge that takes the birth year and the current year, and returns the age.
166 |
167 | `Example:`
168 |
169 | ```javascript
170 |
171 | calculateAge(birthYear, currentYear) {
172 |
173 | // Your Code Here
174 |
175 | }
176 |
177 | // Example usage:
178 | console.log(calculateAge(1990, 2024)); // Output: 34
179 | console.log(calculateAge(2000, 2024)); // Output: 24
180 |
181 |
182 |
183 | ```
184 |
185 | `Topics Covered:`
186 | Operators in JS
187 |
188 | **Hints:**
189 | - [Operators in JS](https://www.w3schools.com/js/js_operators.asp)
190 |
191 |
192 | Solution
193 |
194 | ### Let's look at the solution:
195 |
196 | ```javascript
197 |
198 | calculateAge(birthYear, currentYear) {
199 | const age = currentYear - birthYear;
200 | return age;
201 | }
202 |
203 | // Example usage:
204 | console.log(calculateAge(1990, 2024)); // Output: 34
205 | console.log(calculateAge(2000, 2024)); // Output: 24
206 |
207 | ```
208 |
209 | **Explanation:**
210 |
211 |
212 | - It calculates the currentYear (minus) birthYear.
213 | - Returns the computed age.
214 |
215 |
216 |
217 | ----
218 | ###### ` Question 5: Calculate Simple Interest`
219 |
220 | Write a function calculateSimpleInterest that takes the principal amount, the annual interest rate, and the time in years, and returns the simple interest.
221 |
222 | `Example:`
223 |
224 | ```javascript
225 |
226 | function calculateSimpleInterest(principal, rate, time) {
227 |
228 | // Your code here
229 |
230 | }
231 |
232 | // Example usage:
233 | console.log(calculateSimpleInterest(1000, 5, 2)); // Output: 100
234 | console.log(calculateSimpleInterest(500, 3, 4)); // Output: 60
235 |
236 | ```
237 |
238 | `Topics Covered:`
239 | Operators in JS
240 |
241 | **Hints:**
242 | - [Operators in JS](https://www.w3schools.com/js/js_operators.asp), - [Simple Intrest](https://www.cuemath.com/commercial-math/simple-interest/)
243 |
244 |
245 | Solution
246 |
247 | ### Let's look at the solution:
248 |
249 | ```javascript
250 |
251 | function calculateSimpleInterest(principal, rate, time) {
252 | const interest = (principal * rate * time) / 100;
253 | return interest;
254 | }
255 |
256 | // Example usage:
257 | console.log(calculateSimpleInterest(1000, 5, 2)); // Output: 100
258 | console.log(calculateSimpleInterest(500, 3, 4)); // Output: 60
259 |
260 | ```
261 |
262 | **Explanation:**
263 |
264 |
265 | - The calculateSimpleInterest function computes simple interest using the formula:
266 | - Interest = (Principal×Rate×Time)/100
267 | - It takes principal, rate, and time as inputs and returns the calculated interest.
268 |
269 |
270 |
271 | ----
272 | ###### ` Question 6: Calculate Annual Salary from Hourly Wage`
273 |
274 | Write a function calculateAnnualSalary that takes the hourly wage and the number of hours worked per week, and returns the annual salary, assuming 52 working weeks in a year.
275 |
276 | `Example:`
277 |
278 | ```javascript
279 |
280 | function calculateAnnualSalary(hourlyWage, hoursPerWeek) {
281 |
282 | // Your Code Here
283 |
284 | }
285 |
286 | // Example usage:
287 | console.log(calculateAnnualSalary(20, 40)); // Output: 41600
288 | console.log(calculateAnnualSalary(15, 35)); // Output: 27300
289 |
290 |
291 | ```
292 |
293 | `Topics Covered:`
294 | Operators in JS
295 |
296 | **Hints:**
297 | - [Operators in JS](https://www.w3schools.com/js/js_operators.asp)
298 |
299 |
300 | Solution
301 |
302 | ### Let's look at the solution:
303 |
304 | ```javascript
305 |
306 | function calculateAnnualSalary(hourlyWage, hoursPerWeek) {
307 | const weeksPerYear = 52;
308 | const annualSalary = hourlyWage * hoursPerWeek * weeksPerYear;
309 | return annualSalary;
310 | }
311 |
312 | // Example usage:
313 | console.log(calculateAnnualSalary(20, 40)); // Output: 41600
314 | console.log(calculateAnnualSalary(15, 35)); // Output: 27300
315 |
316 | ```
317 |
318 | **Explanation:**
319 |
320 |
321 | - It multiplies hourlyWage by hoursPerWeek and 52 weeks per year.
322 | - Returns the calculated annual salary.
323 |
324 |
325 |
326 | ----
327 | ###### ` Question 7: Calculate Discounted Price`
328 |
329 | Write a function calculateDiscountedPrice that takes the original price and the discount percentage, and returns the price after the discount is applied.
330 |
331 | `Example:`
332 |
333 | ```javascript
334 |
335 | function calculateDiscountedPrice(originalPrice, discountPercentage) {
336 |
337 | //Your Code Here
338 | }
339 |
340 | // Example usage:
341 | console.log(calculateDiscountedPrice(100, 20)); // Output: 80
342 | console.log(calculateDiscountedPrice(250, 10)); // Output: 225
343 |
344 |
345 | ```
346 |
347 | `Topics Covered:`
348 | Operators in JS
349 |
350 | **Hints:**
351 | - [Operators in JS](https://www.w3schools.com/js/js_operators.asp)
352 |
353 |
354 | Solution
355 |
356 | ### Let's look at the solution:
357 |
358 | ```javascript
359 |
360 | function calculateDiscountedPrice(originalPrice, discountPercentage) {
361 | const discountAmount = (originalPrice * discountPercentage) / 100;
362 | const discountedPrice = originalPrice - discountAmount;
363 | return discountedPrice;
364 | }
365 |
366 | // Example usage:
367 | console.log(calculateDiscountedPrice(100, 20)); // Output: 80
368 | console.log(calculateDiscountedPrice(250, 10)); // Output: 225
369 |
370 | ```
371 |
372 | **Explanation:**
373 |
374 |
375 | - It multiplies hourlyWage by hoursPerWeek and 52 weeks per year.
376 | - Returns the calculated annual salary.
377 |
378 |
379 |
380 | ----
381 | ###### ` Question 8: Calculate Time Difference in Hours`
382 |
383 | Write a function calculateTimeDifference that takes two times (in 24-hour format) as strings and returns the difference in hours.
384 |
385 | `Example:`
386 |
387 | ```javascript
388 |
389 | function calculateTimeDifference(time1, time2) {
390 |
391 | //Your code here
392 |
393 | }
394 |
395 | // Example usage:
396 | console.log(calculateTimeDifference("08:30", "17:45")); // Output: 9.25
397 | console.log(calculateTimeDifference("09:00", "14:30")); // Output: 5.50
398 |
399 | ```
400 |
401 | `Topics Covered:`
402 | Operators in JS
403 |
404 | **Hints:**
405 | - [Operators in JS](https://www.w3schools.com/js/js_operators.asp)
406 |
407 |
408 | Solution
409 |
410 | ### Let's look at the solution:
411 |
412 | ```javascript
413 |
414 | function calculateTimeDifference(time1, time2) {
415 | const [hours1, minutes1] = time1.split(':').map(Number);
416 | const [hours2, minutes2] = time2.split(':').map(Number);
417 | const totalMinutes1 = hours1 * 60 + minutes1;
418 | const totalMinutes2 = hours2 * 60 + minutes2;
419 | const differenceInMinutes = Math.abs(totalMinutes2 - totalMinutes1);
420 | return (differenceInMinutes / 60).toFixed(2);
421 |
422 | }
423 |
424 | // Example usage:
425 | console.log(calculateTimeDifference("08:30", "17:45")); // Output: 9.25
426 | console.log(calculateTimeDifference("09:00", "14:30")); // Output: 5.50
427 |
428 | ```
429 |
430 | **Explanation:**
431 |
432 |
433 | - It converts both times (time1 and time2) into total minutes.
434 | - Finds the absolute difference in minutes, divides by 60, and rounds to two decimal places.
435 |
436 |
437 |
438 | ----
439 | ###### ` Question 9: Calculate Distance Between Two Points`
440 |
441 | Write a function calculateDistance that takes the coordinates of two points in a 2D plane and returns the distance between them.
442 |
443 | `Example:`
444 |
445 | ```javascript
446 |
447 | function calculateDistance(x1, y1, x2, y2) {
448 |
449 | // Your Code here
450 |
451 | }
452 |
453 | // Example usage:
454 | console.log(calculateDistance(3, 4, 7, 1)); // Output: 5.00
455 | console.log(calculateDistance(0, 0, 5, 12)); // Output: 13.00
456 |
457 | ```
458 |
459 | `Topics Covered:`
460 | Operators in JS
461 |
462 | **Hints:**
463 | - [Operators in JS](https://www.w3schools.com/js/js_operators.asp)
464 |
465 |
466 | Solution
467 |
468 | ### Let's look at the solution:
469 |
470 | ```javascript
471 |
472 | function calculateDistance(x1, y1, x2, y2) {
473 | const dx = x2 - x1;
474 | const dy = y2 - y1;
475 | const distance = Math.sqrt(dx * dx + dy * dy);
476 | return distance.toFixed(2);
477 | }
478 |
479 | // Example usage:
480 | console.log(calculateDistance(3, 4, 7, 1)); // Output: 5.00
481 | console.log(calculateDistance(0, 0, 5, 12)); // Output: 13.00
482 |
483 | ```
484 |
485 | **Explanation:**
486 |
487 |
488 | - This function calculates the distance between two points using the distance formula (x2−x1)2+(y2−y1)2sqrt{(x2 - x1)^2 + (y2 - y1)^2}.
489 |
490 |
491 |
492 | ----
493 | ###### ` Question 10: Calculate Average Speed`
494 |
495 | Write a function calculateAverageSpeed that takes the total distance traveled and the total time taken, and returns the average speed.
496 |
497 | `Example:`
498 |
499 | ```javascript
500 |
501 | function calculateAverageSpeed(totalDistance, totalTime) {
502 |
503 | // Your code here
504 |
505 | }
506 |
507 | // Example usage:
508 | console.log(calculateAverageSpeed(150, 3)); // Output: 50.00
509 | console.log(calculateAverageSpeed(100, 2)); // Output: 50.00
510 |
511 | ```
512 |
513 | `Topics Covered:`
514 | Operators in JS
515 |
516 | **Hints:**
517 | - [Operators in JS](https://www.w3schools.com/js/js_operators.asp)
518 |
519 |
520 | Solution
521 |
522 | ### Let's look at the solution:
523 |
524 | ```javascript
525 |
526 | function calculateAverageSpeed(totalDistance, totalTime) {
527 | const averageSpeed = totalDistance / totalTime;
528 | return averageSpeed.toFixed(2);
529 | }
530 |
531 | // Example usage:
532 | console.log(calculateAverageSpeed(150, 3)); // Output: 50.00
533 | console.log(calculateAverageSpeed(100, 2)); // Output: 50.00
534 |
535 | ```
536 |
537 | **Explanation:**
538 |
539 |
540 | - This function divides the total distance by the total time to calculate the average speed.
541 |
542 |
543 |
544 | ----
545 |
--------------------------------------------------------------------------------
/resources/Date/readme.md:
--------------------------------------------------------------------------------
1 | # Date
2 | ###### ` Question 1:Get Current Date and Time`
3 |
4 | Description:Write a javascript program where print the current date and time using Date object.
5 | `Example:`
6 |
7 | ```javascript
8 |
9 | function logCurrentDate() {
10 | //code here
11 | }
12 |
13 | // Calling the function
14 | logCurrentDate();
15 |
16 | ```
17 | `Topics Covered:`
18 | Date Object
19 |
20 | **Hints:**
21 | - [Date Object](https://www.w3schools.com/js/js_dates.asp)
22 |
23 | Solution
24 |
25 | ### Let's look at the solution:
26 |
27 | ```javascript
28 | function logCurrentDate() {
29 | console.log(new Date()); // Creates and logs the current date and time
30 | }
31 |
32 | logCurrentDate();
33 |
34 | ```
35 | **Explanation:**
36 | -The function logCurrentDate creates a new Date object representing the current date and time.
37 |
38 | -It directly logs this object to the console without storing it in a variable.
39 |
40 |
41 | ----
42 | ###### ` Question 2:Get Specific Date and Time`
43 |
44 | Description::Write a javascript program where print the specific date and time using Date object
45 |
46 | `Example:`
47 |
48 | ```javascript
49 |
50 | function logSpecificDate() {
51 | //code here
52 | }
53 |
54 | logSpecificDate(); // Calling the function
55 |
56 | ```
57 | `Topics Covered:`
58 | Date Object
59 |
60 | **Hints:**
61 | - [Date Object](https://www.w3schools.com/js/js_dates.asp)
62 |
63 | Solution
64 |
65 | ### Let's look at the solution:
66 |
67 | ```javascript
68 | function logSpecificDate() {
69 | let specificDate = new Date('2024-12-25T00:00:00');
70 | console.log(specificDate); // Logs: Thu Dec 25 2024 00:00:00 GMT+0000 (UTC)
71 | }
72 |
73 | logSpecificDate(); // Calling the function
74 |
75 |
76 | ```
77 | **Explanation:**
78 | -The function logSpecificDate creates a Date object for the specific date '2024-12-25T00:00:00' and logs it.
79 |
80 | -When calling logSpecificDate(), it logs the date in the console in the default format.
81 |
82 |
83 | ----
84 | ###### ` Question 3:Get Current Year, Month, Date`
85 |
86 | Description:Write a javascript program where print the year date and month using the different function of date object.
87 |
88 | `Example:`
89 |
90 | ```javascript
91 |
92 | function logCurrentDateInfo() {
93 | //code here
94 | }
95 |
96 | logCurrentDateInfo(); // Calling the function
97 |
98 |
99 | ```
100 | `Topics Covered:`
101 | Date Object getFullYear getDate getMonth.
102 |
103 | **Hints:**
104 | - [Date Object,getFullYear, getDate, getMonth](https://www.geeksforgeeks.org/how-to-get-day-month-and-year-from-date-object-in-javascript/#:~:text=The%20getMonth()%20method%20to,year%20from%20the%20Date%20object.)
105 |
106 | Solution
107 |
108 | ### Let's look at the solution:
109 |
110 | ```javascript
111 | function logCurrentDateInfo() {
112 | let currentDate = new Date();
113 | console.log('Year:', currentDate.getFullYear()); // Logs current year
114 | console.log('Month:', currentDate.getMonth() + 1); // Logs current month (0-indexed)
115 | console.log('Date:', currentDate.getDate()); // Logs current date
116 | }
117 |
118 | logCurrentDateInfo(); // Calling the function
119 |
120 |
121 | ```
122 | **Explanation:**
123 | -The function logCurrentDateInfo creates a new Date object, and then logs the current year, month (adding 1 to adjust for the zero-based index), and date to the console.
124 |
125 | -Calling logCurrentDateInfo() triggers the function and prints the current date details.
126 |
127 |
128 | ----
129 | ###### ` Question 4:Format Date as a String`
130 |
131 | Description:Write a javascript program where print the current date and formate the date in the readable formate.
132 | `Example:`
133 |
134 | ```javascript
135 |
136 | function logFormattedDate() {
137 | //code here
138 | }
139 |
140 | logFormattedDate(); // Calling the function
141 |
142 | ```
143 | `Topics Covered:`
144 | Date Object,toDateString().
145 |
146 | **Hints:**
147 | - [Date Object,toDateString().](https://www.w3schools.com/js/js_dates.asp)
148 |
149 | Solution
150 |
151 | ### Let's look at the solution:
152 |
153 | ```javascript
154 | function logFormattedDate() {
155 | let currentDate = new Date();
156 | let formattedDate = currentDate.toDateString(); // Formats the date as a string
157 | console.log(formattedDate); // Logs the formatted date, e.g., "Tue Dec 21 2024"
158 | }
159 |
160 | logFormattedDate(); // Calling the function
161 |
162 |
163 | ```
164 | **Explanation:**
165 | -The function logFormattedDate creates a Date object for the current date and formats it using toDateString() to display the date in a readable format (e.g., "Tue Dec 21 2024").
166 |
167 | -When the function is called, it logs the formatted date to the console.
168 |
169 |
170 | ----
171 | ###### ` Question 5:Get Day of the Week`
172 |
173 | Description:Write a javascript program where print the day of week according to date.For this firstly find the day then return the day of week from that.
174 | `Example:`
175 |
176 | ```javascript
177 |
178 | function logDayOfWeek() {
179 | //code here
180 | }
181 |
182 | logDayOfWeek(); // Calling the function
183 |
184 |
185 | ```
186 | `Topics Covered:`
187 | Date Object getDay()
188 |
189 | **Hints:**
190 | - [Date Object, getDay()](https://www.w3schools.com/js/js_dates.asp)
191 |
192 | Solution
193 |
194 | ### Let's look at the solution:
195 |
196 | ```javascript
197 | function logDayOfWeek() {
198 | let currentDate = new Date();
199 | let dayOfWeek = currentDate.getDay(); // Gets the day of the week (0 = Sunday, 1 = Monday, etc.)
200 | console.log('Day of the week:', dayOfWeek); // Logs the day (0 = Sunday, 1 = Monday, etc.)
201 | }
202 |
203 | logDayOfWeek(); // Calling the function
204 |
205 |
206 | ```
207 | **Explanation:**
208 | -The function logDayOfWeek creates a Date object for the current date and uses getDay() to retrieve the day of the week (0 for Sunday, 1 for Monday, etc.).
209 |
210 | -The function then logs this day to the console when called.
211 |
212 |
213 | ----
214 | ###### ` Question 6:Add Days to a Date`
215 |
216 | Description:Write a javascript program where manipulate the current date by adding some extra date and return the updated date from it.
217 | `Example:`
218 |
219 | ```javascript
220 |
221 | function getFutureDate(daysToAdd) {
222 | //code here
223 | }
224 |
225 | console.log(getFutureDate(5)); // Logs the date 5 days from today
226 |
227 |
228 | ```
229 | `Topics Covered:`
230 | Date Object, getDate()
231 |
232 | **Hints:**
233 | - [Date Object, getDate()](https://www.w3schools.com/js/js_dates.asp)
234 |
235 | Solution
236 |
237 | ### Let's look at the solution:
238 |
239 | ```javascript
240 | function getFutureDate(daysToAdd) {
241 | let currentDate = new Date();
242 | currentDate.setDate(currentDate.getDate() + daysToAdd);
243 | return currentDate;
244 | }
245 |
246 | console.log(getFutureDate(5)); // Logs the date 5 days from today
247 |
248 | ```
249 | **Explanation:**
250 | -getFutureDate(daysToAdd) accepts a number (daysToAdd) and adds that many days to the current date.
251 |
252 | -The function then returns the updated date.
253 |
254 |
255 | ----
256 | ###### ` Question 7:Subtract Days from a Date`
257 |
258 | Description:Write a javascript program where manipulate the current date by subtracting some date and return the updated date from it.
259 | `Example:`
260 |
261 | ```javascript
262 | function subtractDaysFromCurrentDate(daysToSubtract) {
263 | //code here
264 | }
265 |
266 | // Example usage:
267 | let updatedDate = subtractDaysFromCurrentDate(10); // Subtract 10 days from the current date
268 | console.log(updatedDate); // Logs the updated date
269 |
270 |
271 | ```
272 | `Topics Covered:`
273 | Date Object, getDate()
274 |
275 | **Hints:**
276 | - [Date Object, getDate()](https://www.w3schools.com/js/js_dates.asp)
277 |
278 | Solution
279 |
280 | ### Let's look at the solution:
281 |
282 | ```javascript
283 | function subtractDaysFromCurrentDate(daysToSubtract) {
284 | let currentDate = new Date(); // Get the current date
285 | currentDate.setDate(currentDate.getDate() - daysToSubtract); // Subtract the specified number of days
286 | return currentDate; // Return the updated date
287 | }
288 |
289 | // Example usage:
290 | let updatedDate = subtractDaysFromCurrentDate(10); // Subtract 10 days from the current date
291 | console.log(updatedDate); // Logs the updated date
292 |
293 |
294 | ```
295 | **Explanation:**
296 | -subtractDaysFromCurrentDate(daysToSubtract): This function takes an argument daysToSubtract and subtracts that many days from the current date.
297 |
298 | -setDate(currentDate.getDate() - daysToSubtract): This modifies the current date by subtracting the specified number of days.
299 |
300 |
301 | ----
302 | ###### ` Question 8:Compare Dates`
303 |
304 | Description:Write a javascript program where create a two variable date1 date2 and took a two date and then compare it on the basis of comparison print that date1 is earlier to date2 of later to date2 or same to date2.
305 | `Example:`
306 |
307 | ```javascript
308 |
309 | function compareDates(date1, date2) {
310 | //code here
311 | }
312 |
313 | // Example usage:
314 | let date1 = new Date('2024-12-25');
315 | let date2 = new Date('2024-12-31');
316 |
317 | compareDates(date1, date2); // Compare the two dates
318 |
319 |
320 | ```
321 | `Topics Covered:`
322 | Date Object, getDate()
323 |
324 | **Hints:**
325 | - [Date Object, getDate()](https://www.w3schools.com/js/js_dates.asp)
326 |
327 | Solution
328 |
329 | ### Let's look at the solution:
330 |
331 | ```javascript
332 | function compareDates(date1, date2) {
333 | if (date1 < date2) {
334 | console.log('date1 is earlier than date2');
335 | } else if (date1 > date2) {
336 | console.log('date1 is later than date2');
337 | } else {
338 | console.log('Both dates are the same');
339 | }
340 | }
341 |
342 | // Example usage:
343 | let date1 = new Date('2024-12-25');
344 | let date2 = new Date('2024-12-31');
345 |
346 | compareDates(date1, date2); // Compare the two dates
347 |
348 | ```
349 | **Explanation:**
350 | -compareDates(date1, date2): This function takes two Date objects as parameters (date1 and date2) and compares them.
351 |
352 | -Inside the function, the comparison logic is similar to your original code:
353 |
354 | If date1 is earlier than date2, it logs 'date1 is earlier than date2'.
355 | If date1 is later than date2, it logs 'date1 is later than date2'.
356 | If the dates are the same, it logs 'Both dates are the same'.
357 |
358 |
359 | ----
360 | ###### ` Question 9: Convert Date to Timestamp (Unix Time)`
361 |
362 | Description:Write a javascript program where convert a Date object to a Unix timestamp (milliseconds since January 1, 1970).
363 | `Example:`
364 |
365 | ```javascript
366 |
367 | function getCurrentTimestamp() {
368 | //code here
369 | }
370 |
371 | // Example usage:
372 | let timestamp = getCurrentTimestamp();
373 | console.log('Timestamp:', timestamp); // Logs the timestamp
374 |
375 |
376 |
377 | ```
378 | `Topics Covered:`
379 | Date Object,getTime()
380 |
381 | **Hints:**
382 | - [Date Object,getTime()](https://www.w3schools.com/js/js_dates.asp)
383 |
384 | Solution
385 |
386 | ### Let's look at the solution:
387 |
388 | ```javascript
389 | function getCurrentTimestamp() {
390 | let currentDate = new Date(); // Get the current date
391 | let timestamp = currentDate.getTime(); // Get the timestamp (milliseconds since January 1, 1970)
392 | return timestamp; // Return the timestamp
393 | }
394 |
395 | // Example usage:
396 | let timestamp = getCurrentTimestamp();
397 | console.log('Timestamp:', timestamp); // Logs the timestamp
398 |
399 |
400 | ```
401 | **Explanation:**
402 | -getCurrentTimestamp(): This function creates a new Date object for the current date and time, then calls .getTime() on it to get the timestamp.
403 |
404 | -.getTime(): This method returns the number of milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC).
405 |
406 |
407 | ----
408 | ###### ` Question 10:Get Time Difference Between Two Dates`
409 |
410 | Description:Write a program in javascript where take two variable startDate endDate and store the two date then find dateDiffrence after that find the daysDiffrence and return the difference.
411 | `Example:`
412 |
413 | ```javascript
414 |
415 | function getDaysDifference(startDate, endDate) {
416 | //code here
417 | }
418 |
419 | // Example usage:
420 | let startDate = new Date('2024-01-01');
421 | let endDate = new Date('2024-12-31');
422 |
423 | let daysDifference = getDaysDifference(startDate, endDate);
424 | console.log('Days difference:', daysDifference); // Logs the difference in days
425 |
426 |
427 |
428 | ```
429 | `Topics Covered:`
430 | Date Object
431 |
432 | **Hints:**
433 | - [Date Object](https://www.w3schools.com/js/js_dates.asp)
434 |
435 | Solution
436 |
437 | ### Let's look at the solution:
438 |
439 | ```javascript
440 | function getDaysDifference(startDate, endDate) {
441 | let timeDifference = endDate - startDate; // Difference in milliseconds
442 | let daysDifference = timeDifference / (1000 * 3600 * 24); // Convert to days
443 | return daysDifference; // Return the difference in days
444 | }
445 |
446 | // Example usage:
447 | let startDate = new Date('2024-01-01');
448 | let endDate = new Date('2024-12-31');
449 |
450 | let daysDifference = getDaysDifference(startDate, endDate);
451 | console.log('Days difference:', daysDifference); // Logs the difference in days
452 |
453 |
454 | ```
455 | **Explanation:**
456 | -getDaysDifference(startDate, endDate): This function takes two Date objects as parameters — startDate and endDate.
457 |
458 | -endDate - startDate: Subtracting the two dates gives the difference in milliseconds.
459 |
460 | -timeDifference / (1000 * 3600 * 24): This converts the time difference from milliseconds to days.
461 |
462 | -The denominator represents the number of milliseconds in a day (1000 milliseconds in a second, 3600 seconds in an hour, and 24 hours in a day).
463 |
464 |
465 | ----
466 |
467 |
468 |
--------------------------------------------------------------------------------
/resources/Loops/readme.md:
--------------------------------------------------------------------------------
1 | # Loops
2 |
3 | ###### ` Question 1. Calculate Total Cart Price`
4 |
5 | Write a program in javascript where define a cartItem array which store the all item.Each item is represented as an object with properties like name, price, and quantity.Use a loop to go through each item in the cart and calculate its total price (item price multiplied by item quantity).After calculating the total price of all items, print or display the total to the user.
6 |
7 | `Example:`
8 |
9 | ```javascript
10 |
11 | // Define the cartItem array with each item represented as an object
12 | const cartItems = [
13 | { name: "Laptop", price: 800, quantity: 2 },
14 | { name: "Phone", price: 500, quantity: 3 },
15 | { name: "Headphones", price: 100, quantity: 1 }
16 | ];
17 |
18 | // Function to calculate total price of all items in the cart
19 | function calculateTotalPrice(cartItems) {
20 |
21 | // Your code here
22 |
23 | }
24 |
25 | // Call the function and log the result
26 | const total = calculateTotalPrice(cartItems);
27 | console.log("Total Cart Price: $" + total);
28 |
29 |
30 |
31 | ```
32 |
33 | `Topics Covered:`
34 | Loop in JS
35 |
36 | **Hints:**
37 | - [Loop in JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)
38 |
39 |
40 | Solution
41 |
42 | ### Let's look at the solution:
43 |
44 | ```javascript
45 |
46 | // Define the cartItem array with each item represented as an object
47 | const cartItems = [
48 | { name: "Laptop", price: 800, quantity: 2 },
49 | { name: "Phone", price: 500, quantity: 3 },
50 | { name: "Headphones", price: 100, quantity: 1 }
51 | ];
52 |
53 | // Function to calculate total price of all items in the cart
54 | function calculateTotalPrice(cartItems) {
55 | let totalPrice = 0;
56 |
57 | // Loop through each item in the cart and calculate its total price
58 | for (let i = 0; i < cartItems.length; i++) {
59 | const item = cartItems[i];
60 | totalPrice += item.price * item.quantity; // Add the total price of the current item
61 | }
62 |
63 | return totalPrice; // Return the total price
64 | }
65 |
66 | // Call the function and log the result
67 | const total = calculateTotalPrice(cartItems);
68 | console.log("Total Cart Price: $" + total);
69 |
70 |
71 |
72 | ```
73 |
74 | **Explanation:**
75 |
76 |
77 | - This function takes the cartItems array as input, calculates the total price by multiplying the price and quantity of each item, and returns the total price.
78 |
79 | - The loop iterates over the cartItems array and calculates the price for each item, adding it to the total.
80 |
81 |
82 |
83 | ----
84 | ###### ` Question 2. Calculate Quiz Score Based on User's Answers`
85 |
86 | Write a program in javascript where create An array of objects questions, where each object contains a question (question text) and the points (point value for that question).Create a array userAnswers that stores the users answers.Each answer is either "correct" or "incorrect".create function calculateQuizScore function .Loops through all the questions and checks the users answer.If the answer is correct, it adds the respective points to the total score.It also calculates the percentage by dividing the total score by the maximum possible score and multiplying by 100.
87 |
88 | `Example:`
89 |
90 | ```javascript
91 |
92 | // Array representing items in the shopping cart
93 | const cart = [
94 | { name: 'Laptop', price: 1000, quantity: 2 },
95 | { name: 'Phone', price: 500, quantity: 1 },
96 | { name: 'Headphones', price: 100, quantity: 3 }
97 | ];
98 |
99 | // Function to calculate the total price of items in the cart
100 | function calculateTotalPrice() {
101 |
102 | // Your code here
103 |
104 | }
105 |
106 | // Call the function to calculate the total price
107 | calculateTotalPrice();
108 |
109 |
110 |
111 | ```
112 |
113 | `Topics Covered:`
114 | Loops in Javascript
115 |
116 | **Hints:**
117 | - [Loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)
118 |
119 |
120 | Solution
121 |
122 | ### Let's look at the solution:
123 |
124 | ```javascript
125 |
126 | // Array representing items in the shopping cart
127 | const cart = [
128 | { name: 'Laptop', price: 1000, quantity: 2 },
129 | { name: 'Phone', price: 500, quantity: 1 },
130 | { name: 'Headphones', price: 100, quantity: 3 }
131 | ];
132 |
133 | // Function to calculate the total price of items in the cart
134 | function calculateTotalPrice() {
135 | let totalPrice = 0; // Initialize total price to 0
136 |
137 | // Loop through each item in the cart
138 | for (let i = 0; i < cart.length; i++) {
139 | const item = cart[i];
140 |
141 | // Calculate the price for the current item (price * quantity)
142 | const itemTotal = item.price * item.quantity;
143 |
144 | // Add the item's total price to the overall total price
145 | totalPrice += itemTotal;
146 |
147 | // Log item details and its total price to the console
148 | console.log(item.name + ": $" + item.price + " x " + item.quantity + " = $" + itemTotal);
149 | }
150 |
151 | // Log the final total price to the console
152 | console.log("Total Price: $" + totalPrice);
153 | }
154 |
155 | // Call the function to calculate the total price
156 | calculateTotalPrice();
157 |
158 |
159 |
160 | ```
161 |
162 | **Explanation:**
163 |
164 |
165 | - Instead of using template literals, string concatenation with the + operator is used for combining the strings and variables.
166 | - The log now includes details for each item and the final total price.
167 |
168 |
169 |
170 | ----
171 | ###### ` Question 3. Filter Products Based on Availability and Price`
172 |
173 | Write a program in javascript where You are given an array called products, which contains objects representing various products. Each product has properties such as id, name, price, and inStock. The goal is to filter the array to keep only those products where inStock is true and the price is less than $100. You need to use an array method, like filter, to achieve this and return a new array containing the products that meet these criteria.
174 |
175 |
176 | `Example:`
177 |
178 | ```javascript
179 |
180 | const products = [
181 | { id: 1, name: "Laptop", price: 999, inStock: true },
182 | { id: 2, name: "Phone", price: 499, inStock: false },
183 | { id: 3, name: "Headphones", price: 50, inStock: true },
184 | { id: 4, name: "Mouse", price: 20, inStock: true },
185 | { id: 5, name: "Keyboard", price: 120, inStock: true }
186 | ];
187 |
188 | // Function to filter products based on inStock and price
189 | function filterProducts(products) {
190 |
191 | // Your code here
192 |
193 | }
194 |
195 | // Call the function and display the filtered products
196 | const filteredProducts = filterProducts(products);
197 | console.log(filteredProducts);
198 |
199 |
200 | ```
201 |
202 | `Topics Covered:`
203 | Loops in Javascript
204 |
205 | **Hints:**
206 | - [Loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)
207 |
208 |
209 | Solution
210 |
211 | ### Let's look at the solution:
212 |
213 | ```javascript
214 |
215 | const products = [
216 | { id: 1, name: "Laptop", price: 999, inStock: true },
217 | { id: 2, name: "Phone", price: 499, inStock: false },
218 | { id: 3, name: "Headphones", price: 50, inStock: true },
219 | { id: 4, name: "Mouse", price: 20, inStock: true },
220 | { id: 5, name: "Keyboard", price: 120, inStock: true }
221 | ];
222 |
223 | // Function to filter products based on inStock and price
224 | function filterProducts(products) {
225 | return products.filter(function(product) {
226 | return product.inStock && product.price < 100;
227 | });
228 | }
229 |
230 | // Call the function and display the filtered products
231 | const filteredProducts = filterProducts(products);
232 | console.log(filteredProducts);
233 |
234 |
235 | ```
236 |
237 | **Explanation:**
238 |
239 |
240 | - The displayInfo function takes an object person and accesses name and age properties to log them.
241 | - The + operator is used to concatenate the string and variables.
242 | - Result: For the input { name: "Charlie", age: 35, city: "London" }, it logs "Name: Charlie, Age: 35".
243 |
244 |
245 |
246 | ----
247 | ###### ` Question 4. Generating a List of Random Numbers`
248 |
249 | Write a program in javascript where create function generateRandomNumbers(count, min, max): count: The number of random numbers you want to generate. , min: The minimum possible value for the random number. , max: The maximum possible value for the random number. , The for loop runs count times, which means it will generate that many random numbers.Once the loop is finished, the function returns the array of random numbers.
250 |
251 | `Example:`
252 |
253 | ```javascript
254 |
255 | // Function to generate random numbers
256 | function generateRandomNumbers(count, min, max) {
257 |
258 | // Your code here
259 |
260 | }
261 |
262 | // Example usage: Generate 5 random numbers between 1 and 10
263 | const randomList = generateRandomNumbers(5, 1, 10);
264 | console.log(randomList);
265 |
266 |
267 | ```
268 |
269 | `Topics Covered:`
270 | Loops in Javascript
271 |
272 | **Hints:**
273 | - [Loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)
274 |
275 |
276 | Solution
277 |
278 | ### Let's look at the solution:
279 |
280 | ```javascript
281 |
282 | // Function to generate random numbers
283 | function generateRandomNumbers(count, min, max) {
284 | // Array to hold the random numbers
285 | const randomNumbers = [];
286 |
287 | // Loop to generate the required number of random numbers
288 | for (let i = 0; i < count; i++) {
289 | // Generate a random number within the range [min, max]
290 | const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
291 |
292 | // Add the random number to the array
293 | randomNumbers.push(randomNumber);
294 | }
295 |
296 | // Return the array of random numbers
297 | return randomNumbers;
298 | }
299 |
300 | // Example usage: Generate 5 random numbers between 1 and 10
301 | const randomList = generateRandomNumbers(5, 1, 10);
302 | console.log(randomList);
303 |
304 |
305 | ```
306 |
307 | **Explanation:**
308 |
309 |
310 | - The generateRandomNumbers function generates a specified number of random integers within a given range by using a loop and Math.random().
311 | - It returns an array of random numbers that meet the conditions of the specified range (min to max).
312 |
313 |
314 |
315 | ----
316 | ###### ` Question 5. Counting Down Timer (Countdown)`
317 |
318 | Write a program in javascript where Start with a specific countdown time (in seconds).Create a loop that will run for the number of seconds in the countdown.Inside the loop, wait for 1 second (1000 milliseconds).Calculate and display the remaining time.Stop the loop when the time is zero and display "Time up!
319 |
320 | `Example:`
321 |
322 | ```javascript
323 |
324 | // Function to start the countdown
325 | function countdown(seconds) {
326 |
327 | // Your code here
328 |
329 | }
330 |
331 | // Start countdown from 10 seconds
332 | countdown(10);
333 |
334 |
335 |
336 | ```
337 |
338 | `Topics Covered:`
339 | Loops in Javascript
340 |
341 | **Hints:**
342 | - [setInterval in Javascript](https://www.programiz.com/javascript/setInterval), - [Loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)
343 |
344 |
345 | Solution
346 |
347 | ### Let's look at the solution:
348 |
349 | ```javascript
350 |
351 | // Function to start the countdown
352 | function countdown(seconds) {
353 | let remainingTime = seconds;
354 |
355 | // Loop every second
356 | const timer = setInterval(function() {
357 | console.log(remainingTime); // Display remaining time
358 | remainingTime--; // Decrease time by 1
359 |
360 | // Stop when time is zero
361 | if (remainingTime < 0) {
362 | clearInterval(timer); // Stop the countdown
363 | console.log("Time's up!");
364 | }
365 | }, 1000); // Interval of 1 second
366 | }
367 |
368 | // Start countdown from 10 seconds
369 | countdown(10);
370 |
371 |
372 | ```
373 |
374 | **Explanation:**
375 |
376 |
377 | - setInterval runs a function every second, displaying the remaining time and decreasing it.
378 | - When the time reaches zero, the clearInterval stops the countdown, and "Time's up!" is displayed.
379 |
380 |
381 |
382 | ----
383 | ###### ` Question 6. Summing Numbers in an Array`
384 |
385 | Write a program in javascript where create array numbers where store the some numbers.Then the for loop iterates through each element in the numbers array. In each iteration, the current number (numbers[i]) is added to the sum variable.
386 |
387 | `Example:`
388 |
389 | ```javascript
390 |
391 | // Array of numbers to sum
392 | const numbers = [5, 10, 15, 20, 25];
393 |
394 | // Function to calculate the sum of the numbers
395 | function calculateSum() {
396 | // Your code here
397 | }
398 |
399 | // Calling the function to calculate the sum
400 | calculateSum();
401 |
402 | ```
403 |
404 | `Topics Covered:`
405 | Loops in Javascript
406 |
407 | **Hints:**
408 | - [Loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)
409 |
410 |
411 | Solution
412 |
413 | ### Let's look at the solution:
414 |
415 | ```javascript
416 |
417 | // Array of numbers to sum
418 | const numbers = [5, 10, 15, 20, 25];
419 |
420 | // Function to calculate the sum of the numbers
421 | function calculateSum() {
422 | let sum = 0; // Initialize sum to 0
423 |
424 | // Using a for loop to iterate over each number in the array
425 | for (let i = 0; i < numbers.length; i++) {
426 | sum += numbers[i]; // Add the current number to the sum
427 | }
428 |
429 | // Display the total sum
430 | console.log('Total Sum:'+sum);
431 | }
432 |
433 | // Calling the function to calculate the sum
434 | calculateSum();
435 |
436 | ```
437 |
438 | **Explanation:**
439 |
440 |
441 | - The numbers array holds the numbers you want to sum.
442 | - The calculateSum function uses a for loop to iterate through each number in the array and adds it to the sum.
443 |
444 |
445 |
446 | ----
447 |
--------------------------------------------------------------------------------
/resources/Timer_Function/readme.md:
--------------------------------------------------------------------------------
1 |
2 | # Timer Function
3 |
4 | ###### ` Question 1:Auto-Save Function`
5 |
6 | Write a javascript program where every five minutes the input field data is automatically saved.
7 |
8 | `Example:`
9 |
10 | ```javascript
11 |
12 |
13 |
14 |
15 |
16 |
17 | Auto Save Example
18 |
19 |
20 |
21 |
22 |
23 |
33 |
34 |
35 |
36 |
37 |
38 | ```
39 |
40 | `Topics Covered:`
41 | Timer function
42 |
43 | **Hints:**
44 | - [Timer function](https://www.freecodecamp.org/news/javascript-timer-how-to-set-a-timer-function-in-js/)
45 |
46 |
47 | Solution
48 |
49 | ### Let's look at the solution:
50 |
51 | ```javascript
52 |
53 |
54 |
55 |
56 |
57 |
58 | Auto Save Example
59 |
60 |
61 |
62 |
63 |
64 |
77 |
78 |
79 |
80 |
81 |
82 |
83 | ```
84 |
85 | **Explanation:**
86 |
87 |
88 | - **timeout**: A variable to store the timeout ID.
89 | - **autoSave function**:
90 | - Clears any previously set timeout using clearTimeout(timeout).
91 | - Sets a new timeout to trigger an auto-save after 5 seconds of inactivity using setTimeout.
92 | - Inside the timeout, console.log("Data auto-saved.") simulates the auto-save action.
93 | - **Event listener**:
94 | - Listens for the input event on an `` element.
95 | - Calls the autoSave function every time the input changes.
96 | - **Effect**: Auto-save happens after 5 seconds of no input (inactivity).
97 |
98 |
99 |
100 | ----
101 | ###### ` Question 2:Slideshow (Image Carousel)`
102 |
103 | Write a javascript program where an array called images contains the URLs of the images you want to display.On every second display the every image of array.Create currentIndex variable that keep track of all images.
104 |
105 | `Example:`
106 |
107 | ```javascript
108 |
109 | let timeout;
110 |
111 | // Array of image URLs (this can be any valid image URLs or placeholders)
112 | const images = [
113 | "https://via.placeholder.com/600x300/ff7f7f/333333?text=Image+1",
114 | "https://via.placeholder.com/600x300/ff9f00/333333?text=Image+2",
115 | "https://via.placeholder.com/600x300/00aaff/333333?text=Image+3",
116 | "https://via.placeholder.com/600x300/30ff7f/333333?text=Image+4"
117 | ];
118 |
119 | let currentIndex = 0; // Initial index of the current image
120 |
121 | // Function to simulate showing the next image in the console
122 | function showNextImage() {
123 | //Your code here
124 | }
125 |
126 | // Initialize the slideshow and make it cycle every 3 seconds
127 | setInterval(showNextImage, 3000); // Change image every 3 seconds
128 |
129 |
130 | ```
131 |
132 | `Topics Covered:`
133 | Timer function
134 |
135 | **Hints:**
136 | - [setInterval](https://www.freecodecamp.org/news/javascript-timer-how-to-set-a-timer-function-in-js/)
137 |
138 |
139 | Solution
140 |
141 | ### Let's look at the solution:
142 |
143 | ```javascript
144 |
145 | // Array of image URLs (this can be any valid image URLs or placeholders)
146 | const images = [
147 | "https://via.placeholder.com/600x300/ff7f7f/333333?text=Image+1",
148 | "https://via.placeholder.com/600x300/ff9f00/333333?text=Image+2",
149 | "https://via.placeholder.com/600x300/00aaff/333333?text=Image+3",
150 | "https://via.placeholder.com/600x300/30ff7f/333333?text=Image+4"
151 | ];
152 |
153 | let currentIndex = 0; // Initial index of the current image
154 |
155 | // Function to simulate showing the next image in the console
156 | function showNextImage() {
157 | // Clear the console (optional, to simulate a "transition" effect)
158 | console.clear();
159 |
160 | // Display the current image URL
161 | console.log("Displaying image: " + images[currentIndex]);
162 |
163 | // Update the current index (loop back to 0 after the last image)
164 | currentIndex = (currentIndex + 1) % images.length;
165 | }
166 |
167 | // Initialize the slideshow and make it cycle every 3 seconds
168 | setInterval(showNextImage, 3000); // Change image every 3 seconds
169 |
170 |
171 | ```
172 |
173 | **Explanation:**
174 |
175 |
176 | - **images**: An array containing image URLs (or placeholders).
177 | - **currentIndex**: A variable that keeps track of the current image’s index.
178 | - **showNextImage function**:
179 | - Clears the console (optional for transition effect).
180 | - Displays the current image URL.
181 | - Updates currentIndex to the next image, looping back to the start after the last image.
182 | - **setInterval**: Calls showNextImage every 3 seconds, creating an automatic slideshow of images in the console.
183 |
184 |
185 |
186 | ----
187 | ###### ` Question 3:Displaying Notifications (Delayed Alert)`
188 |
189 | Write a javascript program where display a notification on every 10 second. Write a function resetTimer which run on the mouse movement and any key press
190 |
191 | `Example:`
192 |
193 | ```javascript
194 |
195 | let timeout;
196 |
197 | function resetTimer() {
198 | //Your code here
199 | }
200 |
201 | // Reset timer on any mouse movement
202 | window.addEventListener('mousemove', resetTimer);
203 |
204 | // Reset timer on any key press
205 | window.addEventListener('keydown', resetTimer);
206 |
207 |
208 | ```
209 |
210 | `Topics Covered:`
211 | Timer function
212 |
213 | **Hints:**
214 | - [Timer function](https://www.freecodecamp.org/news/javascript-timer-how-to-set-a-timer-function-in-js/)
215 |
216 |
217 | Solution
218 |
219 | ### Let's look at the solution:
220 |
221 | ```javascript
222 |
223 | let timeout;
224 |
225 | function resetTimer() {
226 | clearTimeout(timeout); // Clear any existing timeout
227 | timeout = setTimeout(function() {
228 | alert("You have been inactive for 10 seconds!"); // Alert after 10 seconds of inactivity
229 | }, 10000);
230 | }
231 |
232 | // Reset timer on any mouse movement
233 | window.addEventListener('mousemove', resetTimer);
234 |
235 | // Reset timer on any key press
236 | window.addEventListener('keydown', resetTimer);
237 |
238 | ```
239 |
240 | **Explanation:**
241 |
242 |
243 | - **timeout**: A variable to store the timeout ID.
244 | - **resetTimer function**:
245 | - Clears any existing timeout using clearTimeout(timeout).
246 | - Sets a new timeout to trigger an alert after 10 seconds of inactivity.
247 | - **Event listeners**:
248 | - mousemove event: Resets the timer whenever the mouse is moved.
249 | - keydown event: Resets the timer whenever a key is pressed.
250 |
251 |
252 |
253 | ----
254 | ###### ` Question 4:Simple Random Number Generator (with setInterval)`
255 |
256 | Write a javascript program generates a random number every second and prints it to the console.
257 |
258 | `Example:`
259 |
260 | ```javascript
261 |
262 | const randomNumberGenerator = setInterval(function() {
263 | //Your code here
264 | }, 1000); // Generate a random number every 1 second
265 |
266 | ```
267 |
268 | `Topics Covered:`
269 | Timer function
270 |
271 | **Hints:**
272 | - [Timer function](https://www.freecodecamp.org/news/javascript-timer-how-to-set-a-timer-function-in-js/)
273 |
274 |
275 | Solution
276 |
277 | ### Let's look at the solution:
278 |
279 | ```javascript
280 |
281 | const randomNumberGenerator = setInterval(function() {
282 | const randomNumber = Math.floor(Math.random() * 100) + 1;
283 | console.log("Random Number: " + randomNumber);
284 | }, 1000); // Generate a random number every 1 second
285 |
286 | ```
287 |
288 | **Explanation:**
289 |
290 |
291 | - **randomNumberGenerator**: A variable that stores the setInterval ID.
292 | - **setInterval**:
293 | - Runs the provided function every 1 second (1000 milliseconds).
294 | - Inside the function, Math.floor(Math.random() * 100) + 1 generates a random number between 1 and 100.
295 | - The random number is logged to the console.
296 | - **Effect**: A random number is generated and displayed every second.
297 |
298 |
299 |
300 | ----
301 | ###### ` Question 5:Simple Stopwatch`
302 |
303 | Write a javascript program program acts like a stopwatch that counts seconds from 0 upward. On every 10 second print the message on console the stopwatch is stopped.
304 |
305 | `Example:`
306 |
307 | ```javascript
308 |
309 | let seconds = 0;
310 | const stopwatch = setInterval(function() {
311 | //Your code here
312 | }, 1000);
313 | // Increment every 1 second
314 |
315 |
316 | ```
317 |
318 | `Topics Covered:`
319 | Timer function
320 |
321 | **Hints:**
322 | - [Timer function](https://www.freecodecamp.org/news/javascript-timer-how-to-set-a-timer-function-in-js/)
323 |
324 |
325 | Solution
326 |
327 | ### Let's look at the solution:
328 |
329 | ```javascript
330 |
331 | let seconds = 0;
332 | const stopwatch = setInterval(function() {
333 | console.log(seconds + " seconds");
334 | seconds++;
335 |
336 | if (seconds === 10) { // Stop after 10 seconds
337 | clearInterval(stopwatch);
338 | console.log("Stopwatch stopped at 10 seconds");
339 | }
340 | }, 1000);
341 | // Increment every 1 second
342 |
343 |
344 | ```
345 |
346 | **Explanation:**
347 |
348 |
349 | - **seconds**: A variable to track the time in seconds.
350 | - **setInterval**:
351 | - Runs the provided function every 1 second (1000 milliseconds).
352 | - Logs the current value of seconds to the console.
353 | - Increments the seconds variable by 1 each time.
354 | - After 10 seconds, stops the stopwatch using clearInterval(stopwatch) and logs that the stopwatch has stopped.
355 | - **Effect**: The stopwatch logs the elapsed time every second and stops after 10 seconds.
356 |
357 |
358 |
359 | ----
360 | ###### ` Question 6: Show a Welcome Message After a Delaya`
361 |
362 | Create a simple JavaScript program that shows a welcome message after a delay of 5 seconds. This message should appear in the console, and it should demonstrate how to use setTimeout to delay the execution of a function.
363 |
364 | `Example:`
365 |
366 | ```javascript
367 |
368 | // Program to show a welcome message after 5 seconds
369 | // Function to display the welcome message
370 | function showWelcomeMessage() {
371 | //Your code here
372 | }
373 | // Delay the welcome message by 5 seconds (5000 milliseconds)
374 |
375 |
376 | ```
377 |
378 | `Topics Covered:`
379 | Timer function
380 |
381 | **Hints:**
382 | - [Timer function](https://www.freecodecamp.org/news/javascript-timer-how-to-set-a-timer-function-in-js/)
383 |
384 |
385 | Solution
386 |
387 | ### Let's look at the solution:
388 |
389 | ```javascript
390 |
391 | // Program to show a welcome message after 5 seconds
392 | // Function to display the welcome message
393 | function showWelcomeMessage() {
394 | console.log("Welcome to our website!");
395 | }
396 | // Delay the welcome message by 5 seconds (5000 milliseconds)
397 | setTimeout(showWelcomeMessage, 5000);
398 | // 5000ms = 5 seconds
399 |
400 |
401 | ```
402 |
403 | **Explanation:**
404 |
405 |
406 | - **showWelcomeMessage function**: A function that logs the welcome message to the console.
407 | - **setTimeout**:
408 | - Delays the execution of the showWelcomeMessage function by 5 seconds (5000 milliseconds).
409 | - After 5 seconds, the welcome message "Welcome to our website!" is logged to the console.
410 | - **Effect**: The welcome message is displayed 5 seconds after the code runs.
411 |
412 |
413 |
414 | ----
415 | ###### ` Question 7: Counting Seconds`
416 |
417 | This program counts down from 10 to 1 and then prints "Done!".
418 |
419 | `Example:`
420 |
421 | ```javascript
422 |
423 | // Program to count seconds and stop after 10 seconds
424 | let seconds = 0;
425 | // Initialize the counter
426 | // Function to increment and display the count of seconds
427 | function countSeconds() {
428 | //Your code here
429 | }
430 | // Start counting every 1000ms (1 second)
431 | const interval = setInterval(countSeconds, 1000);
432 |
433 |
434 | ```
435 |
436 | `Topics Covered:`
437 | Timer function
438 |
439 | **Hints:**
440 | - [Timer function](https://www.freecodecamp.org/news/javascript-timer-how-to-set-a-timer-function-in-js/)
441 |
442 |
443 | Solution
444 |
445 | ### Let's look at the solution:
446 |
447 | ```javascript
448 |
449 | // Program to count seconds and stop after 10 seconds
450 | let seconds = 0;
451 | // Initialize the counter
452 | // Function to increment and display the count of seconds
453 | function countSeconds() {
454 | console.log(seconds);
455 | // Display the current count of seconds
456 | seconds++;
457 | // Increment the counter by 1
458 | if (seconds > 10) {
459 | // Stop counting after 10 seconds
460 | clearInterval(interval);
461 | // Stop the interval timer
462 | console.log("Counting stopped.");
463 | }
464 | }
465 | // Start counting every 1000ms (1 second)
466 | const interval = setInterval(countSeconds, 1000);
467 |
468 | ```
469 |
470 | **Explanation:**
471 |
472 |
473 | - **seconds**: A variable to track the count of seconds, initialized to 0.
474 | - **countSeconds function**:
475 | - Logs the current value of seconds to the console.
476 | - Increments the seconds variable by 1 each time it's called.
477 | - After 10 seconds, stops the counting using clearInterval(interval) and logs "Counting stopped."
478 | - **setInterval**:
479 | - Starts the countSeconds function every 1 second (1000 milliseconds).
480 | - The counter stops automatically after 10 seconds.
481 |
482 |
483 |
484 | ----
485 |
--------------------------------------------------------------------------------
/resources/RegEx/readme.md:
--------------------------------------------------------------------------------
1 | # RegEx
2 |
3 | ###### ` Question 1: Check if an Email is Valid`
4 |
5 | Write a function createChatManager that stores and retrieves live chat messages in a chat application.
6 |
7 | `Example:`
8 |
9 | ```javascript
10 |
11 | function isValidEmail(email) {
12 | // Your code here
13 | }
14 |
15 | // Example usage:
16 | console.log(isValidEmail("example@gmail.com")); // true
17 | console.log(isValidEmail("example@.com")); // false
18 |
19 |
20 | ```
21 |
22 | `Topics Covered:`
23 | RegEx methods i.e. test()
24 |
25 | **Hints:**
26 | - [RegEx methods i.e. test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions)
27 |
28 |
29 | Solution
30 |
31 | ### Let's look at the solution:
32 |
33 | ```javascript
34 |
35 | function isValidEmail(email) {
36 | // Regular expression to check if the email is valid
37 | const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/;
38 | return emailRegex.test(email); // Returns true if valid, false otherwise
39 | }
40 |
41 | // Example usage:
42 | console.log(isValidEmail("example@gmail.com")); // true
43 | console.log(isValidEmail("example@.com")); // false
44 |
45 | ```
46 |
47 | **Explanation:**
48 |
49 |
50 | The isValidEmail function checks if an email is valid using a regular expression:
51 |
52 | - **Regex Explanation**:
53 | - ^[^s@]+: Ensures the email starts with one or more characters that are not spaces or @.
54 | - @[^s@]+: Ensures the email contains an @ followed by more valid characters.
55 | - .[^s@]+$: Ensures the email ends with a dot . followed by valid characters.
56 |
57 | - **Return Value**:
58 | - Returns true if the email matches the pattern (valid).
59 | - Returns false if the email does not match (invalid).
60 |
61 |
62 |
63 | ----
64 | ###### ` Question 2: Find Phone Numbers in Text`
65 |
66 | Write a function findPhoneNumbers that extracts all valid phone numbers from a string.
67 | Valid formats include:
68 | (123) 456-7890
69 | 123-456-7890
70 | 123 456 7890
71 |
72 |
73 | `Example:`
74 |
75 | ```javascript
76 |
77 | function findPhoneNumbers(text) {
78 | //Your code
79 | }
80 |
81 | // Example usage:
82 | console.log(findPhoneNumbers("Call me at (123) 456-7890 or 123-456-7890"));
83 | // ["(123) 456-7890", "123-456-7890"]
84 |
85 |
86 | ```
87 |
88 | `Topics Covered:`
89 | RegEx methods i.e. test(), String methods i.e. match()
90 |
91 | **Hints:**
92 | - [RegEx methods i.e. test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions), - [String methods i.e. match()](https://www.w3schools.com/jsref/jsref_match.asp)
93 |
94 |
95 | Solution
96 |
97 | ### Let's look at the solution:
98 |
99 | ```javascript
100 |
101 | function findPhoneNumbers(text) {
102 | // Regular expression to match different phone number formats
103 | const phoneRegex = /(?d{3})?[- ]?d{3}[- ]?d{4}/g;
104 | return text.match(phoneRegex) || []; // Returns all matches or an empty array
105 | }
106 |
107 | // Example usage:
108 | console.log(findPhoneNumbers("Call me at (123) 456-7890 or 123-456-7890"));
109 | // ["(123) 456-7890", "123-456-7890"]
110 |
111 |
112 | ```
113 |
114 | **Explanation:**
115 |
116 |
117 | The findPhoneNumbers function extracts phone numbers from a given text using a regular expression:
118 |
119 | - **Regex Breakdown**:
120 | - (?d{3})?: Matches an optional opening parenthesis (, followed by 3 digits, and an optional closing parenthesis ).
121 | - [- ]?: Matches an optional hyphen - or space after the area code.
122 | - d{3}: Matches the next 3 digits.
123 | - [- ]?: Matches an optional hyphen - or space.
124 | - d{4}: Matches the final 4 digits.
125 | - /g: The global flag ensures all matches are found in the text.
126 |
127 | - **Return Value**:
128 | - text.match(phoneRegex): Returns an array of all matched phone numbers.
129 | - || []: Ensures the function returns an empty array if no matches are found.
130 |
131 |
132 |
133 | ----
134 | ###### ` Question 3: Get Query Parameters from a Link`
135 |
136 | Write a function getQueryParameter that extracts the value of a specific query parameter from a URL.
137 |
138 | `Example:`
139 |
140 | ```javascript
141 |
142 | function getQueryParameter(url, parameter) {
143 | //Your code here
144 | }
145 |
146 | // Example usage:
147 | console.log(getQueryParameter("https://example.com?id=123&name=chandra", "id")); // "123"
148 |
149 |
150 | ```
151 |
152 | `Topics Covered:`
153 | URL object
154 |
155 | **Hints:**
156 | - [URL object](https://javascript.info/url)
157 |
158 |
159 | Solution
160 |
161 | ### Let's look at the solution:
162 |
163 | ```javascript
164 |
165 | function getQueryParameter(url, parameter) {
166 | // Create a URL object to easily parse query parameters
167 | const urlObj = new URL(url);
168 | return urlObj.searchParams.get(parameter); // Returns the value of the parameter
169 | }
170 |
171 | // Example usage:
172 | console.log(getQueryParameter("https://example.com?id=123&name=chandra", "id")); // "123"
173 |
174 |
175 | ```
176 |
177 | **Explanation:**
178 |
179 |
180 | The getQueryParameter function extracts the value of a specific query parameter from a given URL.
181 |
182 | - **Steps**:
183 | 1. new URL(url): Creates a URL object to parse the URL easily.
184 | 2. urlObj.searchParams.get(parameter): Retrieves the value of the query parameter specified by parameter.
185 |
186 |
187 |
188 | ----
189 | ###### ` Question 4: Check if a Date is in the Right Format`
190 |
191 | Write a function isValidDate that checks if a string follows the YYYY-MM-DD date format.
192 |
193 | `Example:`
194 |
195 | ```javascript
196 |
197 | function isValidDate(date) {
198 | //Your code here
199 | }
200 |
201 | // Example usage:
202 | console.log(isValidDate("2024-12-31")); // true
203 | console.log(isValidDate("31-12-2024")); // false
204 |
205 |
206 | ```
207 |
208 | `Topics Covered:`
209 | RegEx methods i.e. test()
210 |
211 | **Hints:**
212 | - [RegEx methods i.e. test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions)
213 |
214 |
215 | Solution
216 |
217 | ### Let's look at the solution:
218 |
219 | ```javascript
220 |
221 | function getQueryParameter(url, parameter) {
222 | // Create a URL object to easily parse query parameters
223 | const urlObj = new URL(url);
224 | return urlObj.searchParams.get(parameter); // Returns the value of the parameter
225 | }
226 |
227 | // Example usage:
228 | console.log(getQueryParameter("https://example.com?id=123&name=chandra", "id")); // "123"
229 |
230 |
231 | ```
232 |
233 | **Explanation:**
234 |
235 |
236 | The isValidDate function checks if a given date string is in the correct YYYY-MM-DD format.
237 |
238 | - **Steps**:
239 | 1. A regular expression (/^d{4}-d{2}-d{2}$/) is used to match:
240 | - 4 digits for the year (d{4}).
241 | - A hyphen (-).
242 | - 2 digits for the month (d{2}).
243 | - Another hyphen (-).
244 | - 2 digits for the day (d{2}).
245 | 2. dateRegex.test(date) checks if the input matches the format.
246 |
247 |
248 |
249 | ----
250 | ###### ` Question 5: Validate an IP Address`
251 |
252 | Write a function isValidIP to check if a string is a valid IP address in either IPv4 or IPv6 format.
253 |
254 | `Example:`
255 |
256 | ```javascript
257 |
258 | function isValidIP(ip) {
259 | //Your code here
260 | }
261 |
262 | // Example usage:
263 | console.log(isValidIP("192.168.1.1")); // true
264 | console.log(isValidIP("999.999.999.999")); // false
265 |
266 |
267 | ```
268 |
269 | `Topics Covered:`
270 | RegEx methods i.e. test()
271 |
272 | **Hints:**
273 | - [RegEx methods i.e. test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions)
274 |
275 |
276 | Solution
277 |
278 | ### Let's look at the solution:
279 |
280 | ```javascript
281 |
282 | function isValidIP(ip) {
283 | // Regular expression for IPv4 addresses
284 | const ipv4Regex = /^(25[0-5]|2[0-4]d|1d{2}|d{1,2})(.(?!$)){3}(25[0-5]|2[0-4]d|1d{2}|d{1,2})$/;
285 | return ipv4Regex.test(ip); // Returns true for valid IPv4, false otherwise
286 | }
287 |
288 | // Example usage:
289 | console.log(isValidIP("192.168.1.1")); // true
290 | console.log(isValidIP("999.999.999.999")); // false
291 |
292 |
293 | ```
294 |
295 | **Explanation:**
296 |
297 |
298 | The isValidIP function checks if a given string is a valid IPv4 address.
299 |
300 | - **Steps**:
301 | 1. The regular expression (ipv4Regex) breaks down IPv4 addresses into 4 numeric parts separated by dots (.):
302 | - Each part must be:
303 | - A number between 0-255.
304 | - Valid numbers: 25[0-5] (250-255), 2[0-4]d (200-249), 1d{2} (100-199), or d{1,2} (0-99).
305 | 2. The (.(?!$)){3} ensures there are exactly 3 dots, and the string doesn't end with a dot.
306 | 3. ipv4Regex.test(ip) checks if the input matches this format.
307 |
308 |
309 |
310 | ----
311 | ###### ` Question 6: Find All Hashtags in a Text`
312 |
313 | Write a function findHashtags to extract all hashtags from a text.
314 |
315 | `Example:`
316 |
317 | ```javascript
318 |
319 | function findHashtags(text) {
320 | // Your code here
321 | }
322 |
323 | // Example usage:
324 | console.log(findHashtags("I love #coding and #webdev")); // ["#coding", "#webdev"]
325 |
326 |
327 | ```
328 |
329 | `Topics Covered:`
330 | String methods i.e. match()
331 |
332 | **Hints:**
333 | - [String methods i.e. match()](https://www.w3schools.com/jsref/jsref_match.asp)
334 |
335 |
336 | Solution
337 |
338 | ### Let's look at the solution:
339 |
340 | ```javascript
341 |
342 | function findHashtags(text) {
343 | // Regular expression for hashtags
344 | const hashtagRegex = /#w+/g;
345 | return text.match(hashtagRegex) || []; // Returns all matches or an empty array
346 | }
347 |
348 | // Example usage:
349 | console.log(findHashtags("I love #coding and #webdev")); // ["#coding", "#webdev"]
350 |
351 |
352 | ```
353 |
354 | **Explanation:**
355 |
356 |
357 | The findHashtags function extracts all hashtags from a given text.
358 |
359 | - **Steps**:
360 | 1. **Regular Expression**:
361 | - #w+ matches:
362 | - A # symbol.
363 | - Followed by one or more word characters (w, which includes letters, numbers, and underscores).
364 | - The g flag ensures it finds all matches in the text.
365 | 2. text.match(hashtagRegex):
366 | - Searches the input text for hashtags matching the pattern.
367 | - If no hashtags are found, it returns an empty array (|| []).
368 |
369 |
370 |
371 | ----
372 | ###### ` Question 7: Find HTML Tags`
373 |
374 | Write a function findHTMLTags to extract all HTML tags from a string.
375 |
376 | `Example:`
377 |
378 | ```javascript
379 |
380 | function findHTMLTags(htmlString) {
381 | //Your code here
382 | }
383 |
384 | // Example usage:
385 | console.log(findHTMLTags("
Hello
")); // ["
", "
", "
", "
"]
386 |
387 |
388 | ```
389 |
390 | `Topics Covered:`
391 | String methods i.e. match()
392 |
393 | **Hints:**
394 | - [String methods i.e. match()](https://www.w3schools.com/jsref/jsref_match.asp)
395 |
396 |
397 | Solution
398 |
399 | ### Let's look at the solution:
400 |
401 | ```javascript
402 |
403 | function findHTMLTags(htmlString) {
404 | // Regular expression for HTML tags
405 | const tagRegex = /?[^>]+>/g;
406 | return htmlString.match(tagRegex) || []; // Returns all matches or an empty array
407 | }
408 |
409 | // Example usage:
410 | console.log(findHTMLTags("
Hello
")); // ["
", "
", "
", "
"]
411 |
412 |
413 | ```
414 |
415 | **Explanation:**
416 |
417 |
418 | ### How It Works:
419 | 1. **Regular Expression**:
420 | - ?: Matches the opening < and optionally the closing /.
421 | - [^>]+: Matches everything inside the tag except > (e.g., tag name and attributes).
422 | - >: Matches the closing > of the tag.
423 | - g: Global flag ensures all matching tags in the string are captured.
424 |
425 | 2. **htmlString.match(tagRegex)**:
426 | - Finds all HTML tags in the input string.
427 | - If no tags are found, it returns an empty array using || [].
428 |
429 |
430 |
431 | ----
432 | ###### ` Question 8: Extract the Domain Name from a URL`
433 |
434 | Write a function getDomain to extract the domain name from a URL.
435 |
436 | `Example:`
437 |
438 | ```javascript
439 |
440 | function getDomain(url) {
441 | //Your code here
442 | }
443 |
444 | // Example usage:
445 | console.log(getDomain("https://www.example.com/path")); // "www.example.com"
446 |
447 |
448 | ```
449 |
450 | `Topics Covered:`
451 | URL object
452 |
453 | **Hints:**
454 | - [URL object](https://javascript.info/url)
455 |
456 |
457 | Solution
458 |
459 | ### Let's look at the solution:
460 |
461 | ```javascript
462 |
463 | function getDomain(url) {
464 | // Create a URL object to extract the domain
465 | const urlObj = new URL(url);
466 | return urlObj.hostname; // Returns the domain name
467 | }
468 |
469 | // Example usage:
470 | console.log(getDomain("https://www.example.com/path")); // "www.example.com"
471 |
472 |
473 | ```
474 |
475 | **Explanation:**
476 |
477 |
478 | The getDomain function extracts the domain name from a given URL.
479 |
480 | - **Steps**:
481 | 1. **URL Object**:
482 | - It creates a URL object from the input url.
483 | 2. urlObj.hostname:
484 | - The hostname property of the URL object provides the domain name (e.g., www.example.com).
485 |
486 |
487 |
488 | ----
489 | ###### ` Question 9: Find Hex Color Codes`
490 |
491 | Write a function findHexColors to extract all valid hex color codes from a string.
492 |
493 | `Example:`
494 |
495 | ```javascript
496 |
497 | function findHexColors(text) {
498 | //Your code here
499 | }
500 |
501 | // Example usage:
502 | console.log(findHexColors("The colors are #FF5733 and #f73.")); // ["#FF5733", "#f73"]
503 |
504 |
505 | ```
506 |
507 | `Topics Covered:`
508 | URL object
509 |
510 | **Hints:**
511 | - [URL object](https://javascript.info/url)
512 |
513 |
514 | Solution
515 |
516 | ### Let's look at the solution:
517 |
518 | ```javascript
519 |
520 | function findHexColors(text) {
521 | // Regular expression for hex color codes
522 | const hexRegex = /#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})\b/g;
523 | return text.match(hexRegex) || []; // Returns all matches or an empty array
524 | }
525 |
526 | // Example usage:
527 | console.log(findHexColors("The colors are #FF5733 and #f73.")); // ["#FF5733", "#f73"]
528 |
529 |
530 | ```
531 |
532 | **Explanation:**
533 |
534 |
535 | The function findHexColors uses a regular expression (hexRegex) to find all hexadecimal color codes (like #FF5733) in a given text.
536 |
537 | ## Regular Expression Breakdown:
538 |
539 | The regular expression used in the function matches color codes that are either 3 or 6 characters long, consisting of letters (a-f, A-F) and digits (0-9).
540 |
541 | ### Regex: /#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})\b/g
542 |
543 | - #([a-fA-F0-9]{3}|[a-fA-F0-9]{6}):
544 | - This part of the regex captures color codes that are either 3 or 6 characters long, following the # symbol.
545 |
546 | - \b:
547 | - Ensures the match ends at a word boundary, meaning it won't match partial strings.
548 |
549 | - text.match(hexRegex) :
550 | - This method returns an array of all the matching color codes found in the text. If no matches are found, it returns an empty array.
551 |
552 |
553 |
554 |
555 | ----
556 |
--------------------------------------------------------------------------------
/resources/Numbers/readme.md:
--------------------------------------------------------------------------------
1 | # Numbers
2 |
3 |
4 | ###### ` Question 1: Convert a string to a valid number`
5 |
6 | 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.
7 |
8 | `Example:`
9 |
10 | ```javascript
11 |
12 | function convertToNumber(str) {
13 | // Your code here
14 | }
15 |
16 | console.log(convertToNumber("123")); // 123
17 | console.log(convertToNumber("abc")); // NaN
18 |
19 | ```
20 |
21 | `Topics Covered:`
22 | Number methods i.e. Number(), isNaN()
23 |
24 | **Hints:**
25 | - [isNaN()](https://www.w3schools.com/jsref/jsref_isnan.asp), - [JS Numbers](https://www.w3schools.com/jsref/jsref_number.asp)
26 |
27 |
28 | Solution
29 |
30 | ### Let's look at the solution:
31 |
32 | ```javascript
33 |
34 | function convertToNumber(str) {
35 | const number = Number(str); // Try to convert the string to a number
36 | return isNaN(number) ? NaN : number; // If conversion fails, return NaN
37 | }
38 |
39 | console.log(convertToNumber("123")); // 123
40 | console.log(convertToNumber("abc")); // NaN
41 | console.log(convertToNumber("12.34")); // 12.34
42 |
43 | ```
44 |
45 | **Explanation:**
46 |
47 |
48 | - Number(str): tries to convert the string to a number.
49 | - isNaN(number): checks if the result is not a valid number and returns NaN if it's invalid.
50 |
51 |
52 |
53 | ----
54 | ###### ` Question 2: Round a number to the nearest integer`
55 |
56 | Write a function that rounds a number to the nearest whole number.
57 |
58 | `Example:`
59 |
60 | ```javascript
61 |
62 | function roundNumber(num) {
63 | // Your code here
64 | }
65 | console.log(roundNumber(4.3)); // 4
66 | console.log(roundNumber(4.7)); // 5
67 |
68 | ```
69 |
70 | `Topics Covered:`
71 | math.round()
72 |
73 | **Hints:**
74 | - [math.round()](https://www.w3schools.com/jsref/jsref_round.asp)
75 |
76 |
77 | Solution
78 |
79 | ### Let's look at the solution:
80 |
81 | ```javascript
82 |
83 | function roundToNearestInteger(num) {
84 | return Math.round(num); // Rounds the number to the nearest integer
85 | }
86 |
87 | console.log(roundToNearestInteger(4.5)); // 5
88 | console.log(roundToNearestInteger(4.4)); // 4
89 | console.log(roundToNearestInteger(-1.5)); // -1
90 |
91 | ```
92 |
93 | **Explanation:**
94 |
95 |
96 | - Math.round(num) rounds the number to the nearest integer.
97 | - If the decimal part is 0.5 or greater, it rounds up.
98 | Otherwise, it rounds down.
99 |
100 |
101 |
102 | ----
103 | ###### ` Question 3: Working with Large Numbers: Formatting and Display`
104 |
105 | Write a function formatLargeNumber that converts a large number into a user-friendly format (e.g., 1.5K, 3.5M).
106 |
107 | `Example:`
108 |
109 | ```javascript
110 |
111 | function formatLargeNumber(number) {
112 |
113 | }
114 |
115 | // Example usage
116 | console.log(formatLargeNumber(1500)); // Output: "1.5K"
117 | console.log(formatLargeNumber(3500000)); // Output: "3.5M"
118 | console.log(formatLargeNumber(950)); // Output: "950"
119 |
120 | ```
121 |
122 | `Topics Covered:`
123 | Number methods i.e. toFixed()
124 |
125 | **Hints:**
126 | - [Number methods i.e. toFixed()](https://www.w3schools.com/jsref/jsref_tofixed.asp)
127 |
128 |
129 | Solution
130 |
131 | ### Let's look at the solution:
132 |
133 | ```javascript
134 |
135 | function formatLargeNumber(number) {
136 | if (number >= 1_000_000) {
137 | // Convert to millions (M) and format to one decimal place
138 | return (number / 1_000_000).toFixed(1) + "M";
139 | } else if (number >= 1_000) {
140 | // Convert to thousands (K) and format to one decimal place
141 | return (number / 1_000).toFixed(1) + "K";
142 | } else {
143 | // If the number is less than 1000, just return it as a string
144 | return number.toString();
145 | }
146 | }
147 |
148 | // Example usage
149 | console.log(formatLargeNumber(1500)); // Output: "1.5K"
150 | console.log(formatLargeNumber(3500000)); // Output: "3.5M"
151 | console.log(formatLargeNumber(950)); // Output: "950"
152 |
153 | ```
154 |
155 | **Explanation:**
156 |
157 |
158 | - Check the range of the number and format it based on its value.
159 | - If the number is ≥ 1,000,000, convert it to millions, round to 1 decimal place, and append "M".
160 | - ßIf the number is ≥ 1,000, convert it to thousands, round to 1 decimal place, and append "K".
161 | - ßIf the number is < 1,000, return it as-is.
162 | - ßConvert numbers not meeting the "K" or "M" conditions to a string using .toString().
163 | - ßHandle edge cases for numbers less than 1,000 without adding "K" or "M".
164 | - ßEnsure rounding provides clean and readable output like 1.5K instead of 1.500K.
165 |
166 |
167 |
168 |
169 | ----
170 | ###### ` Question 4: Optimizing Price Calculation with Bulk Discount`
171 |
172 | Write a function calculateBulkDiscount that calculates the total cost for bulk orders, applying a discount when the quantity exceeds a threshold.
173 |
174 | `Example:`
175 |
176 | ```javascript
177 |
178 | function calculateBulkDiscount(price, quantity, discountThreshold, discountRate) {
179 |
180 | }
181 |
182 | // Example usage
183 | console.log(calculateBulkDiscount(50, 15, 10, 10)); // Output: 675
184 | console.log(calculateBulkDiscount(50, 5, 10, 10)); // Output: 250
185 | console.log(calculateBulkDiscount(100, 20, 15, 20)); // Output: 1600
186 |
187 | ```
188 |
189 | `Topics Covered:`
190 | Operators i.e arithmetic operators
191 |
192 | **Hints:**
193 | - [Operators i.e arithmetic operators](https://www.w3schools.com/js/js_arithmetic.asp)
194 |
195 |
196 | Solution
197 |
198 | ### Let's look at the solution:
199 |
200 | ```javascript
201 |
202 | function calculateBulkDiscount(price, quantity, discountThreshold, discountRate) {
203 | // Check if the quantity exceeds the discount threshold
204 | if (quantity > discountThreshold) {
205 | // Apply the discount rate to the price
206 | const discountedPrice = price * (1 - discountRate / 100);
207 | // Calculate the total cost with the discounted price
208 | return discountedPrice * quantity;
209 | } else {
210 | // No discount applied; calculate the total cost with the original price
211 | return price * quantity;
212 | }
213 | }
214 |
215 | // Example usage
216 | console.log(calculateBulkDiscount(50, 15, 10, 10)); // Output: 675
217 | console.log(calculateBulkDiscount(50, 5, 10, 10)); // Output: 250
218 | console.log(calculateBulkDiscount(100, 20, 15, 20)); // Output: 1600
219 |
220 | ```
221 |
222 | **Explanation:**
223 |
224 |
225 | - Check the range of the quantity and apply discount if applicable.
226 | - If the quantity is greater than or equal to the discountThreshold, calculate the discounted price and multiply it by - the quantity to get the total cost.
227 | - If the quantity is less than the discountThreshold, multiply the original price by the quantity without applying any discount.
228 | - Handle calculations involving prices and quantities as numbers without explicit string conversion.
229 | - Ensure no discount is applied if the quantity is less than or equal to the discountThreshold.
230 | - Use the original price without changes if the discountRate is 0.
231 | - Handle large numbers and high discount percentages accurately.
232 | - Round results to ensure clean and readable output without unnecessary decimal places.
233 |
234 |
235 |
236 |
237 | ----
238 | ###### ` Question 5: Calculating the Time Remaining for a Sale`
239 |
240 | Write a function calculateTimeRemaining that calculates the remaining time between two timestamps in hours, minutes, and seconds.
241 |
242 | `Example:`
243 |
244 | ```javascript
245 |
246 | function calculateTimeRemaining(startTime, endTime) {
247 | //your code here
248 | }
249 |
250 | // Example usage
251 | console.log(calculateTimeRemaining("2024-12-18T00:00:00Z", "2024-12-31T23:59:59Z"));
252 | // Output: { hours: 359, minutes: 59, seconds: 59 }
253 |
254 | console.log(calculateTimeRemaining("2024-12-18T12:00:00Z", "2024-12-19T14:30:45Z"));
255 | // Output: { hours: 26, minutes: 30, seconds: 45 }
256 |
257 | ```
258 |
259 | `Topics Covered:`
260 | Date and Time, math.floor()
261 |
262 | **Hints:**
263 | - [math.floor()](https://www.w3schools.com/jsref/jsref_floor.asp), - [Date and Time](https://www.w3schools.com/js/js_dates.asp)
264 |
265 |
266 | Solution
267 |
268 | ### Let's look at the solution:
269 |
270 | ```javascript
271 |
272 | function calculateTimeRemaining(startTime, endTime) {
273 | // Convert the input timestamps to Date objects
274 | const start = new Date(startTime);
275 | const end = new Date(endTime);
276 |
277 | // Calculate the difference in milliseconds
278 | const difference = end - start;
279 |
280 | // Convert the difference into hours, minutes, and seconds
281 | const totalSeconds = Math.floor(difference / 1000); // Total seconds
282 | const hours = Math.floor(totalSeconds / 3600); // Total hours
283 | const minutes = Math.floor((totalSeconds % 3600) / 60); // Remaining minutes
284 | const seconds = totalSeconds % 60; // Remaining seconds
285 |
286 | return { hours, minutes, seconds };
287 | }
288 |
289 | // Example usage
290 | console.log(calculateTimeRemaining("2024-12-18T00:00:00Z", "2024-12-31T23:59:59Z"));
291 | // Output: { hours: 359, minutes: 59, seconds: 59 }
292 |
293 | console.log(calculateTimeRemaining("2024-12-18T12:00:00Z", "2024-12-19T14:30:45Z"));
294 | // Output: { hours: 26, minutes: 30, seconds: 45 }
295 |
296 | ```
297 |
298 | **Explanation:**
299 |
300 | - Convert startTime and endTime from ISO 8601 strings to Date objects using JavaScript's Date constructor.
301 | - Calculate the time difference in milliseconds by subtracting the start date from the end date.
302 | - Convert the milliseconds difference to total seconds using Math.floor.
303 | - Calculate hours by dividing total seconds by 3600 and rounding down using Math.floor.
304 | - Calculate minutes by using the modulo operator (% 3600) to get remaining seconds after hours, then dividing by 60.
305 | - Calculate seconds using modulo 60 to get the remaining seconds after minutes.
306 | - Return an object with properties hours, minutes, and seconds.
307 | - Handle edge cases like a start time after the end time (negative values) and identical start and end times (zero values).
308 |
309 |
310 |
311 |
312 | ----
313 | ###### ` Question 6: Generating a Random Number in a Range`
314 |
315 | Write a function generateRandomNumber that generates a random number between a given minimum and maximum value (inclusive).
316 |
317 | `Example:`
318 |
319 | ```javascript
320 |
321 | function generateRandomNumber(min, max) {
322 | //Your code here
323 | }
324 |
325 | // Example usage
326 | console.log(generateRandomNumber(1, 10)); // Output: A random number between 1 and 10 (e.g., 7)
327 | console.log(generateRandomNumber(5, 15)); // Output: A random number between 5 and 15 (e.g., 12)
328 |
329 | ```
330 |
331 | `Topics Covered:`
332 | Math methods i.e. math.floor()
333 |
334 | **Hints:**
335 | - [math.floor()](https://www.w3schools.com/jsref/jsref_floor.asp)
336 |
337 |
338 | Solution
339 |
340 | ### Let's look at the solution:
341 |
342 | ```javascript
343 |
344 | function generateRandomNumber(min, max) {
345 | // Generate a random number between min and max (inclusive)
346 | return Math.floor(Math.random() * (max - min + 1)) + min;
347 | }
348 |
349 | // Example usage
350 | console.log(generateRandomNumber(1, 10)); // Output: A random number between 1 and 10 (e.g., 7)
351 | console.log(generateRandomNumber(5, 15)); // Output: A random number between 5 and 15 (e.g., 12)
352 |
353 | ```
354 |
355 | **Explanation:**
356 |
357 | - Math.random() generates a random floating-point number between 0 (inclusive) and 1 (exclusive).
358 | - Scale the random number to the desired range by multiplying it by (max - min + 1).
359 | - Use Math.floor() to round down the scaled number to the nearest whole number, ensuring an integer result.
360 | - Add the min value to shift the random number into the correct range starting from the specified min.
361 | - Use the formula: Random Number = Math.floor(Math.random() * (max - min + 1)) + min.
362 | - If min equals max, the function always returns that number (e.g., generateRandomNumber(5, 5) returns 5).
363 | - Handles both positive and negative ranges, allowing random numbers to be generated within negative ranges (e.g., -10 to -5).
364 |
365 |
366 |
367 |
368 | ----
369 | ###### ` Question 7: Converting a Number to Binary`
370 |
371 | Write a function convertToBinary that converts a given number into its binary representation as a string.
372 |
373 | `Example:`
374 |
375 | ```javascript
376 |
377 | function convertToBinary(number) {
378 | //Your code here
379 | }
380 |
381 | // Example usage
382 | console.log(convertToBinary(10)); // Output: "1010"
383 | console.log(convertToBinary(255)); // Output: "11111111"
384 | console.log(convertToBinary(0)); // Output: "0"
385 |
386 | ```
387 |
388 | `Topics Covered:`
389 | Numbers, String methods i.e. toString()
390 |
391 | **Hints:**
392 | - [Numbers](https://www.w3schools.com/jsref/jsref_floor.asp), - [String methods i.e. toString()](https://www.w3schools.com/js/js_string_methods.asp)
393 |
394 |
395 | Solution
396 |
397 | ### Let's look at the solution:
398 |
399 | ```javascript
400 |
401 | function convertToBinary(number) {
402 | // Use the built-in toString() method with a base of 2
403 | return number.toString(2);
404 | }
405 |
406 | // Example usage
407 | console.log(convertToBinary(10)); // Output: "1010"
408 | console.log(convertToBinary(255)); // Output: "11111111"
409 | console.log(convertToBinary(0)); // Output: "0"
410 |
411 | ```
412 |
413 | **Explanation:**
414 |
415 |
416 | - Use the toString() method of numbers in JavaScript to convert a number into a string representation in any base (2 to 36).
417 | - For binary conversion, use a base of 2 with the syntax number.toString(2) to get the binary equivalent of the number.
418 | - Pass the number as an argument to the convertToBinary function and apply toString(2) for conversion.
419 | - Handle edge cases like 0, where the output will be "0".
420 | - The function works for both small and large integers, returning their binary representations as strings.
421 |
422 |
423 |
424 | ----
425 | ###### ` Question 8: Calculate Electricity Bill`
426 |
427 | Write a function calculateElectricityBill that calculates the total electricity bill based on units consumed and the cost per unit.
428 |
429 | `Example:`
430 |
431 | ```javascript
432 |
433 | function calculateElectricityBill(units, costPerUnit) {
434 | //Your code here
435 | }
436 |
437 | // Example usage
438 | console.log(calculateElectricityBill(250, 5)); // Output: 1250
439 | console.log(calculateElectricityBill(100, 10)); // Output: 1000
440 | console.log(calculateElectricityBill(0, 5)); // Output: 0
441 |
442 | ```
443 |
444 | `Topics Covered:`
445 | Arithmetics operator
446 |
447 | **Hints:**
448 | - [Arithmetics operator](https://www.w3schools.com/js/js_arithmetic.asp)
449 |
450 |
451 | Solution
452 |
453 | ### Let's look at the solution:
454 |
455 | ```javascript
456 |
457 | function calculateElectricityBill(units, costPerUnit) {
458 | // Multiply the units consumed by the cost per unit to calculate the total bill
459 | return units * costPerUnit;
460 | }
461 |
462 | // Example usage
463 | console.log(calculateElectricityBill(250, 5)); // Output: 1250
464 | console.log(calculateElectricityBill(100, 10)); // Output: 1000
465 | console.log(calculateElectricityBill(0, 5)); // Output: 0
466 |
467 | ```
468 |
469 | **Explanation:**
470 |
471 | - Accept units (number of electricity units consumed) and costPerUnit (cost of electricity per unit) as inputs.
472 | - Multiply units by costPerUnit to calculate the total bill.
473 | - Return the calculated total bill.
474 |
475 |
476 |
477 |
478 | ----
--------------------------------------------------------------------------------