` 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/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/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/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/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 | ----
--------------------------------------------------------------------------------
/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/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/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/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/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/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/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/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/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------