JavaScript Programs for Date and Time
JavaScript Programs for Date and Time
html
[Link]
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>Your HTML Page</title>
7
8 <!-- Link your external JavaScript file -->
9 <script src="[Link]" defer></script>
10 </head>
11 <body>
12 <h4>
13 1. Write a JavaScript program to display the current day and time in the
14 following format. Sample Output : Today is : Tuesday. Current time is : 10
15 PM : 30 : 38
16 </h4>
17 <!-- Your HTML content goes here -->
18 <div id="currentDayAndTime"></div>
19
20 <script>
21 // Your JavaScript code goes here
22 function getCurrentDayAndTime() {
23 // Days of the week
24 const daysOfWeek = [
25 "Sunday",
26 "Monday",
27 "Tuesday",
28 "Wednesday",
29 "Thursday",
30 "Friday",
31 "Saturday",
32 ];
33
34 // Get current date and time
35 const currentDate = new Date();
36 const currentDay = daysOfWeek[[Link]()]; // Get day of the week
37
38 // Get current time
39 let hours = [Link]();
40 const ampm = hours >= 12 ? "PM" : "AM";
41 hours = hours % 12 || 12; // Convert 24-hour format to 12-hour format
42 const minutes = [Link]();
43 const seconds = [Link]();
44
45 // Format the time components with leading zeros if needed
46 const formattedTime = `${hours} ${ampm} : ${
47 minutes < 10 ? "0" : ""
48 }${minutes} : ${seconds < 10 ? "0" : ""}${seconds}`;
49
50 // Display the result in the element with id "currentDayAndTime"
51 const resultElement = [Link]("currentDayAndTime");
52 [Link] = `Today is: ${currentDay}. Current time is:
${formattedTime}`;
53 }
54
55 // Call the function to display the current day and time
56 getCurrentDayAndTime();
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 1/298
1/31/24, 9:21 AM [Link]
57 </script>
58
59 <hr />
60
61 <h4>
62 2. Write a JavaScript program to print the contents of the current window.
63 </h4>
64 <script>
65 // Your JavaScript code goes here
66 function printWindowContents() {
67 [Link]();
68 }
69 </script>
70
71 <button onclick="printWindowContents()">Print Window Contents</button>
72 <hr />
73
74 <h4>
75 [Link] a JavaScript program to get the current date. Expected Output
76 :mm-dd-yyyy, mm/dd/yyyy or dd-mm-yyyy, dd/mm/yyyy
77 </h4>
78 <button onclick="getCurrentDate('mm-dd-yyyy')">mm-dd-yyyy</button>
79 <button onclick="getCurrentDate('mm/dd/yyyy')">mm/dd/yyyy</button>
80 <button onclick="getCurrentDate('dd-mm-yyyy')">dd-mm-yyyy</button>
81 <button onclick="getCurrentDate('dd/mm/yyyy')">dd/mm/yyyy</button>
82
83 <script>
84 // Your JavaScript code goes here
85 function getCurrentDate(format) {
86 const currentDate = new Date();
87
88 const day = [Link]();
89 const month = [Link]() + 1; // Months are zero-indexed, so we add
1
90 const year = [Link]();
91
92 // Format the date based on the provided format
93 switch (format) {
94 case "mm-dd-yyyy":
95 alert(
96 `${month < 10 ? "0" : ""}${month}-${
97 day < 10 ? "0" : ""
98 }${day}-${year}`
99 );
100 break;
101 case "mm/dd/yyyy":
102 alert(
103 `${month < 10 ? "0" : ""}${month}/${
104 day < 10 ? "0" : ""
105 }${day}/${year}`
106 );
107 break;
108 case "dd-mm-yyyy":
109 alert(
110 `${day < 10 ? "0" : ""}${day}-${
111 month < 10 ? "0" : ""
112 }${month}-${year}`
113 );
114 break;
115 case "dd/mm/yyyy":
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 2/298
1/31/24, 9:21 AM [Link]
116 alert(
117 `${day < 10 ? "0" : ""}${day}/${
118 month < 10 ? "0" : ""
119 }${month}/${year}`
120 );
121 break;
122 default:
123 alert("Invalid date format specified.");
124 }
125 }
126 </script>
127 <hr />
128 <h4>
129 4. Write a JavaScript program to find the area of a triangle where lengths
130 of the three of its sides are 5, 6, 7.
131 </h4>
132 <button onclick="calculateAndDisplayArea()">Calculate Area</button>
133
134 <p id="result"></p>
135
136 <script>
137 // Your JavaScript code goes here
138 function calculateTriangleArea(a, b, c) {
139 // Calculate the semi-perimeter
140 const s = (a + b + c) / 2;
141
142 // Calculate the area using Heron's formula
143 const area = [Link](s * (s - a) * (s - b) * (s - c));
144
145 return area;
146 }
147
148 function calculateAndDisplayArea() {
149 // Given side lengths of the triangle
150 const sideA = 5;
151 const sideB = 6;
152 const sideC = 7;
153
154 // Calculate the area
155 const triangleArea = calculateTriangleArea(sideA, sideB, sideC);
156
157 // Display the result
158 const resultElement = [Link]("result");
159 [Link] = `The area of the triangle with sides ${sideA},
${sideB}, ${sideC} is: ${triangleArea}`;
160 }
161 </script>
162 <hr />
163
164 <h4>
165 5. Write a JavaScript program to rotate the string 'The InfoMatrix Digital
166 Services' in right direction by periodically removing one letter from the
167 end of the string and attaching it to the front
168 </h4>
169
170 <p id="rotatedString"></p>
171
172 <script>
173 // Your JavaScript code goes here
174 function rotateString(str) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 3/298
1/31/24, 9:21 AM [Link]
175 // Rotate the string to the right by removing one letter from the end and
attaching it to the front
176 const rotatedString =
177 [Link]([Link] - 1) + [Link](0, [Link] - 1);
178 return rotatedString;
179 }
180
181 // Initial string
182 const originalString = "The InfoMatrix Digital Services";
183
184 // Display the initial string
185 [Link](
186 "rotatedString"
187 ).textContent = `Original String: ${originalString}`;
188
189 // Rotate the string every second (adjust the interval as needed)
190 setInterval(function () {
191 // Rotate the string
192 const rotatedString = rotateString(originalString);
193
194 // Display the rotated string
195 [Link](
196 "rotatedString"
197 ).textContent = `Rotated String: ${rotatedString}`;
198
199 // Update the original string for the next rotation
200 originalString = rotatedString;
201 }, 1000); // 1000 milliseconds = 1 second
202 </script>
203 <hr />
204
205 <h4>
206 [Link] a JavaScript program to determine whether a given year is a leap
207 year in the Gregorian calendar.
208 </h4>
209
210 <p>Enter a year to check if it's a leap year:</p>
211 <input type="number" id="yearInput" placeholder="Enter year" />
212 <button onclick="checkLeapYear()">Check</button>
213
214 <p id="result1"></p>
215
216 <script>
217 // Your JavaScript code goes here
218 function isLeapYear(year) {
219 // Leap year conditions in the Gregorian calendar
220 if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
221 return true;
222 } else {
223 return false;
224 }
225 }
226
227 function checkLeapYear() {
228 // Get the input year from the user
229 const inputYear = [Link]("yearInput").value;
230
231 // Check if it's a leap year
232 if (isLeapYear(inputYear)) {
233 [Link](
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 4/298
1/31/24, 9:21 AM [Link]
234 "result1"
235 ).textContent = `${inputYear} is a leap year.`;
236 } else {
237 [Link](
238 "result1"
239 ).textContent = `${inputYear} is not a leap year.`;
240 }
241 }
242 </script>
243
244 <h4>
245 [Link] a JavaScript program to find 1st January is being a Sunday between
246 2014 and 2050?
247 </h4>
248 <ul id="sundayYears"></ul>
249
250 <script>
251 // Your JavaScript code goes here
252 function findSundayYears() {
253 const sundayYearsList = [Link]("sundayYears");
254 [Link] = ""; // Clear previous results
255
256 for (let year = 2014; year <= 2050; year++) {
257 const januaryFirst = new Date(year, 0, 1); // Month is zero-indexed (0 =
January)
258
259 // Check if January 1st is a Sunday (getDay() returns 0 for Sunday)
260 if ([Link]() === 0) {
261 const listItem = [Link]("li");
262 [Link] = year;
263 [Link](listItem);
264 }
265 }
266 }
267
268 // Find and display years where January 1st is a Sunday
269 findSundayYears();
270 </script>
271 <hr />
272
273 <h4>
274 8. Write a JavaScript program where the program takes a random integer
275 between 1 to 10, the user is then prompted to input a guess number. If the
276 user input matches with guess number, the program will display a message
277 "Good Work" otherwise display a message "Not matched".
278 </h4>
279 <h6 id="gameTitle">Number Guessing Game</h6>
280
281 <button id="guessButton">Guess a Number</button>
282
283 <script id="gameScript">
284 // Your JavaScript code goes here
285 function playNumberGuessingGame() {
286 // Generate a random integer between 1 and 10
287 const randomNumber = [Link]([Link]() * 10) + 1;
288
289 // Prompt the user to input a guess number
290 const userGuess = prompt("Guess a number between 1 and 10:");
291
292 // Check if the user's guess matches the random number
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 5/298
1/31/24, 9:21 AM [Link]
293 if (userGuess !== null) {
294 // Check if the user clicked Cancel
295 const guessNumber = parseInt(userGuess, 10);
296
297 if (!isNaN(guessNumber)) {
298 if (guessNumber === randomNumber) {
299 alert("Good Work! You guessed the correct number.");
300 } else {
301 alert(`Not matched. The correct number was ${randomNumber}.`);
302 }
303 } else {
304 alert("Please enter a valid number.");
305 }
306 }
307 }
308
309 // Assign a click event to the button to trigger the game
310 const guessButton = [Link]("guessButton");
311 [Link]("click", playNumberGuessingGame);
312 </script>
313
314 <hr />
315 <h4>
316 9. Write a JavaScript program to calculate days left until next Christmas.
317 </h4>
318
319 <p id="daysLeft"></p>
320
321 <script>
322 // Your JavaScript code goes here
323 function calculateDaysUntilChristmas() {
324 // Get the current date
325 const currentDate = new Date();
326
327 // Get the next Christmas date
328 const nextChristmas = new Date([Link](), 11, 25); // Month is
zero-indexed (11 = December)
329
330 // If Christmas has already passed this year, set it to next year
331 if (currentDate > nextChristmas) {
332 [Link]([Link]() + 1);
333 }
334
335 // Calculate the difference in days
336 const timeDifference = nextChristmas - currentDate;
337 const daysLeft = [Link](timeDifference / (1000 * 60 * 60 * 24));
338
339 // Display the result
340 const daysLeftElement = [Link]("daysLeft");
341 [Link] = `Days left until Christmas: ${daysLeft} days`;
342 }
343
344 // Calculate and display days until Christmas when the page loads
345 calculateDaysUntilChristmas();
346 </script>
347
348 <hr />
349
350 <h4>
351 [Link] a JavaScript program to calculate multiplication and division of
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 6/298
1/31/24, 9:21 AM [Link]
352 two numbers (input from user). a. Sample form :
353 </h4>
354 <form id="calculatorForm">
355 <label for="number1">Enter Number 1:</label>
356 <input type="number" id="number1" required />
357
358 <label for="number2">Enter Number 2:</label>
359 <input type="number" id="number2" required />
360
361 <button type="button" onclick="calculate()">Calculate</button>
362 </form>
363
364 <p id="result2"></p>
365
366 <script>
367 // Your JavaScript code goes here
368 function calculate() {
369 // Get user input
370 const number1 = parseFloat([Link]("number1").value);
371 const number2 = parseFloat([Link]("number2").value);
372
373 // Check if the input is valid
374 if (!isNaN(number1) && !isNaN(number2)) {
375 // Perform multiplication and division
376 const multiplicationResult = number1 * number2;
377 const divisionResult = number1 / number2;
378
379 // Display the results
380 const resultElement = [Link]("result2");
381 [Link] = `Multiplication Result: ${multiplicationResult},
Division Result: ${divisionResult}`;
382 } else {
383 alert("Please enter valid numbers.");
384 }
385 }
386 </script>
387 <hr />
388
389 <h4>
390 11. Write a JavaScript program to convert temperatures to and from
391 Celsius, Fahrenheit. [ Formula : c/5 = (f-32)/9 [ where c = temperature in
392 Celsius and f = temperature in Fahrenheit ] Expected Output : 60°C is 140
393 °F 45°F is 7.222222222222222°C
394 </h4>
395 <form id="converterForm">
396 <label for="temperature">Enter Temperature:</label>
397 <input type="number" id="temperature" required />
398
399 <label for="unit">Select Unit:</label>
400 <select id="unit" required>
401 <option value="celsius">Celsius</option>
402 <option value="fahrenheit">Fahrenheit</option>
403 </select>
404
405 <button type="button" onclick="convertTemperature()">Convert</button>
406 </form>
407
408 <p id="result3"></p>
409
410 <script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 7/298
1/31/24, 9:21 AM [Link]
411 // Your JavaScript code goes here
412 function convertTemperature() {
413 // Get user input
414 const temperature = parseFloat(
415 [Link]("temperature").value
416 );
417 const unit = [Link]("unit").value;
418
419 // Check if the input is valid
420 if (!isNaN(temperature)) {
421 // Convert temperature based on the selected unit
422 let convertedTemperature;
423 let resultUnit;
424
425 if (unit === "celsius") {
426 convertedTemperature = (temperature * 9) / 5 + 32;
427 resultUnit = "Fahrenheit";
428 } else {
429 convertedTemperature = ((temperature - 32) * 5) / 9;
430 resultUnit = "Celsius";
431 }
432
433 // Display the result
434 const resultElement = [Link]("result3");
435 [Link] = `${temperature}°${
436 [Link](0).toUpperCase() + [Link](1)
437 } is ${[Link](2)} °${resultUnit}`;
438 } else {
439 alert("Please enter a valid temperature.");
440 }
441 }
442 </script>
443 <hr />
444
445 <h4>
446 [Link] a JavaScript program to get the website URL (loading page).
447 </h4>
448 <p id="urlDisplay"></p>
449
450 <script>
451 // Your JavaScript code goes here
452 function displayURL() {
453 // Get the current URL
454 const currentURL = [Link];
455
456 // Display the URL
457 const urlDisplayElement = [Link]("urlDisplay");
458 [Link] = `Website URL: ${currentURL}`;
459 }
460
461 // Call the function when the page loads
462 displayURL();
463 </script>
464 <hr />
465
466 <h4>
467 13. Write a JavaScript exercise to create a variable using a user-defined
468 name.
469 </h4>
470 <form id="variableForm">
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 8/298
1/31/24, 9:21 AM [Link]
471 <label for="variableName">Enter Variable Name:</label>
472 <input type="text" id="variableName" required />
473
474 <label for="variableValue">Enter Variable Value:</label>
475 <input type="text" id="variableValue" required />
476
477 <button type="button" onclick="createVariable()">Create Variable</button>
478 </form>
479
480 <p id="result4"></p>
481
482 <script>
483 // Your JavaScript code goes here
484 function createVariable() {
485 // Get user input for variable name and value
486 const variableName = [Link]("variableName").value;
487 const variableValue = [Link]("variableValue").value;
488
489 // Check if the input is valid
490 if ([Link]() !== "") {
491 // Create an object to simulate a variable with a user-defined name
492 const userDefinedVariable = {};
493 userDefinedVariable[variableName] = variableValue;
494
495 // Display the result
496 const resultElement = [Link]("result4");
497 [Link] = `Variable ${variableName} created with value:
${userDefinedVariable[variableName]}`;
498 } else {
499 alert("Please enter a valid variable name.");
500 }
501 }
502 </script>
503 <hr />
504
505 <h4>14. Write a JavaScript exercise to get the extension of a filename.</h4>
506 <form id="extensionForm">
507 <label for="filename">Enter Filename:</label>
508 <input type="text" id="filename" required />
509
510 <button type="button" onclick="getFileExtension()">Get Extension</button>
511 </form>
512
513 <p id="result5"></p>
514
515 <script>
516 // Your JavaScript code goes here
517 function getFileExtension() {
518 // Get user input for filename
519 const filename = [Link]("filename").value;
520
521 // Check if the input is not empty
522 if ([Link]() !== "") {
523 // Use a regular expression to extract the file extension
524 const fileExtension = [Link](".").pop();
525
526 // Display the result
527 const resultElement = [Link]("result5");
528 [Link] = `File extension: ${fileExtension}`;
529 } else {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 9/298
1/31/24, 9:21 AM [Link]
530 alert("Please enter a valid filename.");
531 }
532 }
533 </script>
534 <hr />
535
536 <h4>
537 15. Write a JavaScript program to get the difference between a given
538 number and 13, if the number is greater than 13 return double the absolute
539 difference.
540 </h4>
541 <form id="differenceForm">
542 <label for="inputNumber">Enter a Number:</label>
543 <input type="number" id="inputNumber" required />
544
545 <button type="button" onclick="calculateDifference()">
546 Calculate Difference
547 </button>
548 </form>
549
550 <p id="result6"></p>
551
552 <script>
553 // Your JavaScript code goes here
554 function calculateDifference() {
555 // Get user input
556 const inputNumber = parseFloat(
557 [Link]("inputNumber").value
558 );
559
560 // Check if the input is valid
561 if (!isNaN(inputNumber)) {
562 // Calculate the difference
563 const difference = [Link](inputNumber - 13);
564
565 // If the number is greater than 13, return double the absolute difference
566 const result = inputNumber > 13 ? difference * 2 : difference;
567
568 // Display the result
569 const resultElement = [Link]("result6");
570 [Link] = `The calculated difference is: ${result}`;
571 } else {
572 alert("Please enter a valid number.");
573 }
574 }
575 </script>
576 <hr />
577
578 <h4>
579 16. Write a JavaScript program to compute the sum of the two given
580 integers. If the two values are same, then returns triple their sum.
581 </h4>
582 <form id="sumForm">
583 <label for="number1">Enter Integer 1:</label>
584 <input type="number" id="number1" required />
585
586 <label for="number2">Enter Integer 2:</label>
587 <input type="number" id="number2" required />
588
589 <button type="button" onclick="computeSum()">Compute Sum</button>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 10/298
1/31/24, 9:21 AM [Link]
590 </form>
591
592 <p id="result7"></p>
593
594 <script>
595 // Your JavaScript code goes here
596 function computeSum() {
597 // Get user input for two integers
598 const integer1 = parseInt([Link]("number1").value);
599 const integer2 = parseInt([Link]("number2").value);
600
601 // Check if the inputs are valid integers
602 if (!isNaN(integer1) && !isNaN(integer2)) {
603 // Calculate the sum
604 const sum = integer1 + integer2;
605
606 // If the two values are the same, return triple their sum
607 const result = integer1 === integer2 ? sum * 3 : sum;
608
609 // Display the result
610 const resultElement = [Link]("result7");
611 [Link] = `The computed sum is: ${result}`;
612 } else {
613 alert("Please enter valid integers.");
614 }
615 }
616 </script>
617 <hr />
618
619 <h4>
620 17. Write a JavaScript program to compute the absolute difference between
621 a specified number and 19. Returns triple their absolute difference if the
622 specified number is greater than 19.
623 </h4>
624 <form id="differenceForm">
625 <label for="specifiedNumber">Enter a Number:</label>
626 <input type="number" id="specifiedNumber" required />
627
628 <button type="button" onclick="computeAbsoluteDifference()">
629 Compute Absolute Difference
630 </button>
631 </form>
632
633 <p id="result8"></p>
634
635 <script>
636 // Your JavaScript code goes here
637 function computeAbsoluteDifference() {
638 // Get user input for a specified number
639 const specifiedNumber = parseFloat(
640 [Link]("specifiedNumber").value
641 );
642
643 // Check if the input is a valid number
644 if (!isNaN(specifiedNumber)) {
645 // Calculate the absolute difference
646 const absoluteDifference = [Link](specifiedNumber - 19);
647
648 // If the specified number is greater than 19, return triple their absolute
difference
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 11/298
1/31/24, 9:21 AM [Link]
649 const result =
650 specifiedNumber > 19 ? absoluteDifference * 3 : absoluteDifference;
651
652 // Display the result
653 const resultElement = [Link]("result8");
654 [Link] = `The computed absolute difference is: ${result}`;
655 } else {
656 alert("Please enter a valid number.");
657 }
658 }
659 </script>
660 <hr />
661
662 <h4>
663 18. Write a JavaScript program to check two given numbers and return true
664 if one of the number is 50 or if their sum is 50.
665 </h4>
666 <form id="numberForm">
667 <label for="number1">Enter Number 1:</label>
668 <input type="number" id="number1" required />
669
670 <label for="number2">Enter Number 2:</label>
671 <input type="number" id="number2" required />
672
673 <button type="button" onclick="checkNumbers()">Check Numbers</button>
674 </form>
675
676 <p id="result9"></p>
677
678 <script>
679 // Your JavaScript code goes here
680 function checkNumbers() {
681 // Get user input for two numbers
682 const number1 = parseFloat([Link]("number1").value);
683 const number2 = parseFloat([Link]("number2").value);
684
685 // Check if the inputs are valid numbers
686 if (!isNaN(number1) && !isNaN(number2)) {
687 // Check if one of the numbers is 50 or if their sum is 50
688 const result =
689 number1 === 50 || number2 === 50 || number1 + number2 === 50;
690
691 // Display the result
692 const resultElement = [Link]("result9");
693 [Link] = `The result is: ${result}`;
694 } else {
695 alert("Please enter valid numbers.");
696 }
697 }
698 </script>
699 <hr />
700
701 <h4>
702 19. Write a JavaScript program to check whether a given integer is within
703 20 of 100 or 400.
704 </h4>
705 <form id="integerForm">
706 <label for="inputNumber">Enter an Integer:</label>
707 <input type="number" id="inputNumber" required />
708
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 12/298
1/31/24, 9:21 AM [Link]
709 <button type="button" onclick="checkInteger()">Check Integer</button>
710 </form>
711
712 <p id="result10"></p>
713
714 <script>
715 // Your JavaScript code goes here
716 function checkInteger() {
717 // Get user input for an integer
718 const inputNumber = parseInt(
719 [Link]("inputNumber").value
720 );
721
722 // Check if the input is a valid integer
723 if (!isNaN(inputNumber)) {
724 // Check if the integer is within 20 of 100 or 400
725 const result =
726 [Link](100 - inputNumber) <= 20 ||
727 [Link](400 - inputNumber) <= 20;
728
729 // Display the result
730 const resultElement = [Link]("result10");
731 [Link] = `The result is: ${result}`;
732 } else {
733 alert("Please enter a valid integer.");
734 }
735 }
736 </script>
737 <hr />
738 <h4>
739 20. Write a JavaScript program to check from two given integers, whether
740 one is positive and another one is negative.
741 </h4>
742 <form id="integerForm">
743 <label for="number1">Enter Integer 1:</label>
744 <input type="number" id="number1" required />
745
746 <label for="number2">Enter Integer 2:</label>
747 <input type="number" id="number2" required />
748
749 <button type="button" onclick="checkIntegers()">Check Integers</button>
750 </form>
751
752 <p id="result11"></p>
753
754 <script>
755 // Your JavaScript code goes here
756 function checkIntegers() {
757 // Get user input for two integers
758 const number1 = parseInt([Link]("number1").value);
759 const number2 = parseInt([Link]("number2").value);
760
761 // Check if the inputs are valid integers
762 if (!isNaN(number1) && !isNaN(number2)) {
763 // Check if one integer is positive and the other is negative
764 const result =
765 (number1 > 0 && number2 < 0) || (number1 < 0 && number2 > 0);
766
767 // Display the result
768 const resultElement = [Link]("result11");
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 13/298
1/31/24, 9:21 AM [Link]
769 [Link] = `The result is: ${result}`;
770 } else {
771 alert("Please enter valid integers.");
772 }
773 }
774 </script>
775 <hr />
776
777 <h4>
778 21. Write a JavaScript program to create a new string adding "Py" in front
779 of a given string. If the given string begins with "Py" then return the
780 original string.
781 </h4>
782 <form id="stringForm">
783 <label for="inputString">Enter a String:</label>
784 <input type="text" id="inputString" required />
785
786 <button type="button" onclick="modifyString()">Modify String</button>
787 </form>
788
789 <p id="result12"></p>
790
791 <script>
792 // Your JavaScript code goes here
793 function modifyString() {
794 // Get user input for a string
795 const inputString = [Link]("inputString").value;
796
797 // Check if the input is not empty
798 if ([Link]() !== "") {
799 // Check if the string begins with "Py"
800 const result = [Link]("Py")
801 ? inputString
802 : "Py" + inputString;
803
804 // Display the result
805 const resultElement = [Link]("result12");
806 [Link] = `The modified string is: ${result}`;
807 } else {
808 alert("Please enter a valid string.");
809 }
810 }
811 </script>
812 <hr />
813
814 <h4>
815 22. Write a JavaScript program to remove a character at the specified
816 position of a given string and return the new string
817 </h4>
818
819 <form id="stringForm">
820 <label for="inputString">Enter a String:</label>
821 <input type="text" id="inputString" required />
822
823 <label for="position">Enter Position to Remove:</label>
824 <input type="number" id="position" required />
825
826 <button type="button" onclick="removeCharacter()">
827 Remove Character
828 </button>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 14/298
1/31/24, 9:21 AM [Link]
829 </form>
830
831 <p id="result13"></p>
832
833 <script>
834 // Your JavaScript code goes here
835 function removeCharacter() {
836 // Get user input for a string and position
837 const inputString = [Link]("inputString").value;
838 const position = parseInt([Link]("position").value);
839
840 // Check if the inputs are valid
841 if ([Link]() !== "" && !isNaN(position)) {
842 // Check if the position is within the string length
843 if (position >= 0 && position < [Link]) {
844 // Remove the character at the specified position
845 const result =
846 [Link](0, position) + [Link](position + 1);
847
848 // Display the result
849 const resultElement = [Link]("result13");
850 [Link] = `The modified string is: ${result}`;
851 } else {
852 alert("Please enter a valid position within the string length.");
853 }
854 } else {
855 alert("Please enter valid string and position.");
856 }
857 }
858 </script>
859 <hr />
860
861 <h4>
862 23. Write a JavaScript program to create a new string from a given string
863 changing the position of first and last characters. The string length must
864 be greater than or equal to 1.
865 </h4>
866 <form id="stringForm">
867 <label for="inputString">Enter a String:</label>
868 <input type="text" id="inputString" required />
869
870 <button type="button" onclick="changeFirstAndLast()">
871 Change First and Last
872 </button>
873 </form>
874
875 <p id="result14"></p>
876
877 <script>
878 // Your JavaScript code goes here
879 function changeFirstAndLast() {
880 // Get user input for a string
881 const inputString = [Link]("inputString").value;
882
883 // Check if the input is not empty
884 if ([Link]() !== "") {
885 // Check if the string length is greater than or equal to 1
886 if ([Link] >= 1) {
887 // Change the position of the first and last characters
888 const result =
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 15/298
1/31/24, 9:21 AM [Link]
889 [Link]([Link] - 1) +
890 [Link](1, -1) +
891 [Link](0);
892
893 // Display the result
894 const resultElement = [Link]("result14");
895 [Link] = `The modified string is: ${result}`;
896 } else {
897 alert(
898 "Please enter a string with length greater than or equal to 1."
899 );
900 }
901 } else {
902 alert("Please enter a valid string.");
903 }
904 }
905 </script>
906 <hr />
907
908 <h4>
909 24. Write a JavaScript program to create a new string from a given string
910 with the first character of the given string added at the front and back.
911 </h4>
912 <form id="stringForm">
913 <label for="inputString">Enter a String:</label>
914 <input type="text" id="inputString" required />
915
916 <button type="button" onclick="addFirstCharacter()">
917 Add First Character
918 </button>
919 </form>
920
921 <p id="result15"></p>
922
923 <script>
924 // Your JavaScript code goes here
925 function addFirstCharacter() {
926 // Get user input for a string
927 const inputString = [Link]("inputString").value;
928
929 // Check if the input is not empty
930 if ([Link]() !== "") {
931 // Get the first character of the given string
932 const firstCharacter = [Link](0);
933
934 // Create a new string with the first character added at the front and back
935 const result = firstCharacter + inputString + firstCharacter;
936
937 // Display the result
938 const resultElement = [Link]("result15");
939 [Link] = `The modified string is: ${result}`;
940 } else {
941 alert("Please enter a valid string.");
942 }
943 }
944 </script>
945 <hr />
946
947 <h4>
948 25. Write a JavaScript program to check whether a given positive number is
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 16/298
1/31/24, 9:21 AM [Link]
949 a multiple of 3 or a multiple of 7.
950 </h4>
951 <form id="numberForm">
952 <label for="inputNumber">Enter a Positive Number:</label>
953 <input type="number" id="inputNumber" required />
954
955 <button type="button" onclick="checkNumber()">Check Number</button>
956 </form>
957
958 <p id="result16"></p>
959
960 <script>
961 // Your JavaScript code goes here
962 function checkNumber() {
963 // Get user input for a positive number
964 const inputNumber = parseFloat(
965 [Link]("inputNumber").value
966 );
967
968 // Check if the input is a valid positive number
969 if (!isNaN(inputNumber) && inputNumber > 0) {
970 // Check if the number is a multiple of 3 or a multiple of 7
971 const result = inputNumber % 3 === 0 || inputNumber % 7 === 0;
972
973 // Display the result
974 const resultElement = [Link]("result16");
975 [Link] = `The result is: ${result}`;
976 } else {
977 alert("Please enter a valid positive number.");
978 }
979 }
980 </script>
981 <hr />
982
983 <h4>
984 26. Write a JavaScript program to create a new string from a given string
985 taking the last 3 characters and added at both the front and back. The
986 string length must be 3 or more.
987 </h4>
988 <form id="stringForm">
989 <label for="inputString">Enter a String (3 or more characters):</label>
990 <input type="text" id="inputString" required />
991
992 <button type="button" onclick="modifyString()">Modify String</button>
993 </form>
994
995 <p id="result17"></p>
996
997 <script>
998 // Your JavaScript code goes here
999 function modifyString() {
1000 // Get user input for a string
1001 const inputString = [Link]("inputString").value;
1002
1003 // Check if the string length is 3 or more
1004 if ([Link] >= 3) {
1005 // Take the last 3 characters and add them at both the front and back
1006 const lastThreeCharacters = [Link](-3);
1007 const result =
1008 lastThreeCharacters + inputString + lastThreeCharacters;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 17/298
1/31/24, 9:21 AM [Link]
1009
1010 // Display the result
1011 const resultElement = [Link]("result17");
1012 [Link] = `The modified string is: ${result}`;
1013 } else {
1014 alert("Please enter a string with length 3 or more.");
1015 }
1016 }
1017 </script>
1018 <hr />
1019
1020 <h4>
1021 27. Write a JavaScript program to check whether a string starts with
1022 'Java' and false otherwise.
1023 </h4>
1024
1025 <form id="stringForm">
1026 <label for="inputString">Enter a String:</label>
1027 <input type="text" id="inputString" required />
1028
1029 <button type="button" onclick="checkString()">Check String</button>
1030 </form>
1031
1032 <p id="result18"></p>
1033
1034 <script>
1035 // Your JavaScript code goes here
1036 function checkString() {
1037 // Get user input for a string
1038 const inputString = [Link]("inputString").value;
1039
1040 // Check if the string starts with 'Java'
1041 const result = [Link]("Java");
1042
1043 // Display the result
1044 const resultElement = [Link]("result18");
1045 [Link] = `The result is: ${result}`;
1046 }
1047 </script>
1048 <hr />
1049
1050 <h4>
1051 28. Write a JavaScript program to check whether two given integer values
1052 are in the range 50..99 (inclusive). Return true if either of them are in
1053 the said range.
1054 </h4>
1055 <form id="numberForm">
1056 <label for="number1">Enter Integer 1:</label>
1057 <input type="number" id="number1" required />
1058
1059 <label for="number2">Enter Integer 2:</label>
1060 <input type="number" id="number2" required />
1061
1062 <button type="button" onclick="checkRange()">Check Range</button>
1063 </form>
1064
1065 <p id="result19"></p>
1066
1067 <script>
1068 // Your JavaScript code goes here
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 18/298
1/31/24, 9:21 AM [Link]
1069 function checkRange() {
1070 // Get user input for two integers
1071 const number1 = parseInt([Link]("number1").value);
1072 const number2 = parseInt([Link]("number2").value);
1073
1074 // Check if the inputs are valid integers
1075 if (!isNaN(number1) && !isNaN(number2)) {
1076 // Check if either of the numbers is in the range 50..99 (inclusive)
1077 const result =
1078 (number1 >= 50 && number1 <= 99) ||
1079 (number2 >= 50 && number2 <= 99);
1080
1081 // Display the result
1082 const resultElement = [Link]("result19");
1083 [Link] = `The result is: ${result}`;
1084 } else {
1085 alert("Please enter valid integers.");
1086 }
1087 }
1088 </script>
1089 <hr />
1090
1091 <h4>
1092 29. Write a JavaScript program to check whether three given integer values
1093 are in the range 50..99 (inclusive). Return true if one or more of them
1094 are in the said range.
1095 </h4>
1096 <form id="numberForm">
1097 <label for="number1">Enter Integer 1:</label>
1098 <input type="number" id="number1" required />
1099
1100 <label for="number2">Enter Integer 2:</label>
1101 <input type="number" id="number2" required />
1102
1103 <label for="number3">Enter Integer 3:</label>
1104 <input type="number" id="number3" required />
1105
1106 <button type="button" onclick="checkRange()">Check Range</button>
1107 </form>
1108
1109 <p id="result20"></p>
1110
1111 <script>
1112 // Your JavaScript code goes here
1113 function checkRange() {
1114 // Get user input for three integers
1115 const number1 = parseInt([Link]("number1").value);
1116 const number2 = parseInt([Link]("number2").value);
1117 const number3 = parseInt([Link]("number3").value);
1118
1119 // Check if the inputs are valid integers
1120 if (!isNaN(number1) && !isNaN(number2) && !isNaN(number3)) {
1121 // Check if one or more of the numbers is in the range 50..99 (inclusive)
1122 const result =
1123 (number1 >= 50 && number1 <= 99) ||
1124 (number2 >= 50 && number2 <= 99) ||
1125 (number3 >= 50 && number3 <= 99);
1126
1127 // Display the result
1128 const resultElement = [Link]("result20");
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 19/298
1/31/24, 9:21 AM [Link]
1129 [Link] = `The result is: ${result}`;
1130 } else {
1131 alert("Please enter valid integers.");
1132 }
1133 }
1134 </script>
1135 <hr />
1136
1137 <h4>
1138 30. Write a JavaScript program to check whether a string "Script" presents
1139 at 5th (index 4) position in a given string, if "Script" presents in the
1140 string return the string without "Script" otherwise return the original
1141 one.
1142 </h4>
1143 <form id="stringForm">
1144 <label for="inputString">Enter a String:</label>
1145 <input type="text" id="inputString" required />
1146
1147 <button type="button" onclick="checkString()">Check String</button>
1148 </form>
1149
1150 <p id="result21"></p>
1151
1152 <script>
1153 // Your JavaScript code goes here
1154 function checkString() {
1155 // Get user input for a string
1156 const inputString = [Link]("inputString").value;
1157
1158 // Check if "Script" is present at the 5th position
1159 const result =
1160 [Link] >= 5 && [Link](4, 10) === "Script"
1161 ? [Link](0, 4) + [Link](10)
1162 : inputString;
1163
1164 // Display the result
1165 const resultElement = [Link]("result21");
1166 [Link] = `The result is: ${result}`;
1167 }
1168 </script>
1169 <hr />
1170
1171 <h4>
1172 31. Write a JavaScript program to find the largest of three given
1173 integers.
1174 </h4>
1175 <form id="integerForm">
1176 <label for="number1">Enter Integer 1:</label>
1177 <input type="number" id="number1" required />
1178
1179 <label for="number2">Enter Integer 2:</label>
1180 <input type="number" id="number2" required />
1181
1182 <label for="number3">Enter Integer 3:</label>
1183 <input type="number" id="number3" required />
1184
1185 <button type="button" onclick="findLargest()">Find Largest</button>
1186 </form>
1187
1188 <p id="result22"></p>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 20/298
1/31/24, 9:21 AM [Link]
1189
1190 <script>
1191 // Your JavaScript code goes here
1192 function findLargest() {
1193 // Get user input for three integers
1194 const number1 = parseInt([Link]("number1").value);
1195 const number2 = parseInt([Link]("number2").value);
1196 const number3 = parseInt([Link]("number3").value);
1197
1198 // Check if the inputs are valid integers
1199 if (!isNaN(number1) && !isNaN(number2) && !isNaN(number3)) {
1200 // Find the largest of the three integers
1201 const largest = [Link](number1, number2, number3);
1202
1203 // Display the result
1204 const resultElement = [Link]("result22");
1205 [Link] = `The largest integer is: ${largest}`;
1206 } else {
1207 alert("Please enter valid integers.");
1208 }
1209 }
1210 </script>
1211 <hr />
1212
1213 <h4>
1214 32. Write a JavaScript program to find a value which is nearest to 100
1215 from two different given integer values.
1216 </h4>
1217 <form id="integerForm">
1218 <label for="number1">Enter Integer 1:</label>
1219 <input type="number" id="number1" required />
1220
1221 <label for="number2">Enter Integer 2:</label>
1222 <input type="number" id="number2" required />
1223
1224 <button type="button" onclick="findNearest()">Find Nearest to 100</button>
1225 </form>
1226
1227 <p id="result23"></p>
1228
1229 <script>
1230 // Your JavaScript code goes here
1231 function findNearest() {
1232 // Get user input for two integers
1233 const number1 = parseInt([Link]("number1").value);
1234 const number2 = parseInt([Link]("number2").value);
1235
1236 // Check if the inputs are valid integers
1237 if (!isNaN(number1) && !isNaN(number2)) {
1238 // Find the value nearest to 100
1239 const nearestValue = findNearestTo100(number1, number2);
1240
1241 // Display the result
1242 const resultElement = [Link]("result23");
1243 [Link] = `The value nearest to 100 is: ${nearestValue}`;
1244 } else {
1245 alert("Please enter valid integers.");
1246 }
1247 }
1248
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 21/298
1/31/24, 9:21 AM [Link]
1249 function findNearestTo100(num1, num2) {
1250 // Calculate the absolute differences from 100
1251 const diff1 = [Link](num1 - 100);
1252 const diff2 = [Link](num2 - 100);
1253
1254 // Determine which value is nearest to 100
1255 if (diff1 < diff2) {
1256 return num1;
1257 } else if (diff2 < diff1) {
1258 return num2;
1259 } else {
1260 // If both differences are equal, return either value
1261 return num1;
1262 }
1263 }
1264 </script>
1265 <hr />
1266
1267 <h4>
1268 33. Write a JavaScript program to check whether two numbers are in range
1269 40..60 or in the range 70..100 inclusive.
1270 </h4>
1271 <form id="numberForm">
1272 <label for="number1">Enter Number 1:</label>
1273 <input type="number" id="number1" required />
1274
1275 <label for="number2">Enter Number 2:</label>
1276 <input type="number" id="number2" required />
1277
1278 <button type="button" onclick="checkRange()">Check Range</button>
1279 </form>
1280
1281 <p id="result24"></p>
1282
1283 <script>
1284 // Your JavaScript code goes here
1285 function checkRange() {
1286 // Get user input for two numbers
1287 const number1 = parseFloat([Link]("number1").value);
1288 const number2 = parseFloat([Link]("number2").value);
1289
1290 // Check if the inputs are valid numbers
1291 if (!isNaN(number1) && !isNaN(number2)) {
1292 // Check if either of the numbers is in the range 40..60 or in the range
70..100 inclusive
1293 const result =
1294 (number1 >= 40 && number1 <= 60) ||
1295 (number1 >= 70 && number1 <= 100) ||
1296 (number2 >= 40 && number2 <= 60) ||
1297 (number2 >= 70 && number2 <= 100);
1298
1299 // Display the result
1300 const resultElement = [Link]("result24");
1301 [Link] = `The result is: ${result}`;
1302 } else {
1303 alert("Please enter valid numbers.");
1304 }
1305 }
1306 </script>
1307 <hr />
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 22/298
1/31/24, 9:21 AM [Link]
1308
1309 <h4>
1310 34. Write a JavaScript program to find the larger number from the two
1311 given positive integers, the two numbers are in the range 40..60
1312 inclusive.
1313 </h4>
1314
1315 <form id="numberForm">
1316 <label for="number1">Enter Positive Integer 1 (40-60):</label>
1317 <input type="number" id="number1" required />
1318
1319 <label for="number2">Enter Positive Integer 2 (40-60):</label>
1320 <input type="number" id="number2" required />
1321
1322 <button type="button" onclick="findLargerNumber()">
1323 Find Larger Number
1324 </button>
1325 </form>
1326
1327 <p id="result25"></p>
1328
1329 <script>
1330 // Your JavaScript code goes here
1331 function findLargerNumber() {
1332 // Get user input for two positive integers
1333 const number1 = parseInt([Link]("number1").value);
1334 const number2 = parseInt([Link]("number2").value);
1335
1336 // Check if the inputs are valid positive integers in the range 40..60 inclusive
1337 if (isValidInput(number1) && isValidInput(number2)) {
1338 // Find the larger of the two numbers
1339 const largerNumber = [Link](number1, number2);
1340
1341 // Display the result
1342 const resultElement = [Link]("result25");
1343 [Link] = `The larger number is: ${largerNumber}`;
1344 } else {
1345 alert("Please enter valid positive integers in the range 40-60.");
1346 }
1347 }
1348
1349 function isValidInput(num) {
1350 return !isNaN(num) && num >= 40 && num <= 60 && [Link](num);
1351 }
1352 </script>
1353 <hr />
1354
1355 <h4>
1356 35. Write a program to check whether a specified character exists within
1357 the 2nd to 4th position in a given string.
1358 </h4>
1359 <form id="stringForm">
1360 <label for="inputString">Enter a String:</label>
1361 <input type="text" id="inputString" required />
1362
1363 <label for="charToCheck">Enter a Character to Check:</label>
1364 <input type="text" id="charToCheck" maxlength="1" required />
1365
1366 <button type="button" onclick="checkCharacter()">Check Character</button>
1367 </form>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 23/298
1/31/24, 9:21 AM [Link]
1368
1369 <p id="result26"></p>
1370
1371 <script>
1372 // Your JavaScript code goes here
1373 function checkCharacter() {
1374 // Get user input for a string and a character
1375 const inputString = [Link]("inputString").value;
1376 const charToCheck = [Link]("charToCheck").value;
1377
1378 // Check if the string has at least 4 characters and the character is a single
character
1379 if ([Link] >= 4 && [Link] === 1) {
1380 // Check if the specified character exists within the 2nd to 4th position
1381 const charExists = [Link](1, 4).includes(charToCheck);
1382
1383 // Display the result
1384 const resultElement = [Link]("result26");
1385 [Link] = `The character ${charToCheck} ${
1386 charExists ? "exists" : "does not exist"
1387 } within the 2nd to 4th position.`;
1388 } else {
1389 alert(
1390 "Please enter a string with at least 4 characters and a single character to
check."
1391 );
1392 }
1393 }
1394 </script>
1395 <hr />
1396
1397 <h4>
1398 36. Write a JavaScript program to check whether the last digit of the
1399 three given positive integers is same.
1400 </h4>
1401 <form id="integerForm">
1402 <label for="number1">Enter Positive Integer 1:</label>
1403 <input type="number" id="number1" required />
1404
1405 <label for="number2">Enter Positive Integer 2:</label>
1406 <input type="number" id="number2" required />
1407
1408 <label for="number3">Enter Positive Integer 3:</label>
1409 <input type="number" id="number3" required />
1410
1411 <button type="button" onclick="checkLastDigit()">Check Last Digit</button>
1412 </form>
1413
1414 <p id="result27"></p>
1415
1416 <script>
1417 // Your JavaScript code goes here
1418 function checkLastDigit() {
1419 // Get user input for three positive integers
1420 const number1 = parseInt([Link]("number1").value);
1421 const number2 = parseInt([Link]("number2").value);
1422 const number3 = parseInt([Link]("number3").value);
1423
1424 // Check if the inputs are valid positive integers
1425 if (
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 24/298
1/31/24, 9:21 AM [Link]
1426 isValidInput(number1) &&
1427 isValidInput(number2) &&
1428 isValidInput(number3)
1429 ) {
1430 // Check if the last digit of the three integers is the same
1431 const lastDigit1 = number1 % 10;
1432 const lastDigit2 = number2 % 10;
1433 const lastDigit3 = number3 % 10;
1434
1435 const lastDigitsAreEqual =
1436 lastDigit1 === lastDigit2 && lastDigit2 === lastDigit3;
1437
1438 // Display the result
1439 const resultElement = [Link]("result27");
1440 [Link] = `The last digits are ${
1441 lastDigitsAreEqual ? "equal" : "not equal"
1442 }.`;
1443 } else {
1444 alert("Please enter valid positive integers.");
1445 }
1446 }
1447
1448 function isValidInput(num) {
1449 return !isNaN(num) && num > 0 && [Link](num);
1450 }
1451 </script>
1452 <hr />
1453
1454 <h4>
1455 37. Write a JavaScript program to create new string with first 3
1456 characters are in lower case from a given string. If the string length is
1457 less than 3 convert all the characters in upper case
1458 </h4>
1459 <form id="stringForm">
1460 <label for="inputString">Enter a String:</label>
1461 <input type="text" id="inputString" required />
1462
1463 <button type="button" onclick="manipulateString()">
1464 Manipulate String
1465 </button>
1466 </form>
1467
1468 <p id="result28"></p>
1469
1470 <script>
1471 // Your JavaScript code goes here
1472 function manipulateString() {
1473 // Get user input for a string
1474 const inputString = [Link]("inputString").value;
1475
1476 // Manipulate the string according to the given conditions
1477 const manipulatedString = manipulateStringFunction(inputString);
1478
1479 // Display the result
1480 const resultElement = [Link]("result28");
1481 [Link] = `The manipulated string is: ${manipulatedString}`;
1482 }
1483
1484 function manipulateStringFunction(str) {
1485 // Check if the string length is less than 3
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 25/298
1/31/24, 9:21 AM [Link]
1486 if ([Link] < 3) {
1487 // Convert all characters to uppercase
1488 return [Link]();
1489 } else {
1490 // Convert the first 3 characters to lowercase and keep the rest unchanged
1491 return [Link](0, 3).toLowerCase() + [Link](3);
1492 }
1493 }
1494 </script>
1495 <hr />
1496
1497 <h4>
1498 38. Write a JavaScript program to check the total marks of a student in
1499 various examinations. The student will get A+ grade if the total marks are
1500 in the range 89..100 inclusive, if the examination is "Final-exam." the
1501 student will get A+ grade and total marks must be greater than or equal to
1502 90. Return true if the student get A+ grade or false otherwise.
1503 </h4>
1504 <form id="examForm">
1505 <label for="totalMarks">Enter Total Marks:</label>
1506 <input type="number" id="totalMarks" required />
1507
1508 <label for="examType">Enter Exam Type (e.g., "Final-exam"):</label>
1509 <input type="text" id="examType" required />
1510
1511 <button type="button" onclick="checkGrade()">Check Grade</button>
1512 </form>
1513
1514 <p id="result29"></p>
1515
1516 <script>
1517 // Your JavaScript code goes here
1518 function checkGrade() {
1519 // Get user input for total marks and exam type
1520 const totalMarks = parseInt(
1521 [Link]("totalMarks").value
1522 );
1523 const examType = [Link]("examType").value;
1524
1525 // Check if the inputs are valid
1526 if (!isNaN(totalMarks) && [Link]() !== "") {
1527 // Check if the student gets an A+ grade based on the specified conditions
1528 const isAPlusGrade = checkAPlusGrade(totalMarks, examType);
1529
1530 // Display the result
1531 const resultElement = [Link]("result29");
1532 [Link] = `The student ${
1533 isAPlusGrade ? "gets" : "does not get"
1534 } an A+ grade.`;
1535 } else {
1536 alert("Please enter valid inputs.");
1537 }
1538 }
1539
1540 function checkAPlusGrade(marks, examType) {
1541 // Check if the total marks are in the range 89..100 inclusive
1542 if (
1543 marks >= 89 &&
1544 marks <= 100 &&
1545 examType === "Final-exam" &&
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 26/298
1/31/24, 9:21 AM [Link]
1546 marks >= 90
1547 ) {
1548 return true;
1549 }
1550
1551 return false;
1552 }
1553 </script>
1554 <hr />
1555
1556 <h4>
1557 39. Write a JavaScript program to compute the sum of the two given
1558 integers, If the sum is in the range 50..80 return 65 other wise return 80
1559 </h4>
1560
1561 <form id="sumForm">
1562 <label for="number1">Enter Integer 1:</label>
1563 <input type="number" id="number1" required />
1564
1565 <label for="number2">Enter Integer 2:</label>
1566 <input type="number" id="number2" required />
1567
1568 <button type="button" onclick="calculateSum()">Calculate Sum</button>
1569 </form>
1570
1571 <p id="result30"></p>
1572
1573 <script>
1574 // Your JavaScript code goes here
1575 function calculateSum() {
1576 // Get user input for two integers
1577 const number1 = parseInt([Link]("number1").value);
1578 const number2 = parseInt([Link]("number2").value);
1579
1580 // Check if the inputs are valid integers
1581 if (!isNaN(number1) && !isNaN(number2)) {
1582 // Calculate the sum of the two integers
1583 const sum = number1 + number2;
1584
1585 // Determine the result based on the sum
1586 const result = sum >= 50 && sum <= 80 ? 65 : 80;
1587
1588 // Display the result
1589 const resultElement = [Link]("result30");
1590 [Link] = `The result is: ${result}`;
1591 } else {
1592 alert("Please enter valid integers.");
1593 }
1594 }
1595 </script>
1596 <hr />
1597
1598 <h4>
1599 40. Write a JavaScript program to check from two given integers whether
1600 one of them is 8 or their sum or difference is 8.
1601 </h4>
1602 <form id="numberForm">
1603 <label for="number1">Enter Integer 1:</label>
1604 <input type="number" id="number1" required />
1605
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 27/298
1/31/24, 9:21 AM [Link]
1606 <label for="number2">Enter Integer 2:</label>
1607 <input type="number" id="number2" required />
1608
1609 <button type="button" onclick="checkNumbers()">Check Numbers</button>
1610 </form>
1611
1612 <p id="result31"></p>
1613
1614 <script>
1615 // Your JavaScript code goes here
1616 function checkNumbers() {
1617 // Get user input for two integers
1618 const number1 = parseInt([Link]("number1").value);
1619 const number2 = parseInt([Link]("number2").value);
1620
1621 // Check if the inputs are valid integers
1622 if (!isNaN(number1) && !isNaN(number2)) {
1623 // Check if one of the numbers is 8, or their sum or difference is 8
1624 const isEightCondition = isEight(number1, number2);
1625
1626 // Display the result
1627 const resultElement = [Link]("result31");
1628 [Link] = `One of the numbers is 8, or their sum/difference
is 8: ${isEightCondition}`;
1629 } else {
1630 alert("Please enter valid integers.");
1631 }
1632 }
1633
1634 function isEight(num1, num2) {
1635 return (
1636 num1 === 8 ||
1637 num2 === 8 ||
1638 num1 + num2 === 8 ||
1639 [Link](num1 - num2) === 8
1640 );
1641 }
1642 </script>
1643 <hr />
1644
1645 <h4>
1646 41. Write a JavaScript program to check three given numbers, if the three
1647 numbers are same return 30 otherwise return 20 and if two numbers are same
1648 return 40.
1649 </h4>
1650 <form id="numberForm">
1651 <label for="number1">Enter Number 1:</label>
1652 <input type="number" id="number1" required />
1653
1654 <label for="number2">Enter Number 2:</label>
1655 <input type="number" id="number2" required />
1656
1657 <label for="number3">Enter Number 3:</label>
1658 <input type="number" id="number3" required />
1659
1660 <button type="button" onclick="checkNumbers()">Check Numbers</button>
1661 </form>
1662
1663 <p id="result32"></p>
1664
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 28/298
1/31/24, 9:21 AM [Link]
1665 <script>
1666 // Your JavaScript code goes here
1667 function checkNumbers() {
1668 // Get user input for three numbers
1669 const number1 = parseFloat([Link]("number1").value);
1670 const number2 = parseFloat([Link]("number2").value);
1671 const number3 = parseFloat([Link]("number3").value);
1672
1673 // Check if the inputs are valid numbers
1674 if (!isNaN(number1) && !isNaN(number2) && !isNaN(number3)) {
1675 // Check the conditions and determine the result
1676 const result = checkNumberConditions(number1, number2, number3);
1677
1678 // Display the result
1679 const resultElement = [Link]("result32");
1680 [Link] = `The result is: ${result}`;
1681 } else {
1682 alert("Please enter valid numbers.");
1683 }
1684 }
1685
1686 function checkNumberConditions(num1, num2, num3) {
1687 if (num1 === num2 && num2 === num3) {
1688 return 30;
1689 } else if (num1 === num2 || num1 === num3 || num2 === num3) {
1690 return 40;
1691 } else {
1692 return 20;
1693 }
1694 }
1695 </script>
1696 <hr />
1697
1698 <h4>
1699 42. Write a JavaScript program to check whether three given numbers are
1700 increasing in strict mode or in soft mode. Note: Strict mode -> 10, 15, 31
1701 : Soft mode -> 24, 22, 31 or 22, 22, 31
1702 </h4>
1703 <form id="numberForm">
1704 <label for="number1">Enter Number 1:</label>
1705 <input type="number" id="number1" required />
1706
1707 <label for="number2">Enter Number 2:</label>
1708 <input type="number" id="number2" required />
1709
1710 <label for="number3">Enter Number 3:</label>
1711 <input type="number" id="number3" required />
1712
1713 <button type="button" onclick="checkNumberOrder()">
1714 Check Number Order
1715 </button>
1716 </form>
1717
1718 <p id="result33"></p>
1719
1720 <script>
1721 // Your JavaScript code goes here
1722 function checkNumberOrder() {
1723 // Get user input for three numbers
1724 const number1 = parseFloat([Link]("number1").value);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 29/298
1/31/24, 9:21 AM [Link]
1725 const number2 = parseFloat([Link]("number2").value);
1726 const number3 = parseFloat([Link]("number3").value);
1727
1728 // Check if the inputs are valid numbers
1729 if (!isNaN(number1) && !isNaN(number2) && !isNaN(number3)) {
1730 // Check whether the numbers are increasing in strict mode or soft mode
1731 const orderType = checkNumberOrderType(number1, number2, number3);
1732
1733 // Display the result
1734 const resultElement = [Link]("result33");
1735 [Link] = `The numbers are in ${orderType} order.`;
1736 } else {
1737 alert("Please enter valid numbers.");
1738 }
1739 }
1740
1741 function checkNumberOrderType(num1, num2, num3) {
1742 if (num1 < num2 && num2 < num3) {
1743 return "strict";
1744 } else if (num1 <= num2 && num2 <= num3) {
1745 return "soft";
1746 } else {
1747 return "neither strict nor soft";
1748 }
1749 }
1750 </script>
1751 <hr />
1752
1753 <h4>
1754 43. Write a JavaScript program to check from three given numbers (non
1755 negative integers) that two or all of them have the same rightmost digit.
1756 </h4>
1757 <form id="numberForm">
1758 <label for="number1">Enter Non-negative Integer 1:</label>
1759 <input type="number" id="number1" required />
1760
1761 <label for="number2">Enter Non-negative Integer 2:</label>
1762 <input type="number" id="number2" required />
1763
1764 <label for="number3">Enter Non-negative Integer 3:</label>
1765 <input type="number" id="number3" required />
1766
1767 <button type="button" onclick="checkRightmostDigit()">
1768 Check Rightmost Digit
1769 </button>
1770 </form>
1771
1772 <p id="result34"></p>
1773
1774 <script>
1775 // Your JavaScript code goes here
1776 function checkRightmostDigit() {
1777 // Get user input for three non-negative integers
1778 const number1 = [Link](
1779 parseInt([Link]("number1").value)
1780 );
1781 const number2 = [Link](
1782 parseInt([Link]("number2").value)
1783 );
1784 const number3 = [Link](
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 30/298
1/31/24, 9:21 AM [Link]
1785 parseInt([Link]("number3").value)
1786 );
1787
1788 // Check if the inputs are valid non-negative integers
1789 if (!isNaN(number1) && !isNaN(number2) && !isNaN(number3)) {
1790 // Check whether two or all three numbers have the same rightmost digit
1791 const hasSameRightmostDigit = checkRightmostDigitEquality(
1792 number1,
1793 number2,
1794 number3
1795 );
1796
1797 // Display the result
1798 const resultElement = [Link]("result34");
1799 [Link] = `Two or all three numbers ${
1800 hasSameRightmostDigit ? "have" : "do not have"
1801 } the same rightmost digit.`;
1802 } else {
1803 alert("Please enter valid non-negative integers.");
1804 }
1805 }
1806
1807 function checkRightmostDigitEquality(num1, num2, num3) {
1808 const rightmostDigit1 = num1 % 10;
1809 const rightmostDigit2 = num2 % 10;
1810 const rightmostDigit3 = num3 % 10;
1811
1812 return (
1813 rightmostDigit1 === rightmostDigit2 ||
1814 rightmostDigit1 === rightmostDigit3 ||
1815 rightmostDigit2 === rightmostDigit3
1816 );
1817 }
1818 </script>
1819 <hr />
1820
1821 <h4>
1822 44. Write a JavaScript program to check from three given integers that
1823 whether a number is greater than or equal to 20 and less than one of the
1824 others.
1825 </h4>
1826 <form id="numberForm">
1827 <label for="number1">Enter Integer 1:</label>
1828 <input type="number" id="number1" required />
1829
1830 <label for="number2">Enter Integer 2:</label>
1831 <input type="number" id="number2" required />
1832
1833 <label for="number3">Enter Integer 3:</label>
1834 <input type="number" id="number3" required />
1835
1836 <button type="button" onclick="checkNumberRange()">
1837 Check Number Range
1838 </button>
1839 </form>
1840
1841 <p id="result35"></p>
1842
1843 <script>
1844 // Your JavaScript code goes here
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 31/298
1/31/24, 9:21 AM [Link]
1845 function checkNumberRange() {
1846 // Get user input for three integers
1847 const number1 = parseInt([Link]("number1").value);
1848 const number2 = parseInt([Link]("number2").value);
1849 const number3 = parseInt([Link]("number3").value);
1850
1851 // Check if the inputs are valid integers
1852 if (!isNaN(number1) && !isNaN(number2) && !isNaN(number3)) {
1853 // Check whether a number is greater than or equal to 20 and less than one of
the others
1854 const isInValidRange = checkNumberValidity(number1, number2, number3);
1855
1856 // Display the result
1857 const resultElement = [Link]("result35");
1858 [Link] = `One of the numbers is greater than or equal to 20
and less than one of the others: ${isInValidRange}`;
1859 } else {
1860 alert("Please enter valid integers.");
1861 }
1862 }
1863
1864 function checkNumberValidity(num1, num2, num3) {
1865 return (
1866 (num1 >= 20 && (num1 < num2 || num1 < num3)) ||
1867 (num2 >= 20 && (num2 < num1 || num2 < num3)) ||
1868 (num3 >= 20 && (num3 < num1 || num3 < num2))
1869 );
1870 }
1871 </script>
1872 <hr />
1873
1874 <h4>
1875 45. Write a JavaScript program to check two given integer values and
1876 return true if one of the number is 15 or if their sum or difference is
1877 15.
1878 </h4>
1879 <form id="numberForm">
1880 <label for="number1">Enter Integer 1:</label>
1881 <input type="number" id="number1" required />
1882
1883 <label for="number2">Enter Integer 2:</label>
1884 <input type="number" id="number2" required />
1885
1886 <button type="button" onclick="checkNumbers()">Check Numbers</button>
1887 </form>
1888
1889 <p id="result36"></p>
1890
1891 <script>
1892 // Your JavaScript code goes here
1893 function checkNumbers() {
1894 // Get user input for two integers
1895 const number1 = parseInt([Link]("number1").value);
1896 const number2 = parseInt([Link]("number2").value);
1897
1898 // Check if the inputs are valid integers
1899 if (!isNaN(number1) && !isNaN(number2)) {
1900 // Check if one of the numbers is 15, or their sum or difference is 15
1901 const isFifteenCondition = checkFifteenCondition(number1, number2);
1902
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 32/298
1/31/24, 9:21 AM [Link]
1903 // Display the result
1904 const resultElement = [Link]("result36");
1905 [Link] = `One of the numbers is 15, or their sum/difference
is 15: ${isFifteenCondition}`;
1906 } else {
1907 alert("Please enter valid integers.");
1908 }
1909 }
1910
1911 function checkFifteenCondition(num1, num2) {
1912 return (
1913 num1 === 15 ||
1914 num2 === 15 ||
1915 num1 + num2 === 15 ||
1916 [Link](num1 - num2) === 15
1917 );
1918 }
1919 </script>
1920 <hr />
1921 <h4>
1922 46. Write a JavaScript program to check two given non-negative integers
1923 that whether one of the number (not both) is multiple of 7 or 11.
1924 </h4>
1925 <form id="numberForm">
1926 <label for="number1">Enter Non-negative Integer 1:</label>
1927 <input type="number" id="number1" required />
1928
1929 <label for="number2">Enter Non-negative Integer 2:</label>
1930 <input type="number" id="number2" required />
1931
1932 <button type="button" onclick="checkNumbers()">Check Numbers</button>
1933 </form>
1934
1935 <p id="result37"></p>
1936
1937 <script>
1938 // Your JavaScript code goes here
1939 function checkNumbers() {
1940 // Get user input for two non-negative integers
1941 const number1 = [Link](
1942 parseInt([Link]("number1").value)
1943 );
1944 const number2 = [Link](
1945 parseInt([Link]("number2").value)
1946 );
1947
1948 // Check if the inputs are valid non-negative integers
1949 if (!isNaN(number1) && !isNaN(number2)) {
1950 // Check whether one of the numbers (not both) is a multiple of 7 or 11
1951 const isMultipleCondition = checkMultipleCondition(number1, number2);
1952
1953 // Display the result
1954 const resultElement = [Link]("result37");
1955 [Link] = `One of the numbers (not both) is a multiple of 7
or 11: ${isMultipleCondition}`;
1956 } else {
1957 alert("Please enter valid non-negative integers.");
1958 }
1959 }
1960
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 33/298
1/31/24, 9:21 AM [Link]
1961 function checkMultipleCondition(num1, num2) {
1962 const isMultipleOf7Or11 =
1963 num1 % 7 === 0 ||
1964 num1 % 11 === 0 ||
1965 num2 % 7 === 0 ||
1966 num2 % 11 === 0;
1967 const isBothMultiples =
1968 (num1 % 7 === 0 || num1 % 11 === 0) &&
1969 (num2 % 7 === 0 || num2 % 11 === 0);
1970
1971 return isMultipleOf7Or11 && !isBothMultiples;
1972 }
1973 </script>
1974 <hr />
1975 <h4>
1976 47. Write a JavaScript program to check whether a given number is presents
1977 in the range 40..10000. For example 40 presents in 40 and 4000
1978 </h4>
1979 <form id="numberForm">
1980 <label for="number">Enter a Number:</label>
1981 <input type="number" id="number" required />
1982
1983 <button type="button" onclick="checkNumberRange()">
1984 Check Number Range
1985 </button>
1986 </form>
1987
1988 <p id="result38"></p>
1989
1990 <script>
1991 // Your JavaScript code goes here
1992 function checkNumberRange() {
1993 // Get user input for a number
1994 const number = parseFloat([Link]("number").value);
1995
1996 // Check if the input is a valid number
1997 if (!isNaN(number)) {
1998 // Check whether the number is in the range 40 to 10000 (inclusive)
1999 const isInRange = checkNumberInRange(number);
2000
2001 // Display the result
2002 const resultElement = [Link]("result38");
2003 [Link] = `The number is ${
2004 isInRange ? "present" : "not present"
2005 } in the range 40 to 10000.`;
2006 } else {
2007 alert("Please enter a valid number.");
2008 }
2009 }
2010
2011 function checkNumberInRange(num) {
2012 return num >= 40 && num <= 10000;
2013 }
2014 </script>
2015 <hr />
2016
2017 <h4>48. Write a JavaScript program to reverse a given string</h4>
2018 <form id="stringForm">
2019 <label for="inputString">Enter a String:</label>
2020 <input type="text" id="inputString" required />
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 34/298
1/31/24, 9:21 AM [Link]
2021
2022 <button type="button" onclick="reverseString()">Reverse String</button>
2023 </form>
2024
2025 <p id="result39"></p>
2026
2027 <script>
2028 // Your JavaScript code goes here
2029 function reverseString() {
2030 // Get user input for a string
2031 const inputString = [Link]("inputString").value;
2032
2033 // Reverse the string
2034 const reversedString = [Link]("").reverse().join("");
2035
2036 // Display the result
2037 const resultElement = [Link]("result39");
2038 [Link] = `Reversed String: ${reversedString}`;
2039 }
2040 </script>
2041 <hr />
2042
2043 <h4>
2044 49. Write a JavaScript program to replace every character in a given
2045 string with the character following it in the alphabet
2046 </h4>
2047 <form id="stringForm">
2048 <label for="inputString">Enter a String:</label>
2049 <input type="text" id="inputString" required />
2050
2051 <button type="button" onclick="replaceWithNextAlphabet()">
2052 Replace with Next Alphabet
2053 </button>
2054 </form>
2055
2056 <p id="result40"></p>
2057
2058 <script>
2059 // Your JavaScript code goes here
2060 function replaceWithNextAlphabet() {
2061 // Get user input for a string
2062 const inputString = [Link]("inputString").value;
2063
2064 // Replace every character with the character following it in the alphabet
2065 const replacedString = [Link](
2066 /[a-zA-Z]/g,
2067 function (char) {
2068 // Determine whether the character is uppercase or lowercase
2069 const isUppercase = char === [Link]();
2070
2071 // Calculate the character code of the next alphabet
2072 const nextCharCode = [Link](0) + 1;
2073
2074 // Wrap around from 'z' to 'a' or 'Z' to 'A'
2075 const newCharCode =
2076 nextCharCode > (isUppercase ? 90 : 122)
2077 ? isUppercase
2078 ? 65
2079 : 97
2080 : nextCharCode;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 35/298
1/31/24, 9:21 AM [Link]
2081
2082 // Convert the character code back to a character
2083 return [Link](newCharCode);
2084 }
2085 );
2086
2087 // Display the result
2088 const resultElement = [Link]("result40");
2089 [Link] = `Result: ${replacedString}`;
2090 }
2091 </script>
2092 <hr />
2093
2094 <h4>
2095 50. Write a JavaScript program to capitalize the first letter of each word
2096 of a given string.
2097 </h4>
2098 <form id="stringForm">
2099 <label for="inputString">Enter a String:</label>
2100 <input type="text" id="inputString" required />
2101
2102 <button type="button" onclick="capitalizeWords()">
2103 Capitalize Words
2104 </button>
2105 </form>
2106
2107 <p id="result41"></p>
2108
2109 <script>
2110 // Your JavaScript code goes here
2111 function capitalizeWords() {
2112 // Get user input for a string
2113 const inputString = [Link]("inputString").value;
2114
2115 // Capitalize the first letter of each word
2116 const capitalizedString = [Link](/\b\w/g, function (char) {
2117 return [Link]();
2118 });
2119
2120 // Display the result
2121 const resultElement = [Link]("result41");
2122 [Link] = `Capitalized String: ${capitalizedString}`;
2123 }
2124 </script>
2125 <hr />
2126
2127 <h4>
2128 51. Write a JavaScript program to convert a given number to hours and
2129 minutes
2130 </h4>
2131 <form id="minutesForm">
2132 <label for="inputMinutes">Enter Minutes:</label>
2133 <input type="number" id="inputMinutes" required />
2134
2135 <button type="button" onclick="convertToHoursAndMinutes()">
2136 Convert
2137 </button>
2138 </form>
2139
2140 <p id="result42"></p>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 36/298
1/31/24, 9:21 AM [Link]
2141
2142 <script>
2143 // Your JavaScript code goes here
2144 function convertToHoursAndMinutes() {
2145 // Get user input for minutes
2146 const inputMinutes = parseInt(
2147 [Link]("inputMinutes").value
2148 );
2149
2150 // Check if the input is a valid number
2151 if (!isNaN(inputMinutes) && inputMinutes >= 0) {
2152 // Convert minutes to hours and minutes
2153 const hours = [Link](inputMinutes / 60);
2154 const remainingMinutes = inputMinutes % 60;
2155
2156 // Display the result
2157 const resultElement = [Link]("result42");
2158 [Link] = `Converted Time: ${hours} hours and
${remainingMinutes} minutes`;
2159 } else {
2160 alert("Please enter a valid non-negative number.");
2161 }
2162 }
2163 </script>
2164 <hr />
2165
2166 <h4>
2167 52. Write a JavaScript program to convert the letters of a given string in
2168 alphabetical order.
2169 </h4>
2170 <form id="stringForm">
2171 <label for="inputString">Enter a String:</label>
2172 <input type="text" id="inputString" required />
2173
2174 <button type="button" onclick="sortAlphabetically()">
2175 Sort Alphabetically
2176 </button>
2177 </form>
2178
2179 <p id="result43"></p>
2180
2181 <script>
2182 // Your JavaScript code goes here
2183 function sortAlphabetically() {
2184 // Get user input for a string
2185 const inputString = [Link]("inputString").value;
2186
2187 // Convert the letters of the string to alphabetical order
2188 const sortedString = [Link]("").sort().join("");
2189
2190 // Display the result
2191 const resultElement = [Link]("result43");
2192 [Link] = `Sorted Alphabetically: ${sortedString}`;
2193 }
2194 </script>
2195 <hr />
2196
2197 <h4>
2198 53. Write a JavaScript program to check whether the characters a and b are
2199 separated by exactly 3 places anywhere (at least once) in a given string.
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 37/298
1/31/24, 9:21 AM [Link]
2200 </h4>
2201 <form id="stringForm">
2202 <label for="inputString">Enter a String:</label>
2203 <input type="text" id="inputString" required />
2204
2205 <button type="button" onclick="checkCharacterSeparation()">
2206 Check Character Separation
2207 </button>
2208 </form>
2209
2210 <p id="result44"></p>
2211
2212 <script>
2213 // Your JavaScript code goes here
2214 function checkCharacterSeparation() {
2215 // Get user input for a string
2216 const inputString = [Link]("inputString").value;
2217
2218 // Check if 'a' and 'b' are separated by exactly 3 places anywhere in the string
2219 const isSeparated = /a.{3}b|b.{3}a/.test(inputString);
2220
2221 // Display the result
2222 const resultElement = [Link]("result44");
2223 [Link] = `Characters 'a' and 'b' are ${
2224 isSeparated ? "" : "not "
2225 }separated by exactly 3 places.`;
2226 }
2227 </script>
2228 <hr />
2229
2230 <h4>
2231 54. Write a JavaScript program to count the number of vowels in a given
2232 string.
2233 </h4>
2234 <form id="stringForm">
2235 <label for="inputString">Enter a String:</label>
2236 <input type="text" id="inputString" required />
2237
2238 <button type="button" onclick="countVowels()">Count Vowels</button>
2239 </form>
2240
2241 <p id="result54"></p>
2242
2243 <script>
2244 // Your JavaScript code goes here
2245 function countVowels() {
2246 // Get user input for a string
2247 const inputString = [Link]("inputString").value;
2248
2249 // Count the number of vowels in the string
2250 const vowelCount = ([Link](/[aeiouAEIOU]/g) || []).length;
2251
2252 // Display the result
2253 const resultElement = [Link]("result54");
2254 [Link] = `Number of vowels: ${vowelCount}`;
2255 }
2256 </script>
2257 <hr />
2258
2259 <h4>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 38/298
1/31/24, 9:21 AM [Link]
2260 55. Write a JavaScript program to check whether a given string contains
2261 equal number of p's and t's.
2262 </h4>
2263 <form id="stringForm">
2264 <label for="inputString">Enter a String:</label>
2265 <input type="text" id="inputString" required />
2266
2267 <button type="button" onclick="checkEqualPT()">
2268 Check Equal P's and T's
2269 </button>
2270 </form>
2271
2272 <p id="result55"></p>
2273
2274 <script>
2275 // Your JavaScript code goes here
2276 function checkEqualPT() {
2277 // Get user input for a string
2278 const inputString = [Link]("inputString").value;
2279
2280 // Count the number of 'p's and 't's in the string
2281 const pCount = ([Link](/p/g) || []).length;
2282 const tCount = ([Link](/t/g) || []).length;
2283
2284 // Check if the number of 'p's is equal to the number of 't's
2285 const areEqual = pCount === tCount;
2286
2287 // Display the result
2288 const resultElement = [Link]("result55");
2289 [Link] = `The string ${
2290 areEqual ? "contains" : "does not contain"
2291 } an equal number of 'p's and 't's.`;
2292 }
2293 </script>
2294 <hr />
2295 <h4>
2296 56. Write a JavaScript program to divide two positive numbers and return a
2297 string with properly formatted commas.
2298 </h4>
2299 <form id="divisionForm">
2300 <label for="numerator">Enter Numerator:</label>
2301 <input type="number" id="numerator" required />
2302
2303 <label for="denominator">Enter Denominator:</label>
2304 <input type="number" id="denominator" required />
2305
2306 <button type="button" onclick="performDivision()">Divide</button>
2307 </form>
2308
2309 <p id="result56"></p>
2310
2311 <script>
2312 // Your JavaScript code goes here
2313 function performDivision() {
2314 // Get user input for numerator and denominator
2315 const numerator = parseFloat(
2316 [Link]("numerator").value
2317 );
2318 const denominator = parseFloat(
2319 [Link]("denominator").value
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 39/298
1/31/24, 9:21 AM [Link]
2320 );
2321
2322 // Check if the inputs are valid positive numbers
2323 if (
2324 !isNaN(numerator) &&
2325 !isNaN(denominator) &&
2326 numerator >= 0 &&
2327 denominator > 0
2328 ) {
2329 // Perform the division
2330 const result = numerator / denominator;
2331
2332 // Format the result with commas
2333 const formattedResult = [Link]();
2334
2335 // Display the result
2336 const resultElement = [Link]("result56");
2337 [Link] = `Result: ${formattedResult}`;
2338 } else {
2339 alert("Please enter valid positive numbers.");
2340 }
2341 }
2342 </script>
2343 <hr />
2344
2345 <h4>
2346 57. Write a JavaScript program to create a new string of specified copies
2347 (positive number) of a given string
2348 </h4>
2349 <form id="stringCopiesForm">
2350 <label for="inputString">Enter a String:</label>
2351 <input type="text" id="inputString" required />
2352
2353 <label for="numCopies">Enter the Number of Copies:</label>
2354 <input type="number" id="numCopies" required />
2355
2356 <button type="button" onclick="generateStringCopies()">
2357 Generate String Copies
2358 </button>
2359 </form>
2360
2361 <p id="result57"></p>
2362
2363 <script>
2364 // Your JavaScript code goes here
2365 function generateStringCopies() {
2366 // Get user input for a string and the number of copies
2367 const inputString = [Link]("inputString").value;
2368 const numCopies = parseInt([Link]("numCopies").value);
2369
2370 // Check if the inputs are valid
2371 if (!isNaN(numCopies) && numCopies >= 0) {
2372 // Generate the string copies
2373 const stringCopies = [Link](numCopies);
2374
2375 // Display the result
2376 const resultElement = [Link]("result57");
2377 [Link] = `String Copies: ${stringCopies}`;
2378 } else {
2379 alert(
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 40/298
1/31/24, 9:21 AM [Link]
2380 "Please enter a valid non-negative number for the number of copies."
2381 );
2382 }
2383 }
2384 </script>
2385 <hr />
2386
2387 <h4>
2388 58. Write a JavaScript program to create a new string of 4 copies of the
2389 last 3 characters of a given original string. The length of the given
2390 string must be 3 and above.
2391 </h4>
2392 <form id="stringForm">
2393 <label for="originalString"
2394 >Enter a String (3 characters and above):</label
2395 >
2396 <input type="text" id="originalString" minlength="3" required />
2397
2398 <button type="button" onclick="generateNewString()">
2399 Generate New String
2400 </button>
2401 </form>
2402
2403 <p id="result58"></p>
2404
2405 <script>
2406 // Your JavaScript code goes here
2407 function generateNewString() {
2408 // Get user input for the original string
2409 const originalString = [Link]("originalString").value;
2410
2411 // Check if the input is valid (length must be 3 and above)
2412 if ([Link] >= 3) {
2413 // Get the last 3 characters of the original string
2414 const lastThreeCharacters = [Link](-3);
2415
2416 // Generate the new string with 4 copies of the last 3 characters
2417 const newString = [Link](4);
2418
2419 // Display the result
2420 const resultElement = [Link]("result58");
2421 [Link] = `New String: ${newString}`;
2422 } else {
2423 alert("Please enter a string with length 3 and above.");
2424 }
2425 }
2426 </script>
2427 <hr />
2428
2429 <h4>
2430 59. Write a JavaScript program to extract the first half of a string of
2431 even length.
2432 </h4>
2433 <form id="stringForm">
2434 <label for="inputString">Enter a String of Even Length:</label>
2435 <input type="text" id="inputString" required />
2436
2437 <button type="button" onclick="extractFirstHalf()">
2438 Extract First Half
2439 </button>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 41/298
1/31/24, 9:21 AM [Link]
2440 </form>
2441
2442 <p id="result59"></p>
2443
2444 <script>
2445 // Your JavaScript code goes here
2446 function extractFirstHalf() {
2447 // Get user input for the string
2448 const inputString = [Link]("inputString").value;
2449
2450 // Check if the input string has an even length
2451 if ([Link] % 2 === 0) {
2452 // Extract the first half of the string
2453 const firstHalf = [Link](0, [Link] / 2);
2454
2455 // Display the result
2456 const resultElement = [Link]("result59");
2457 [Link] = `First Half: ${firstHalf}`;
2458 } else {
2459 alert("Please enter a string of even length.");
2460 }
2461 }
2462 </script>
2463 <hr />
2464
2465 <h4>
2466 60. Write a JavaScript program to create a new string without the first
2467 and last character of a given string.
2468 </h4>
2469 <form id="stringForm">
2470 <label for="inputString">Enter a String:</label>
2471 <input type="text" id="inputString" required />
2472
2473 <button type="button" onclick="removeFirstAndLast()">
2474 Remove First and Last
2475 </button>
2476 </form>
2477
2478 <p id="result60"></p>
2479
2480 <script>
2481 // Your JavaScript code goes here
2482 function removeFirstAndLast() {
2483 // Get user input for the string
2484 const inputString = [Link]("inputString").value;
2485
2486 // Check if the input string has at least two characters
2487 if ([Link] >= 2) {
2488 // Remove the first and last characters
2489 const newString = [Link](1, -1);
2490
2491 // Display the result
2492 const resultElement = [Link]("result60");
2493 [Link] = `New String: ${newString}`;
2494 } else {
2495 alert("Please enter a string with at least two characters.");
2496 }
2497 }
2498 </script>
2499 <hr />
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 42/298
1/31/24, 9:21 AM [Link]
2500
2501 <h4>
2502 61. Write a JavaScript program to concatenate two strings except their
2503 first character
2504 </h4>
2505 <form id="stringForm">
2506 <label for="firstString">Enter the First String:</label>
2507 <input type="text" id="firstString" required />
2508
2509 <label for="secondString">Enter the Second String:</label>
2510 <input type="text" id="secondString" required />
2511
2512 <button type="button" onclick="concatenateStrings()">
2513 Concatenate (Except First Character)
2514 </button>
2515 </form>
2516
2517 <p id="result"></p>
2518
2519 <script>
2520 // Your JavaScript code goes here
2521 function concatenateStrings() {
2522 // Get user input for the first and second strings
2523 const firstString = [Link]("firstString").value;
2524 const secondString = [Link]("secondString").value;
2525
2526 // Check if the input strings have at least one character each
2527 if ([Link] > 0 && [Link] > 0) {
2528 // Concatenate the strings (except their first character)
2529 const concatenatedString =
2530 [Link](1) + [Link](1);
2531
2532 // Display the result
2533 const resultElement = [Link]("result");
2534 [Link] = `Concatenated String: ${concatenatedString}`;
2535 } else {
2536 alert("Please enter at least one character for each string.");
2537 }
2538 }
2539 </script>
2540 <hr />
2541
2542 <h4>
2543 62. Write a JavaScript program to move last three character to the start
2544 of a given string. The string length must be greater or equal to three
2545 </h4>
2546 <form id="stringForm">
2547 <label for="inputString"
2548 >Enter a String (length must be greater or equal to three):</label
2549 >
2550 <input type="text" id="inputString" minlength="3" required />
2551
2552 <button type="button" onclick="moveLastThreeToStart()">
2553 Move Last Three to Start
2554 </button>
2555 </form>
2556
2557 <p id="result"></p>
2558
2559 <script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 43/298
1/31/24, 9:21 AM [Link]
2560 // Your JavaScript code goes here
2561 function moveLastThreeToStart() {
2562 // Get user input for the string
2563 const inputString = [Link]("inputString").value;
2564
2565 // Check if the input string has a length greater or equal to three
2566 if ([Link] >= 3) {
2567 // Extract the last three characters
2568 const lastThreeCharacters = [Link](-3);
2569
2570 // Move the last three characters to the start
2571 const newString = lastThreeCharacters + [Link](0, -3);
2572
2573 // Display the result
2574 const resultElement = [Link]("result");
2575 [Link] = `New String: ${newString}`;
2576 } else {
2577 alert(
2578 "Please enter a string with a length greater or equal to three."
2579 );
2580 }
2581 }
2582 </script>
2583 <hr />
2584
2585 <h4>
2586 63. Write a JavaScript program to create a string using the middle three
2587 characters of a given string of odd length. The string length must be
2588 greater or equal to three.
2589 </h4>
2590 <form id="stringForm">
2591 <label for="inputString"
2592 >Enter a String (length must be greater or equal to three and
2593 odd):</label
2594 >
2595 <input type="text" id="inputString" minlength="3" required />
2596
2597 <button type="button" onclick="createMiddleThreeString()">
2598 Create Middle Three String
2599 </button>
2600 </form>
2601
2602 <p id="result"></p>
2603
2604 <script>
2605 // Your JavaScript code goes here
2606 function createMiddleThreeString() {
2607 // Get user input for the string
2608 const inputString = [Link]("inputString").value;
2609
2610 // Check if the input string has a length greater or equal to three and is odd
2611 if ([Link] >= 3 && [Link] % 2 !== 0) {
2612 // Find the middle index
2613 const middleIndex = [Link]([Link] / 2);
2614
2615 // Extract the middle three characters
2616 const middleThreeCharacters = [Link](
2617 middleIndex - 1,
2618 middleIndex + 2
2619 );
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 44/298
1/31/24, 9:21 AM [Link]
2620
2621 // Display the result
2622 const resultElement = [Link]("result");
2623 [Link] = `Middle Three Characters: ${middleThreeCharacters}
`;
2624 } else {
2625 alert(
2626 "Please enter a string with a length greater or equal to three and odd."
2627 );
2628 }
2629 }
2630 </script>
2631 <hr />
2632
2633 <h4>
2634 64. Write a JavaScript program to concatenate two strings and return the
2635 result. If the length of the strings are not same then remove the
2636 characters from the longer string.
2637 </h4>
2638 <form id="stringForm">
2639 <label for="firstString">Enter the First String:</label>
2640 <input type="text" id="firstString" required />
2641
2642 <label for="secondString">Enter the Second String:</label>
2643 <input type="text" id="secondString" required />
2644
2645 <button type="button" onclick="concatenateAndTrim()">
2646 Concatenate and Trim
2647 </button>
2648 </form>
2649
2650 <p id="result"></p>
2651
2652 <script>
2653 // Your JavaScript code goes here
2654 function concatenateAndTrim() {
2655 // Get user input for the first and second strings
2656 const firstString = [Link]("firstString").value;
2657 const secondString = [Link]("secondString").value;
2658
2659 // Concatenate the strings
2660 let resultString = firstString + secondString;
2661
2662 // Trim the longer string if their lengths are not the same
2663 if ([Link] !== [Link]) {
2664 const minLength = [Link]([Link], [Link]);
2665 resultString = [Link](0, minLength);
2666 }
2667
2668 // Display the result
2669 const resultElement = [Link]("result");
2670 [Link] = `Result: ${resultString}`;
2671 }
2672 </script>
2673 <hr />
2674
2675 <h4>
2676 66. Write a JavaScript program to display the city name if the string
2677 begins with "Los" or "New" otherwise return blank.
2678 </h4>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 45/298
1/31/24, 9:21 AM [Link]
2679 <form id="stringForm">
2680 <label for="inputString">Enter a String:</label>
2681 <input type="text" id="inputString" required />
2682
2683 <button type="button" onclick="displayCityName()">
2684 Display City Name
2685 </button>
2686 </form>
2687
2688 <p id="result"></p>
2689
2690 <script>
2691 // Your JavaScript code goes here
2692 function displayCityName() {
2693 // Get user input for the string
2694 const inputString = document
2695 .getElementById("inputString")
2696 .[Link]();
2697
2698 // Check if the string begins with "los" or "new"
2699 if ([Link]("los")) {
2700 displayResult("Los Angeles");
2701 } else if ([Link]("new")) {
2702 displayResult("New York");
2703 } else {
2704 displayResult("");
2705 }
2706 }
2707
2708 function displayResult(cityName) {
2709 // Display the result
2710 const resultElement = [Link]("result");
2711 [Link] = `City Name: ${cityName}`;
2712 }
2713 </script>
2714 <hr />
2715
2716 <h4>
2717 67. Write a JavaScript program to create a new string from a given string,
2718 removing the first and last characters of the string if the first or last
2719 character are 'P'. Return the original string if the condition is not
2720 satisfied.
2721 </h4>
2722 <form id="stringForm">
2723 <label for="inputString">Enter a String:</label>
2724 <input type="text" id="inputString" required />
2725
2726 <button type="button" onclick="createNewString()">
2727 Create New String
2728 </button>
2729 </form>
2730
2731 <p id="result"></p>
2732
2733 <script>
2734 // Your JavaScript code goes here
2735 function createNewString() {
2736 // Get user input for the string
2737 const inputString = [Link]("inputString").value;
2738
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 46/298
1/31/24, 9:21 AM [Link]
2739 // Check if the first and last characters are 'P'
2740 if (
2741 [Link] >= 2 &&
2742 inputString[0].toUpperCase() === "P" &&
2743 [Link](-1).toUpperCase() === "P"
2744 ) {
2745 // Remove the first and last characters
2746 const newString = [Link](1, -1);
2747
2748 // Display the result
2749 displayResult(newString);
2750 } else {
2751 // Display the original string
2752 displayResult(inputString);
2753 }
2754 }
2755
2756 function displayResult(resultString) {
2757 // Display the result
2758 const resultElement = [Link]("result");
2759 [Link] = `Result: ${resultString}`;
2760 }
2761 </script>
2762 <hr />
2763
2764 <h4>
2765 67. Write a JavaScript program to create a new string from a given string,
2766 removing the first and last characters of the string if the first or last
2767 character are 'P'. Return the original string if the condition is not
2768 satisfied.
2769 </h4>
2770 <form id="stringForm">
2771 <label for="inputString">Enter a String:</label>
2772 <input type="text" id="inputString" required />
2773
2774 <button type="button" onclick="createNewString()">
2775 Create New String
2776 </button>
2777 </form>
2778
2779 <p id="result"></p>
2780
2781 <script>
2782 // Your JavaScript code goes here
2783 function createNewString() {
2784 // Get user input for the string
2785 const inputString = [Link]("inputString").value;
2786
2787 // Check if the first and last characters are 'P' (case-insensitive)
2788 if (
2789 [Link] >= 2 &&
2790 (inputString[0].toUpperCase() === "P" ||
2791 [Link](-1).toUpperCase() === "P")
2792 ) {
2793 // Remove the first and last characters
2794 const newString = [Link](1, -1);
2795
2796 // Display the result
2797 displayResult(newString);
2798 } else {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 47/298
1/31/24, 9:21 AM [Link]
2799 // Display the original string
2800 displayResult(inputString);
2801 }
2802 }
2803
2804 function displayResult(resultString) {
2805 // Display the result
2806 const resultElement = [Link]("result");
2807 [Link] = `Result: ${resultString}`;
2808 }
2809 </script>
2810 <hr />
2811
2812 <h4>
2813 68. Write a JavaScript program to create a new string using the first and
2814 last n characters from a given sting. The string length must be greater or
2815 equal to n.
2816 </h4>
2817 <form id="stringForm">
2818 <label for="inputString">Enter a String:</label>
2819 <input type="text" id="inputString" required />
2820
2821 <label for="nValue">Enter a value for n:</label>
2822 <input type="number" id="nValue" required />
2823
2824 <button type="button" onclick="createNewString()">
2825 Create New String
2826 </button>
2827 </form>
2828
2829 <p id="result"></p>
2830
2831 <script>
2832 // Your JavaScript code goes here
2833 function createNewString() {
2834 // Get user input for the string and value of n
2835 const inputString = [Link]("inputString").value;
2836 const nValue = parseInt([Link]("nValue").value);
2837
2838 // Check if the string length is greater or equal to n
2839 if ([Link] >= nValue) {
2840 // Extract the first and last n characters
2841 const firstNCharacters = [Link](0, nValue);
2842 const lastNCharacters = [Link](-nValue);
2843
2844 // Combine the first and last n characters to create the new string
2845 const newString = firstNCharacters + lastNCharacters;
2846
2847 // Display the result
2848 displayResult(newString);
2849 } else {
2850 alert("Please enter a string with a length greater or equal to n.");
2851 }
2852 }
2853
2854 function displayResult(resultString) {
2855 // Display the result
2856 const resultElement = [Link]("result");
2857 [Link] = `Result: ${resultString}`;
2858 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 48/298
1/31/24, 9:21 AM [Link]
2859 </script>
2860 <hr />
2861
2862 <h4>
2863 69. Write a JavaScript program to compute the sum of three elements of a
2864 given array of integers of length 3
2865 </h4>
2866 <form id="arrayForm">
2867 <label for="inputArray">Enter three integers separated by commas:</label>
2868 <input type="text" id="inputArray" required />
2869
2870 <button type="button" onclick="computeSum()">Compute Sum</button>
2871 </form>
2872
2873 <p id="result"></p>
2874
2875 <script>
2876 // Your JavaScript code goes here
2877 function computeSum() {
2878 // Get user input for the array
2879 const inputArray = [Link]("inputArray").value;
2880
2881 // Convert the input string to an array of integers
2882 const integers = [Link](",").map(Number);
2883
2884 // Check if the array has exactly three elements
2885 if ([Link] === 3) {
2886 // Compute the sum of three elements
2887 const sum = integers[0] + integers[1] + integers[2];
2888
2889 // Display the result
2890 displayResult(sum);
2891 } else {
2892 alert("Please enter three integers separated by commas.");
2893 }
2894 }
2895
2896 function displayResult(result) {
2897 // Display the result
2898 const resultElement = [Link]("result");
2899 [Link] = `Sum of Three Elements: ${result}`;
2900 }
2901 </script>
2902 <hr />
2903
2904 <h4>
2905 70. Write a JavaScript program to rotate the elements left of a given
2906 array of integers of length 3.
2907 </h4>
2908 <form id="arrayForm">
2909 <label for="inputArray">Enter three integers separated by commas:</label>
2910 <input type="text" id="inputArray" required />
2911
2912 <button type="button" onclick="rotateLeft()">Rotate Left</button>
2913 </form>
2914
2915 <p id="result"></p>
2916
2917 <script>
2918 // Your JavaScript code goes here
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 49/298
1/31/24, 9:21 AM [Link]
2919 function rotateLeft() {
2920 // Get user input for the array
2921 const inputArray = [Link]("inputArray").value;
2922
2923 // Convert the input string to an array of integers
2924 const integers = [Link](",").map(Number);
2925
2926 // Check if the array has exactly three elements
2927 if ([Link] === 3) {
2928 // Rotate the elements left
2929 const rotatedArray = [integers[1], integers[2], integers[0]];
2930
2931 // Display the result
2932 displayResult(rotatedArray);
2933 } else {
2934 alert("Please enter three integers separated by commas.");
2935 }
2936 }
2937
2938 function displayResult(resultArray) {
2939 // Display the result
2940 const resultElement = [Link]("result");
2941 [Link] = `Rotated Array: ${[Link](", ")}`;
2942 }
2943 </script>
2944 <hr />
2945
2946 <h4>
2947 71. Write a JavaScript program to check whether 1 appears in first or last
2948 position of a given array of integers. The array length must be greater or
2949 equal to 1.
2950 </h4>
2951 <form id="arrayForm">
2952 <label for="inputArray">Enter integers separated by commas:</label>
2953 <input type="text" id="inputArray" required />
2954
2955 <button type="button" onclick="checkForOne()">Check for 1</button>
2956 </form>
2957
2958 <p id="result"></p>
2959
2960 <script>
2961 // Your JavaScript code goes here
2962 function checkForOne() {
2963 // Get user input for the array
2964 const inputArray = [Link]("inputArray").value;
2965
2966 // Convert the input string to an array of integers
2967 const integers = [Link](",").map(Number);
2968
2969 // Check if the array has at least one element
2970 if ([Link] >= 1) {
2971 // Check if 1 appears in the first or last position
2972 const hasOne =
2973 integers[0] === 1 || integers[[Link] - 1] === 1;
2974
2975 // Display the result
2976 displayResult(hasOne);
2977 } else {
2978 alert("Please enter at least one integer.");
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 50/298
1/31/24, 9:21 AM [Link]
2979 }
2980 }
2981
2982 function displayResult(hasOne) {
2983 // Display the result
2984 const resultElement = [Link]("result");
2985 [Link] = `Does 1 appear in the first or last position? ${
2986 hasOne ? "Yes" : "No"
2987 }`;
2988 }
2989 </script>
2990 <hr />
2991
2992 <h4>
2993 72. Write a JavaScript program to check whether the first and last
2994 elements are equal of a given array of integers length 3.
2995 </h4>
2996 <form id="arrayForm">
2997 <label for="inputArray">Enter three integers separated by commas:</label>
2998 <input type="text" id="inputArray" required />
2999
3000 <button type="button" onclick="checkEquality()">Check Equality</button>
3001 </form>
3002
3003 <p id="result"></p>
3004
3005 <script>
3006 // Your JavaScript code goes here
3007 function checkEquality() {
3008 // Get user input for the array
3009 const inputArray = [Link]("inputArray").value;
3010
3011 // Convert the input string to an array of integers
3012 const integers = [Link](",").map(Number);
3013
3014 // Check if the array has exactly three elements
3015 if ([Link] === 3) {
3016 // Check if the first and last elements are equal
3017 const areEqual = integers[0] === integers[2];
3018
3019 // Display the result
3020 displayResult(areEqual);
3021 } else {
3022 alert("Please enter three integers separated by commas.");
3023 }
3024 }
3025
3026 function displayResult(areEqual) {
3027 // Display the result
3028 const resultElement = [Link]("result");
3029 [Link] = `Are the first and last elements equal? ${
3030 areEqual ? "Yes" : "No"
3031 }`;
3032 }
3033 </script>
3034 <hr />
3035
3036 <h4>
3037 73. Write a JavaScript program to reverse the elements of a given array of
3038 integers length 3
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 51/298
1/31/24, 9:21 AM [Link]
3039 </h4>
3040 <form id="arrayForm">
3041 <label for="inputArray">Enter three integers separated by commas:</label>
3042 <input type="text" id="inputArray" required />
3043
3044 <button type="button" onclick="reverseArray()">Reverse Array</button>
3045 </form>
3046
3047 <p id="result"></p>
3048
3049 <script>
3050 // Your JavaScript code goes here
3051 function reverseArray() {
3052 // Get user input for the array
3053 const inputArray = [Link]("inputArray").value;
3054
3055 // Convert the input string to an array of integers
3056 const integers = [Link](",").map(Number);
3057
3058 // Check if the array has exactly three elements
3059 if ([Link] === 3) {
3060 // Reverse the elements of the array
3061 const reversedArray = [Link]().reverse();
3062
3063 // Display the result
3064 displayResult(reversedArray);
3065 } else {
3066 alert("Please enter three integers separated by commas.");
3067 }
3068 }
3069
3070 function displayResult(resultArray) {
3071 // Display the result
3072 const resultElement = [Link]("result");
3073 [Link] = `Reversed Array: ${[Link](", ")}`;
3074 }
3075 </script>
3076 <hr />
3077
3078 <h4>
3079 74. Write a JavaScript program to find the larger value between the first
3080 or last and set all the other elements with that value. Display the new
3081 array
3082 </h4>
3083 <form id="arrayForm">
3084 <label for="inputArray">Enter integers separated by commas:</label>
3085 <input type="text" id="inputArray" required />
3086
3087 <button type="button" onclick="setLargerValue()">Set Larger Value</button>
3088 </form>
3089
3090 <p id="result"></p>
3091
3092 <script>
3093 // Your JavaScript code goes here
3094 function setLargerValue() {
3095 // Get user input for the array
3096 const inputArray = [Link]("inputArray").value;
3097
3098 // Convert the input string to an array of integers
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 52/298
1/31/24, 9:21 AM [Link]
3099 const integers = [Link](",").map(Number);
3100
3101 // Check if the array has at least one element
3102 if ([Link] >= 1) {
3103 // Find the larger value between the first and last elements
3104 const largerValue = [Link](
3105 integers[0],
3106 integers[[Link] - 1]
3107 );
3108
3109 // Set all other elements with the larger value
3110 const newArray = [Link](() => largerValue);
3111
3112 // Display the result
3113 displayResult(newArray);
3114 } else {
3115 alert("Please enter at least one integer.");
3116 }
3117 }
3118
3119 function displayResult(resultArray) {
3120 // Display the result
3121 const resultElement = [Link]("result");
3122 [Link] = `New Array: ${[Link](", ")}`;
3123 }
3124 </script>
3125 <hr />
3126
3127 <h4>
3128 75. Write a JavaScript program to create a new array taking the middle
3129 elements of the two arrays of integer and each length 3.
3130 </h4>
3131 <form id="arrayForm">
3132 <label for="inputArray1"
3133 >Enter three integers for array 1 separated by commas:</label
3134 >
3135 <input type="text" id="inputArray1" required /><br />
3136
3137 <label for="inputArray2"
3138 >Enter three integers for array 2 separated by commas:</label
3139 >
3140 <input type="text" id="inputArray2" required /><br />
3141
3142 <button type="button" onclick="createMiddleArray()">
3143 Create Middle Array
3144 </button>
3145 </form>
3146
3147 <p id="result"></p>
3148
3149 <script>
3150 // Your JavaScript code goes here
3151 function createMiddleArray() {
3152 // Get user input for the first array
3153 const inputArray1 = [Link]("inputArray1").value;
3154
3155 // Get user input for the second array
3156 const inputArray2 = [Link]("inputArray2").value;
3157
3158 // Convert the input strings to arrays of integers
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 53/298
1/31/24, 9:21 AM [Link]
3159 const array1 = [Link](",").map(Number);
3160 const array2 = [Link](",").map(Number);
3161
3162 // Check if both arrays have exactly three elements
3163 if ([Link] === 3 && [Link] === 3) {
3164 // Create a new array with the middle elements
3165 const middleArray = [array1[1], array2[1]];
3166
3167 // Display the result
3168 displayResult(middleArray);
3169 } else {
3170 alert(
3171 "Please enter three integers for each array separated by commas."
3172 );
3173 }
3174 }
3175
3176 function displayResult(resultArray) {
3177 // Display the result
3178 const resultElement = [Link]("result");
3179 [Link] = `Middle Elements Array: [${[Link](
3180 ", "
3181 )}]`;
3182 }
3183 </script>
3184 <hr />
3185
3186 <h4>
3187 76. Write a JavaScript program to create a new array taking the first and
3188 last elements from a given array of integers and length must be greater or
3189 equal to 1.
3190 </h4>
3191 <form id="arrayForm">
3192 <label for="inputArray">Enter integers separated by commas:</label>
3193 <input type="text" id="inputArray" required />
3194
3195 <button type="button" onclick="createFirstLastArray()">
3196 Create Array
3197 </button>
3198 </form>
3199
3200 <p id="result"></p>
3201
3202 <script>
3203 // Your JavaScript code goes here
3204 function createFirstLastArray() {
3205 // Get user input for the array
3206 const inputArray = [Link]("inputArray").value;
3207
3208 // Convert the input string to an array of integers
3209 const integers = [Link](",").map(Number);
3210
3211 // Check if the array has at least one element
3212 if ([Link] >= 1) {
3213 // Create a new array with the first and last elements
3214 const firstLastArray = [integers[0], integers[[Link] - 1]];
3215
3216 // Display the result
3217 displayResult(firstLastArray);
3218 } else {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 54/298
1/31/24, 9:21 AM [Link]
3219 alert("Please enter at least one integer.");
3220 }
3221 }
3222
3223 function displayResult(resultArray) {
3224 // Display the result
3225 const resultElement = [Link]("result");
3226 [Link] = `First and Last Elements Array: [${[Link](
3227 ", "
3228 )}]`;
3229 }
3230 </script>
3231 <hr />
3232
3233 <h4>
3234 77. Write a JavaScript program to test whether an array of integers of
3235 length 2 contains 1 or a 3.
3236 </h4>
3237 <form id="arrayForm">
3238 <label for="inputArray">Enter two integers separated by commas:</label>
3239 <input type="text" id="inputArray" required />
3240
3241 <button type="button" onclick="testArray()">Test Array</button>
3242 </form>
3243
3244 <p id="result"></p>
3245
3246 <script>
3247 // Your JavaScript code goes here
3248 function testArray() {
3249 // Get user input for the array
3250 const inputArray = [Link]("inputArray").value;
3251
3252 // Convert the input string to an array of integers
3253 const integers = [Link](",").map(Number);
3254
3255 // Check if the array has exactly two elements
3256 if ([Link] === 2) {
3257 // Test whether the array contains 1 or 3
3258 const containsOneOrThree =
3259 [Link](1) || [Link](3);
3260
3261 // Display the result
3262 displayResult(containsOneOrThree);
3263 } else {
3264 alert("Please enter two integers separated by commas.");
3265 }
3266 }
3267
3268 function displayResult(containsOneOrThree) {
3269 // Display the result
3270 const resultElement = [Link]("result");
3271 [Link] = `Does the array contain 1 or 3? ${
3272 containsOneOrThree ? "Yes" : "No"
3273 }`;
3274 }
3275 </script>
3276 <hr />
3277
3278 <h4>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 55/298
1/31/24, 9:21 AM [Link]
3279 78. Write a JavaScript program to test whether an array of integers of
3280 length 2 does not contain 1 or a 3.
3281 </h4>
3282 <form id="arrayForm">
3283 <label for="inputArray">Enter two integers separated by commas:</label>
3284 <input type="text" id="inputArray" required />
3285
3286 <button type="button" onclick="testArray()">Test Array</button>
3287 </form>
3288
3289 <p id="result"></p>
3290
3291 <script>
3292 // Your JavaScript code goes here
3293 function testArray() {
3294 // Get user input for the array
3295 const inputArray = [Link]("inputArray").value;
3296
3297 // Convert the input string to an array of integers
3298 const integers = [Link](",").map(Number);
3299
3300 // Check if the array has exactly two elements
3301 if ([Link] === 2) {
3302 // Test whether the array does not contain 1 or 3
3303 const doesNotContainOneOrThree =
3304  && ;
3305
3306 // Display the result
3307 displayResult(doesNotContainOneOrThree);
3308 } else {
3309 alert("Please enter two integers separated by commas.");
3310 }
3311 }
3312
3313 function displayResult(doesNotContainOneOrThree) {
3314 // Display the result
3315 const resultElement = [Link]("result");
3316 [Link] = `Does the array not contain 1 or 3? ${
3317 doesNotContainOneOrThree ? "Yes" : "No"
3318 }`;
3319 }
3320 </script>
3321 <hr />
3322
3323 <h4>
3324 79. Write a JavaScript program to test whether a given array of integers
3325 contains 30 and 40 twice. The array length should be 0, 1, or 2.
3326 </h4>
3327 <form id="arrayForm">
3328 <label for="inputArray">Enter integers separated by commas:</label>
3329 <input type="text" id="inputArray" required />
3330
3331 <button type="button" onclick="testArray()">Test Array</button>
3332 </form>
3333
3334 <p id="result"></p>
3335
3336 <script>
3337 // Your JavaScript code goes here
3338 function testArray() {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 56/298
1/31/24, 9:21 AM [Link]
3339 // Get user input for the array
3340 const inputArray = [Link]("inputArray").value;
3341
3342 // Convert the input string to an array of integers
3343 const integers = [Link](",").map(Number);
3344
3345 // Check if the array length is 0, 1, or 2
3346 if ([Link] <= 2) {
3347 // Test whether the array contains 30 and 40 twice
3348 const contains30And40Twice =
3349 [Link](30) &&
3350 [Link](30) !== [Link](30) &&
3351 [Link](40) &&
3352 [Link](40) !== [Link](40);
3353
3354 // Display the result
3355 displayResult(contains30And40Twice);
3356 } else {
3357 alert(
3358 "Please enter an array with 0, 1, or 2 integers separated by commas."
3359 );
3360 }
3361 }
3362
3363 function displayResult(contains30And40Twice) {
3364 // Display the result
3365 const resultElement = [Link]("result");
3366 [Link] = `Does the array contain 30 and 40 twice? ${
3367 contains30And40Twice ? "Yes" : "No"
3368 }`;
3369 }
3370 </script>
3371 <hr />
3372
3373 <h4>
3374 80. Write a JavaScript program to swap the first and last elements of a
3375 given array of integers. The array length should be at least 1.
3376 </h4>
3377 <form id="arrayForm">
3378 <label for="inputArray">Enter integers separated by commas:</label>
3379 <input type="text" id="inputArray" required />
3380
3381 <button type="button" onclick="swapElements()">Swap Elements</button>
3382 </form>
3383
3384 <p id="result"></p>
3385
3386 <script>
3387 // Your JavaScript code goes here
3388 function swapElements() {
3389 // Get user input for the array
3390 const inputArray = [Link]("inputArray").value;
3391
3392 // Convert the input string to an array of integers
3393 const integers = [Link](",").map(Number);
3394
3395 // Check if the array has at least one element
3396 if ([Link] >= 1) {
3397 // Swap the first and last elements
3398 const firstElement = integers[0];
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 57/298
1/31/24, 9:21 AM [Link]
3399 const lastElement = integers[[Link] - 1];
3400 integers[0] = lastElement;
3401 integers[[Link] - 1] = firstElement;
3402
3403 // Display the result
3404 displayResult(integers);
3405 } else {
3406 alert("Please enter an array with at least one integer.");
3407 }
3408 }
3409
3410 function displayResult(swappedArray) {
3411 // Display the result
3412 const resultElement = [Link]("result");
3413 [Link] = `Swapped Array: [${[Link](
3414 ", "
3415 )}]`;
3416 }
3417 </script>
3418 <hr />
3419
3420 <h4>
3421 81. Write a JavaScript program to add two digits of a given positive
3422 integer of length two.
3423 </h4>
3424 <form id="integerForm">
3425 <label for="inputInteger">Enter a positive integer of length two:</label>
3426 <input type="text" id="inputInteger" pattern="\d{2}" required />
3427
3428 <button type="button" onclick="addDigits()">Add Digits</button>
3429 </form>
3430
3431 <p id="result"></p>
3432
3433 <script>
3434 // Your JavaScript code goes here
3435 function addDigits() {
3436 // Get user input for the positive integer
3437 const inputInteger = [Link]("inputInteger").value;
3438
3439 // Check if the input is a positive integer of length two
3440 if (/^\d{2}$/.test(inputInteger)) {
3441 // Extract the two digits and add them
3442 const digit1 = parseInt([Link](0), 10);
3443 const digit2 = parseInt([Link](1), 10);
3444 const sum = digit1 + digit2;
3445
3446 // Display the result
3447 displayResult(sum);
3448 } else {
3449 alert("Please enter a positive integer of length two.");
3450 }
3451 }
3452
3453 function displayResult(sum) {
3454 // Display the result
3455 const resultElement = [Link]("result");
3456 [Link] = `Sum of the two digits: ${sum}`;
3457 }
3458 </script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 58/298
1/31/24, 9:21 AM [Link]
3459 <hr />
3460
3461 <h4>82. Write a JavaScript to add two positive integers without carry.</h4>
3462 <form id="integerForm">
3463 <label for="inputInteger1">Enter the first positive integer:</label>
3464 <input type="text" id="inputInteger1" pattern="\d+" required />
3465
3466 <label for="inputInteger2">Enter the second positive integer:</label>
3467 <input type="text" id="inputInteger2" pattern="\d+" required />
3468
3469 <button type="button" onclick="addIntegersWithoutCarry()">
3470 Add Integers Without Carry
3471 </button>
3472 </form>
3473
3474 <p id="result"></p>
3475
3476 <script>
3477 // Your JavaScript code goes here
3478 function addIntegersWithoutCarry() {
3479 // Get user input for the positive integers
3480 const inputInteger1 = [Link]("inputInteger1").value;
3481 const inputInteger2 = [Link]("inputInteger2").value;
3482
3483 // Check if the inputs are positive integers
3484 if (/^\d+$/.test(inputInteger1) && /^\d+$/.test(inputInteger2)) {
3485 // Pad the smaller number with leading zeros to make their lengths equal
3486 const maxLength = [Link](
3487 [Link],
3488 [Link]
3489 );
3490 const paddedInteger1 = [Link](maxLength, "0");
3491 const paddedInteger2 = [Link](maxLength, "0");
3492
3493 // Add the digits without carry
3494 let result = "";
3495 let carry = 0;
3496 for (let i = maxLength - 1; i >= 0; i--) {
3497 const digit1 = parseInt([Link](i), 10);
3498 const digit2 = parseInt([Link](i), 10);
3499 const sum = digit1 + digit2 + carry;
3500
3501 result = (sum % 10) + result; // Append the digit to the result
3502 carry = [Link](sum / 10);
3503 }
3504
3505 // Display the result
3506 displayResult(result);
3507 } else {
3508 alert("Please enter positive integers.");
3509 }
3510 }
3511
3512 function displayResult(result) {
3513 // Display the result
3514 const resultElement = [Link]("result");
3515 [Link] = `Sum without carry: ${
3516 [Link](/^0+/, "") || "0"
3517 }`;
3518 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 59/298
1/31/24, 9:21 AM [Link]
3519 </script>
3520 <hr />
3521
3522 <h4>
3523 83. Write a JavaScript to find the longest string from a given array of
3524 strings.
3525 </h4>
3526 <form id="stringArrayForm">
3527 <label for="inputStringArray">Enter strings separated by commas:</label>
3528 <input type="text" id="inputStringArray" required />
3529
3530 <button type="button" onclick="findLongestString()">
3531 Find Longest String
3532 </button>
3533 </form>
3534
3535 <p id="result"></p>
3536
3537 <script>
3538 // Your JavaScript code goes here
3539 function findLongestString() {
3540 // Get user input for the array of strings
3541 const inputStringArray =
3542 [Link]("inputStringArray").value;
3543
3544 // Convert the input string to an array of strings
3545 const stringArray = [Link](",");
3546
3547 // Find the longest string
3548 const longestString = [Link](
3549 (longest, current) =>
3550 [Link] > [Link] ? current : longest,
3551 ""
3552 );
3553
3554 // Display the result
3555 displayResult(longestString);
3556 }
3557
3558 function displayResult(longestString) {
3559 // Display the result
3560 const resultElement = [Link]("result");
3561 [Link] = `Longest String: ${longestString}`;
3562 }
3563 </script>
3564 <hr />
3565
3566 <h4>
3567 84. Write a JavaScript to replace each character of a given string by the
3568 next one in the English alphabet. Note: 'a' will be replace by 'b' or 'z'
3569 would be replaced by 'a'.
3570 </h4>
3571 <form id="replaceForm">
3572 <label for="inputString">Enter a string:</label>
3573 <input type="text" id="inputString" required />
3574
3575 <button type="button" onclick="replaceCharacters()">
3576 Replace Characters
3577 </button>
3578 </form>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 60/298
1/31/24, 9:21 AM [Link]
3579
3580 <p id="result"></p>
3581
3582 <script>
3583 // Your JavaScript code goes here
3584 function replaceCharacters() {
3585 // Get user input for the string
3586 const inputString = [Link]("inputString").value;
3587
3588 // Replace each character by the next one in the English alphabet
3589 const replacedString = inputString
3590 .split("")
3591 .map((char) => {
3592 if (char >= "a" && char < "z") {
3593 return [Link]([Link](0) + 1);
3594 } else if (char === "z") {
3595 return "a";
3596 } else if (char >= "A" && char < "Z") {
3597 return [Link]([Link](0) + 1);
3598 } else if (char === "Z") {
3599 return "A";
3600 } else {
3601 return char; // Keep non-alphabetic characters unchanged
3602 }
3603 })
3604 .join("");
3605
3606 // Display the result
3607 displayResult(replacedString);
3608 }
3609
3610 function displayResult(replacedString) {
3611 // Display the result
3612 const resultElement = [Link]("result");
3613 [Link] = `Replaced String: ${replacedString}`;
3614 }
3615 </script>
3616 <hr />
3617
3618 <h4>
3619 85. Write a JavaScript code to divide a given array of positive integers
3620 into two parts. First element goes to first part, second element goes to
3621 second part, and third element goes to first part and so on. Now compute
3622 the sum of two parts and store into an array of size two.
3623 </h4>
3624 <form id="arrayForm">
3625 <label for="inputArray"
3626 >Enter positive integers separated by commas:</label
3627 >
3628 <input type="text" id="inputArray" required />
3629
3630 <button type="button" onclick="divideAndSumArray()">
3631 Divide and Sum
3632 </button>
3633 </form>
3634
3635 <p id="result"></p>
3636
3637 <script>
3638 // Your JavaScript code goes here
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 61/298
1/31/24, 9:21 AM [Link]
3639 function divideAndSumArray() {
3640 // Get user input for the array of positive integers
3641 const inputArray = [Link]("inputArray").value;
3642
3643 // Convert the input string to an array of positive integers
3644 const positiveIntegers = inputArray
3645 .split(",")
3646 .map(Number)
3647 .filter((num) => num >= 0);
3648
3649 // Divide the array into two parts and compute the sum of each part
3650 const sums = [Link](
3651 (result, num, index) => {
3652 result[index % 2] += num;
3653 return result;
3654 },
3655 [0, 0]
3656 );
3657
3658 // Display the result
3659 displayResult(sums);
3660 }
3661
3662 function displayResult(sums) {
3663 // Display the result
3664 const resultElement = [Link]("result");
3665 [Link] = `Sum of Part 1: ${sums[0]}, Sum of Part 2: ${sums[1]
}`;
3666 }
3667 </script>
3668 <hr />
3669
3670 <h4>
3671 86. Write a JavaScript program to find the types of a given angle. i.
3672 Types of angles: 1. Acute angle: An angle between 0 and 90 degrees. 2.
3673 Right angle: An 90 degree angle. 3. Obtuse angle: An angle between 90 and
3674 180 degrees. 4. Straight angle: A 180 degree angle.
3675 </h4>
3676 <form id="angleForm">
3677 <label for="inputAngle">Enter an angle in degrees:</label>
3678 <input type="number" id="inputAngle" required />
3679
3680 <button type="button" onclick="findAngleType()">Find Angle Type</button>
3681 </form>
3682
3683 <p id="result"></p>
3684
3685 <script>
3686 // Your JavaScript code goes here
3687 function findAngleType() {
3688 // Get user input for the angle
3689 const inputAngle = [Link]("inputAngle").value;
3690
3691 // Convert the input to a number
3692 const angle = parseFloat(inputAngle);
3693
3694 // Check the type of the angle
3695 let angleType;
3696 if (isNaN(angle)) {
3697 angleType = "Invalid input. Please enter a valid number.";
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 62/298
1/31/24, 9:21 AM [Link]
3698 } else if (angle < 0 || angle > 180) {
3699 angleType =
3700 "Invalid angle. Please enter an angle between 0 and 180 degrees.";
3701 } else if (angle < 90) {
3702 angleType = "Acute angle";
3703 } else if (angle === 90) {
3704 angleType = "Right angle";
3705 } else if (angle < 180) {
3706 angleType = "Obtuse angle";
3707 } else {
3708 angleType = "Straight angle";
3709 }
3710
3711 // Display the result
3712 displayResult(angleType);
3713 }
3714
3715 function displayResult(angleType) {
3716 // Display the result
3717 const resultElement = [Link]("result");
3718 [Link] = `Angle Type: ${angleType}`;
3719 }
3720 </script>
3721 <hr />
3722
3723 <h4>
3724 87. Write a JavaScript program to check whether two arrays of integers of
3725 same length are similar or not. The arrays will be similar if one array
3726 can be obtained from another array by swapping at most one pair of
3727 elements.
3728 </h4>
3729 <form id="arraysForm">
3730 <label for="inputArray1"
3731 >Enter the first array of integers (comma-separated):</label
3732 >
3733 <input type="text" id="inputArray1" required />
3734
3735 <label for="inputArray2"
3736 >Enter the second array of integers (comma-separated):</label
3737 >
3738 <input type="text" id="inputArray2" required />
3739
3740 <button type="button" onclick="checkSimilarArrays()">
3741 Check Similarity
3742 </button>
3743 </form>
3744
3745 <p id="result"></p>
3746
3747 <script>
3748 // Your JavaScript code goes here
3749 function checkSimilarArrays() {
3750 // Get user input for the two arrays
3751 const inputArray1 = [Link]("inputArray1").value;
3752 const inputArray2 = [Link]("inputArray2").value;
3753
3754 // Convert the input strings to arrays of integers
3755 const array1 = [Link](",").map(Number);
3756 const array2 = [Link](",").map(Number);
3757
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 63/298
1/31/24, 9:21 AM [Link]
3758 // Check if the arrays are of the same length
3759 if ([Link] !== [Link]) {
3760 displayResult("Arrays are not of the same length.");
3761 return;
3762 }
3763
3764 // Count the number of differences between the arrays
3765 let differences = 0;
3766 for (let i = 0; i < [Link]; i++) {
3767 if (array1[i] !== array2[i]) {
3768 differences++;
3769 }
3770 }
3771
3772 // Check if the arrays are similar
3773 const similar = differences === 0 || differences === 2;
3774
3775 // Display the result
3776 displayResult(
3777 similar ? "Arrays are similar." : "Arrays are not similar."
3778 );
3779 }
3780
3781 function displayResult(result) {
3782 // Display the result
3783 const resultElement = [Link]("result");
3784 [Link] = result;
3785 }
3786 </script>
3787 <hr />
3788
3789 <h4>
3790 88. Write a JavaScript program to check whether two given integers are
3791 similar or not, if a given divisor divides both integers and it does not
3792 divide either
3793 </h4>
3794 <form id="integersForm">
3795 <label for="inputInteger1">Enter the first integer:</label>
3796 <input type="number" id="inputInteger1" required />
3797
3798 <label for="inputInteger2">Enter the second integer:</label>
3799 <input type="number" id="inputInteger2" required />
3800
3801 <label for="inputDivisor">Enter the divisor:</label>
3802 <input type="number" id="inputDivisor" required />
3803
3804 <button type="button" onclick="checkSimilarIntegers()">
3805 Check Similarity
3806 </button>
3807 </form>
3808
3809 <p id="result"></p>
3810
3811 <script>
3812 // Your JavaScript code goes here
3813 function checkSimilarIntegers() {
3814 // Get user input for the two integers and the divisor
3815 const integer1 = parseInt(
3816 [Link]("inputInteger1").value,
3817 10
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 64/298
1/31/24, 9:21 AM [Link]
3818 );
3819 const integer2 = parseInt(
3820 [Link]("inputInteger2").value,
3821 10
3822 );
3823 const divisor = parseInt(
3824 [Link]("inputDivisor").value,
3825 10
3826 );
3827
3828 // Check if the divisor is not 0
3829 if (divisor === 0) {
3830 displayResult("Invalid divisor. Please enter a non-zero divisor.");
3831 return;
3832 }
3833
3834 // Check if the integers are similar
3835 const similar =
3836 integer1 % divisor === 0 &&
3837 integer2 % divisor === 0 &&
3838 (integer1 % divisor !== 0 || integer2 % divisor !== 0);
3839
3840 // Display the result
3841 displayResult(
3842 similar ? "Integers are similar." : "Integers are not similar."
3843 );
3844 }
3845
3846 function displayResult(result) {
3847 // Display the result
3848 const resultElement = [Link]("result");
3849 [Link] = result;
3850 }
3851 </script>
3852 <hr />
3853
3854 <h4>
3855 89. Write a JavaScript program to check whether it is possible to replace
3856 $ in a given expression x $ y = z with one of the four signs +, -, * or /
3857 to obtain a correct expression. For example x = 10, y = 30 and z = 300, we
3858 can replace $ with a multiple operator (*) to obtain x * y = z
3859 </h4>
3860 <form id="expressionForm">
3861 <label for="inputX">Enter the value of x:</label>
3862 <input type="number" id="inputX" required />
3863
3864 <label for="inputY">Enter the value of y:</label>
3865 <input type="number" id="inputY" required />
3866
3867 <label for="inputZ">Enter the value of z:</label>
3868 <input type="number" id="inputZ" required />
3869
3870 <button type="button" onclick="checkExpression()">
3871 Check Expression
3872 </button>
3873 </form>
3874
3875 <p id="result"></p>
3876
3877 <script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 65/298
1/31/24, 9:21 AM [Link]
3878 // Your JavaScript code goes here
3879 function checkExpression() {
3880 // Get user input for the values of x, y, and z
3881 const x = parseFloat([Link]("inputX").value);
3882 const y = parseFloat([Link]("inputY").value);
3883 const z = parseFloat([Link]("inputZ").value);
3884
3885 // Check if it is possible to replace $ with one of the four signs (+, -, * or
/)
3886 const possible =
3887 x + y === z || x - y === z || x * y === z || x / y === z;
3888
3889 // Display the result
3890 displayResult(possible ? "It is possible." : "It is not possible.");
3891 }
3892
3893 function displayResult(result) {
3894 // Display the result
3895 const resultElement = [Link]("result");
3896 [Link] = result;
3897 }
3898 </script>
3899 <hr />
3900
3901 <h4>
3902 90. Write a JavaScript program to find the kth greatest element of a given
3903 array of integers
3904 </h4>
3905 <form id="arrayForm">
3906 <label for="inputArray"
3907 >Enter the array of integers (comma-separated):</label
3908 >
3909 <input type="text" id="inputArray" required />
3910
3911 <label for="inputK">Enter the value of k:</label>
3912 <input type="number" id="inputK" required />
3913
3914 <button type="button" onclick="findKthGreatestElement()">
3915 Find Kth Greatest Element
3916 </button>
3917 </form>
3918
3919 <p id="result"></p>
3920
3921 <script>
3922 // Your JavaScript code goes here
3923 function findKthGreatestElement() {
3924 // Get user input for the array of integers and k
3925 const inputArray = [Link]("inputArray").value;
3926 const array = [Link](",").map(Number);
3927 const k = parseInt([Link]("inputK").value, 10);
3928
3929 // Sort the array in descending order
3930 const sortedArray = [Link]((a, b) => b - a);
3931
3932 // Check if k is within the array bounds
3933 if (k >= 1 && k <= [Link]) {
3934 // Get the kth greatest element
3935 const kthGreatestElement = sortedArray[k - 1];
3936
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 66/298
1/31/24, 9:21 AM [Link]
3937 // Display the result
3938 displayResult(
3939 `The ${k}th greatest element is: ${kthGreatestElement}`
3940 );
3941 } else {
3942 // Display an error message if k is out of bounds
3943 displayResult(
3944 "Invalid value of k. Please enter a value within the array bounds."
3945 );
3946 }
3947 }
3948
3949 function displayResult(result) {
3950 // Display the result
3951 const resultElement = [Link]("result");
3952 [Link] = result;
3953 }
3954 </script>
3955 <hr />
3956
3957 <h4>
3958 91. Write a JavaScript program to find the maximum possible sum of some of
3959 its k consecutive numbers (numbers that follow each other in order.) of a
3960 given array of positive integers
3961 </h4>
3962 <form id="arrayForm">
3963 <label for="inputArray"
3964 >Enter the array of positive integers (comma-separated):</label
3965 >
3966 <input type="text" id="inputArray" required />
3967
3968 <label for="inputK">Enter the value of k:</label>
3969 <input type="number" id="inputK" required />
3970
3971 <button type="button" onclick="findMaxSumOfKConsecutiveNumbers()">
3972 Find Maximum Sum
3973 </button>
3974 </form>
3975
3976 <p id="result"></p>
3977
3978 <script>
3979 // Your JavaScript code goes here
3980 function findMaxSumOfKConsecutiveNumbers() {
3981 // Get user input for the array of positive integers and k
3982 const inputArray = [Link]("inputArray").value;
3983 const array = [Link](",").map(Number);
3984 const k = parseInt([Link]("inputK").value, 10);
3985
3986 // Check if k is within the array bounds
3987 if (k >= 1 && k <= [Link]) {
3988 let maxSum = 0;
3989 let currentSum = 0;
3990
3991 // Calculate the sum of the first k elements
3992 for (let i = 0; i < k; i++) {
3993 currentSum += array[i];
3994 }
3995
3996 maxSum = currentSum;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 67/298
1/31/24, 9:21 AM [Link]
3997
3998 // Calculate the sum of consecutive k elements and find the maximum
3999 for (let i = k; i < [Link]; i++) {
4000 currentSum = currentSum - array[i - k] + array[i];
4001 maxSum = [Link](maxSum, currentSum);
4002 }
4003
4004 // Display the result
4005 displayResult(
4006 `The maximum sum of ${k} consecutive numbers is: ${maxSum}`
4007 );
4008 } else {
4009 // Display an error message if k is out of bounds
4010 displayResult(
4011 "Invalid value of k. Please enter a value within the array bounds."
4012 );
4013 }
4014 }
4015
4016 function displayResult(result) {
4017 // Display the result
4018 const resultElement = [Link]("result");
4019 [Link] = result;
4020 }
4021 </script>
4022 <hr />
4023
4024 <h4>
4025 92. Write a JavaScript program to find the maximal difference between any
4026 two adjacent elements of a given array of integers
4027 </h4>
4028 <form id="arrayForm">
4029 <label for="inputArray"
4030 >Enter the array of integers (comma-separated):</label
4031 >
4032 <input type="text" id="inputArray" required />
4033
4034 <button type="button" onclick="findMaximalDifference()">
4035 Find Maximal Difference
4036 </button>
4037 </form>
4038
4039 <p id="result"></p>
4040
4041 <script>
4042 // Your JavaScript code goes here
4043 function findMaximalDifference() {
4044 // Get user input for the array of integers
4045 const inputArray = [Link]("inputArray").value;
4046 const array = [Link](",").map(Number);
4047
4048 // Check if the array has at least two elements
4049 if ([Link] >= 2) {
4050 let maximalDifference = 0;
4051
4052 // Iterate over the array and find the maximal difference between adjacent
elements
4053 for (let i = 0; i < [Link] - 1; i++) {
4054 const difference = [Link](array[i] - array[i + 1]);
4055 maximalDifference = [Link](maximalDifference, difference);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 68/298
1/31/24, 9:21 AM [Link]
4056 }
4057
4058 // Display the result
4059 displayResult(
4060 `The maximal difference between any two adjacent elements is:
${maximalDifference}`
4061 );
4062 } else {
4063 // Display an error message if the array has less than two elements
4064 displayResult("Array must have at least two elements.");
4065 }
4066 }
4067
4068 function displayResult(result) {
4069 // Display the result
4070 const resultElement = [Link]("result");
4071 [Link] = result;
4072 }
4073 </script>
4074 <hr />
4075
4076 <h4>
4077 93. Write a JavaScript program to find the maximal difference among all
4078 possible pairs of a given array of integers.
4079 </h4>
4080 <form id="arrayForm">
4081 <label for="inputArray"
4082 >Enter the array of integers (comma-separated):</label
4083 >
4084 <input type="text" id="inputArray" required />
4085
4086 <button type="button" onclick="findMaximalDifference()">
4087 Find Maximal Difference
4088 </button>
4089 </form>
4090
4091 <p id="result"></p>
4092
4093 <script>
4094 // Your JavaScript code goes here
4095 function findMaximalDifference() {
4096 // Get user input for the array of integers
4097 const inputArray = [Link]("inputArray").value;
4098 const array = [Link](",").map(Number);
4099
4100 // Check if the array has at least two elements
4101 if ([Link] >= 2) {
4102 let maximalDifference = 0;
4103
4104 // Iterate over all pairs of elements in the array and find the maximal
difference
4105 for (let i = 0; i < [Link]; i++) {
4106 for (let j = i + 1; j < [Link]; j++) {
4107 const difference = [Link](array[i] - array[j]);
4108 maximalDifference = [Link](maximalDifference, difference);
4109 }
4110 }
4111
4112 // Display the result
4113 displayResult(
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 69/298
1/31/24, 9:21 AM [Link]
4114 `The maximal difference among all possible pairs is: ${maximalDifference}`
4115 );
4116 } else {
4117 // Display an error message if the array has less than two elements
4118 displayResult("Array must have at least two elements.");
4119 }
4120 }
4121
4122 function displayResult(result) {
4123 // Display the result
4124 const resultElement = [Link]("result");
4125 [Link] = result;
4126 }
4127 </script>
4128 <hr />
4129
4130 <h4>
4131 94. Write a JavaScript program to find the number which appears most in a
4132 given array of integers.
4133 </h4>
4134 <form id="arrayForm">
4135 <label for="inputArray"
4136 >Enter the array of integers (comma-separated):</label
4137 >
4138 <input type="text" id="inputArray" required />
4139
4140 <button type="button" onclick="findMostFrequentNumber()">
4141 Find Most Frequent Number
4142 </button>
4143 </form>
4144
4145 <p id="result"></p>
4146
4147 <script>
4148 // Your JavaScript code goes here
4149 function findMostFrequentNumber() {
4150 // Get user input for the array of integers
4151 const inputArray = [Link]("inputArray").value;
4152 const array = [Link](",").map(Number);
4153
4154 // Create an object to store the frequency of each number
4155 const frequencyMap = {};
4156
4157 // Iterate through the array to count the frequency of each number
4158 [Link]((num) => {
4159 frequencyMap[num] = (frequencyMap[num] || 0) + 1;
4160 });
4161
4162 // Find the number with the highest frequency
4163 let mostFrequentNumber;
4164 let maxFrequency = 0;
4165
4166 for (const num in frequencyMap) {
4167 if (frequencyMap[num] > maxFrequency) {
4168 mostFrequentNumber = num;
4169 maxFrequency = frequencyMap[num];
4170 }
4171 }
4172
4173 // Display the result
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 70/298
1/31/24, 9:21 AM [Link]
4174 displayResult(
4175 `The most frequent number is: ${mostFrequentNumber}, with a frequency of
${maxFrequency}`
4176 );
4177 }
4178
4179 function displayResult(result) {
4180 // Display the result
4181 const resultElement = [Link]("result");
4182 [Link] = result;
4183 }
4184 </script>
4185 <hr />
4186
4187 <h4>
4188 95. Write a JavaScript program to replace all the numbers with a specified
4189 number of a given array of integers.
4190 </h4>
4191 <form id="arrayForm">
4192 <label for="inputArray"
4193 >Enter the array of integers (comma-separated):</label
4194 >
4195 <input type="text" id="inputArray" required />
4196
4197 <label for="targetNumber">Enter the target number to replace:</label>
4198 <input type="number" id="targetNumber" required />
4199
4200 <label for="replacementNumber">Enter the replacement number:</label>
4201 <input type="number" id="replacementNumber" required />
4202
4203 <button type="button" onclick="replaceNumbers()">Replace Numbers</button>
4204 </form>
4205
4206 <p id="result"></p>
4207
4208 <script>
4209 // Your JavaScript code goes here
4210 function replaceNumbers() {
4211 // Get user input for the array of integers, target number, and replacement
number
4212 const inputArray = [Link]("inputArray").value;
4213 const array = [Link](",").map(Number);
4214 const targetNumber = parseInt(
4215 [Link]("targetNumber").value,
4216 10
4217 );
4218 const replacementNumber = parseInt(
4219 [Link]("replacementNumber").value,
4220 10
4221 );
4222
4223 // Replace all occurrences of the target number with the replacement number
4224 const replacedArray = [Link]((num) =>
4225 num === targetNumber ? replacementNumber : num
4226 );
4227
4228 // Display the result
4229 displayResult(`Array with numbers replaced: [${replacedArray}]`);
4230 }
4231
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 71/298
1/31/24, 9:21 AM [Link]
4232 function displayResult(result) {
4233 // Display the result
4234 const resultElement = [Link]("result");
4235 [Link] = result;
4236 }
4237 </script>
4238 <hr />
4239
4240 <h4>
4241 96. Write a JavaScript program to compute the sum of absolute differences
4242 of consecutive numbers of a given array of integers
4243 </h4>
4244 <form id="arrayForm">
4245 <label for="inputArray"
4246 >Enter the array of integers (comma-separated):</label
4247 >
4248 <input type="text" id="inputArray" required />
4249
4250 <button type="button" onclick="computeSum()">Compute Sum</button>
4251 </form>
4252
4253 <p id="result"></p>
4254
4255 <script>
4256 // Your JavaScript code goes here
4257 function computeSum() {
4258 // Get user input for the array of integers
4259 const inputArray = [Link]("inputArray").value;
4260 const array = [Link](",").map(Number);
4261
4262 // Initialize sum of absolute differences
4263 let sum = 0;
4264
4265 // Compute the sum of absolute differences of consecutive numbers
4266 for (let i = 1; i < [Link]; i++) {
4267 sum += [Link](array[i] - array[i - 1]);
4268 }
4269
4270 // Display the result
4271 displayResult(`Sum of absolute differences: ${sum}`);
4272 }
4273
4274 function displayResult(result) {
4275 // Display the result
4276 const resultElement = [Link]("result");
4277 [Link] = result;
4278 }
4279 </script>
4280 <hr />
4281
4282 <h4>
4283 97. Write a JavaScript program to find the shortest possible string which
4284 can create a string to make it a palindrome by adding characters to the
4285 end of it.
4286 </h4>
4287 <form id="stringForm">
4288 <label for="inputString">Enter the string:</label>
4289 <input type="text" id="inputString" required />
4290
4291 <button type="button" onclick="findShortestPalindrome()">
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 72/298
1/31/24, 9:21 AM [Link]
4292 Find Shortest Palindrome
4293 </button>
4294 </form>
4295
4296 <p id="result"></p>
4297
4298 <script>
4299 // Your JavaScript code goes here
4300 function findShortestPalindrome() {
4301 // Get user input for the string
4302 const inputString = [Link]("inputString").value;
4303
4304 // Find the shortest possible palindrome by iterating through the characters of
the string
4305 for (let i = 0; i < [Link]; i++) {
4306 if (isPalindrome([Link](i))) {
4307 // If the substring starting from the current character is a palindrome,
then add the characters before it to the end of the string
4308 const palindrome =
4309 inputString +
4310 [Link](0, i).split("").reverse().join("");
4311 displayResult(`Shortest palindrome: ${palindrome}`);
4312 return;
4313 }
4314 }
4315
4316 // If the string itself is already a palindrome, then it is the shortest
possible palindrome
4317 displayResult(`Shortest palindrome: ${inputString}`);
4318 }
4319
4320 function isPalindrome(str) {
4321 // Check if a string is a palindrome
4322 return str === [Link]("").reverse().join("");
4323 }
4324
4325 function displayResult(result) {
4326 // Display the result
4327 const resultElement = [Link]("result");
4328 [Link] = result;
4329 }
4330 </script>
4331 <hr />
4332
4333 <h4>
4334 98. Write a JavaScript program to switch case of the minimum possible
4335 number of letters to make a given string written in the upper case or in
4336 the lower case. Fox example "Write" will be write and "PHp" will be "PHP"
4337 </h4>
4338 <form id="stringForm">
4339 <label for="inputString">Enter the string:</label>
4340 <input type="text" id="inputString" required />
4341
4342 <button type="button" onclick="switchCase()">Switch Case</button>
4343 </form>
4344
4345 <p id="result"></p>
4346
4347 <script>
4348 // Your JavaScript code goes here
4349 function switchCase() {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 73/298
1/31/24, 9:21 AM [Link]
4350 // Get user input for the string
4351 const inputString = [Link]("inputString").value;
4352
4353 // Count the number of uppercase and lowercase letters
4354 let uppercaseCount = 0;
4355 let lowercaseCount = 0;
4356
4357 for (let i = 0; i < [Link]; i++) {
4358 if (inputString[i] >= "A" && inputString[i] <= "Z") {
4359 uppercaseCount++;
4360 } else if (inputString[i] >= "a" && inputString[i] <= "z") {
4361 lowercaseCount++;
4362 }
4363 }
4364
4365 // Convert the string to the case with the minimum number of changes
4366 let resultString;
4367 if (uppercaseCount <= lowercaseCount) {
4368 resultString = [Link]();
4369 } else {
4370 resultString = [Link]();
4371 }
4372
4373 // Display the result
4374 displayResult(`Switched case: ${resultString}`);
4375 }
4376
4377 function displayResult(result) {
4378 // Display the result
4379 const resultElement = [Link]("result");
4380 [Link] = result;
4381 }
4382 </script>
4383 <hr />
4384
4385 <h4>
4386 99. Write a JavaScript program to check whether it is possible to
4387 rearrange characters of a given string in such way that it will become
4388 equal to another given string.
4389 </h4>
4390 <form id="stringForm">
4391 <label for="string1">Enter the first string:</label>
4392 <input type="text" id="string1" required />
4393
4394 <label for="string2">Enter the second string:</label>
4395 <input type="text" id="string2" required />
4396
4397 <button type="button" onclick="checkRearrange()">Check Rearrange</button>
4398 </form>
4399
4400 <p id="result"></p>
4401
4402 <script>
4403 // Your JavaScript code goes here
4404 function checkRearrange() {
4405 // Get user input for the strings
4406 const string1 = [Link]("string1").value;
4407 const string2 = [Link]("string2").value;
4408
4409 // Sort the characters of both strings and compare them
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 74/298
1/31/24, 9:21 AM [Link]
4410 const sortedString1 = [Link]("").sort().join("");
4411 const sortedString2 = [Link]("").sort().join("");
4412
4413 // Check if the sorted strings are equal
4414 const isPossible = sortedString1 === sortedString2;
4415
4416 // Display the result
4417 if (isPossible) {
4418 displayResult(
4419 "It is possible to rearrange the characters of the first string to make it
equal to the second string."
4420 );
4421 } else {
4422 displayResult(
4423 "It is not possible to rearrange the characters of the first string to make
it equal to the second string."
4424 );
4425 }
4426 }
4427
4428 function displayResult(result) {
4429 // Display the result
4430 const resultElement = [Link]("result");
4431 [Link] = result;
4432 }
4433 </script>
4434 <hr />
4435
4436 <h4>
4437 100. Write a JavaScript program to check whether there is at least one
4438 element which occurs in two given sorted arrays of integers.
4439 </h4>
4440 <form id="arrayForm">
4441 <label for="array1">Enter the first sorted array:</label>
4442 <input type="text" id="array1" placeholder="e.g., 1, 2, 3" />
4443
4444 <label for="array2">Enter the second sorted array:</label>
4445 <input type="text" id="array2" placeholder="e.g., 2, 3, 4" />
4446
4447 <button type="button" onclick="checkCommonElements()">
4448 Check Common Elements
4449 </button>
4450 </form>
4451
4452 <p id="result"></p>
4453
4454 <script>
4455 // Your JavaScript code goes here
4456 function checkCommonElements() {
4457 // Get user input for the arrays
4458 const array1 = document
4459 .getElementById("array1")
4460 .[Link](",")
4461 .map(Number);
4462 const array2 = document
4463 .getElementById("array2")
4464 .[Link](",")
4465 .map(Number);
4466
4467 // Initialize pointers for both arrays
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 75/298
1/31/24, 9:21 AM [Link]
4468 let pointer1 = 0;
4469 let pointer2 = 0;
4470
4471 // Iterate through both arrays to find common elements
4472 while (pointer1 < [Link] && pointer2 < [Link]) {
4473 if (array1[pointer1] === array2[pointer2]) {
4474 // If the elements are equal, display the result and return
4475 displayResult(
4476 "There is at least one common element in the two arrays."
4477 );
4478 return;
4479 } else if (array1[pointer1] < array2[pointer2]) {
4480 // If the element in array1 is smaller, move pointer1 forward
4481 pointer1++;
4482 } else {
4483 // If the element in array2 is smaller, move pointer2 forward
4484 pointer2++;
4485 }
4486 }
4487
4488 // If no common element is found after iterating both arrays
4489 displayResult("There are no common elements in the two arrays.");
4490 }
4491
4492 function displayResult(result) {
4493 // Display the result
4494 const resultElement = [Link]("result");
4495 [Link] = result;
4496 }
4497 </script>
4498 <hr />
4499
4500 <!-- --------------------------- 201 --------------------------------- -->
4501 <h4>
4502 [Link] a JavaScript program to get an object containing the parameters
4503 of the current URL
4504 </h4>
4505 <form id="expressionForm">
4506 <label for="inputX">Enter the value of x:</label>
4507 <input type="number" id="inputX" required />
4508
4509 <label for="inputY">Enter the value of y:</label>
4510 <input type="number" id="inputY" required />
4511
4512 <label for="inputZ">Enter the value of z:</label>
4513 <input type="number" id="inputZ" required />
4514
4515 <button type="button" onclick="checkExpression()">
4516 Check Expression
4517 </button>
4518 </form>
4519
4520 <p id="result"></p>
4521
4522 <script>
4523 // Your JavaScript code goes here
4524 function checkExpression() {
4525 // Get user input for the values of x, y, and z
4526 const x = parseFloat([Link]("inputX").value);
4527 const y = parseFloat([Link]("inputY").value);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 76/298
1/31/24, 9:21 AM [Link]
4528 const z = parseFloat([Link]("inputZ").value);
4529
4530 // Check if it is possible to replace $ with one of the four signs (+, -, * or
/)
4531 const possible =
4532 x + y === z || x - y === z || x * y === z || x / y === z;
4533
4534 // Display the result
4535 displayResult(possible ? "It is possible." : "It is not possible.");
4536 }
4537
4538 function displayResult(result) {
4539 // Display the result
4540 const resultElement = [Link]("result");
4541 [Link] = result;
4542 }
4543 </script>
4544 <hr />
4545
4546 <h4>
4547 [Link] a JavaScript program to group the elements of a given array
4548 based on the given function.
4549 </h4>
4550 <form id="groupForm">
4551 <label for="numberInput">Enter numbers separated by commas:</label>
4552 <input type="text" id="numberInput" placeholder="e.g., 1, 2, 3" />
4553
4554 <button type="button" onclick="groupNumbers()">Group Numbers</button>
4555 </form>
4556
4557 <div id="result"></div>
4558
4559 <script>
4560 function groupElementsByFunction(arr, func) {
4561 return [Link]((acc, curr) => {
4562 const key = func(curr);
4563 if (!acc[key]) {
4564 acc[key] = [];
4565 }
4566 acc[key].push(curr);
4567 return acc;
4568 }, {});
4569 }
4570
4571 function groupNumbers() {
4572 const numbersInput = [Link]("numberInput").value;
4573 const numbersArray = numbersInput
4574 .split(",")
4575 .map((num) => parseInt([Link]()));
4576
4577 const groupedByEvenOdd = groupElementsByFunction(numbersArray, (num) =>
4578 num % 2 === 0 ? "even" : "odd"
4579 );
4580
4581 // Display the grouped elements
4582 const resultElement = [Link]("result");
4583 [Link] = "<h2>Grouped Numbers:</h2>";
4584 for (const key in groupedByEvenOdd) {
4585 if ([Link](key)) {
4586 [Link] += `<p>${key}: ${groupedByEvenOdd[key].join(
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 77/298
1/31/24, 9:21 AM [Link]
4587 ", "
4588 )}</p>`;
4589 }
4590 }
4591 }
4592 </script>
4593 <hr />
4594
4595 <h4>
4596 [Link] a JavaScript program to Initialize a two dimension array of
4597 given width and height and value.
4598 </h4>
4599 <form id="arrayForm">
4600 <label for="widthInput">Width:</label>
4601 <input type="number" id="widthInput" min="1" required />
4602 <br />
4603 <label for="heightInput">Height:</label>
4604 <input type="number" id="heightInput" min="1" required />
4605 <br />
4606 <label for="valueInput">Initial Value:</label>
4607 <input type="text" id="valueInput" required />
4608 <br />
4609 <button type="button" onclick="initializeArray()">
4610 Initialize Array
4611 </button>
4612 </form>
4613
4614 <div id="result"></div>
4615
4616 <script>
4617 function initializeArray() {
4618 const width = parseInt([Link]("widthInput").value);
4619 const height = parseInt([Link]("heightInput").value);
4620 const value = [Link]("valueInput").value;
4621
4622 // Initialize a 2D array
4623 const array = [];
4624 for (let i = 0; i < height; i++) {
4625 array[i] = [];
4626 for (let j = 0; j < width; j++) {
4627 array[i][j] = value;
4628 }
4629 }
4630
4631 // Display the initialized array
4632 const resultElement = [Link]("result");
4633 [Link] = "<h2>Initialized 2D Array:</h2>";
4634 [Link] +=
4635 "<pre>" + [Link](array, null, 2) + "</pre>";
4636 }
4637 </script>
4638 <hr />
4639
4640 <h4>
4641 [Link] a JavaScript program to initialize an array containing the
4642 numbers in the specified range where start and end are inclusive with
4643 their common difference step
4644 </h4>
4645 <form id="rangeForm">
4646 <label for="startInput">Start:</label>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 78/298
1/31/24, 9:21 AM [Link]
4647 <input type="number" id="startInput" required />
4648 <br />
4649 <label for="endInput">End:</label>
4650 <input type="number" id="endInput" required />
4651 <br />
4652 <label for="stepInput">Step:</label>
4653 <input type="number" id="stepInput" required />
4654 <br />
4655 <button type="button" onclick="initializeArray()">
4656 Initialize Array
4657 </button>
4658 </form>
4659
4660 <div id="result"></div>
4661
4662 <script>
4663 function initializeArray() {
4664 const start = parseInt([Link]("startInput").value);
4665 const end = parseInt([Link]("endInput").value);
4666 const step = parseInt([Link]("stepInput").value);
4667
4668 const array = [];
4669 for (let i = start; i <= end; i += step) {
4670 [Link](i);
4671 }
4672
4673 const resultElement = [Link]("result");
4674 [Link] = "<h2>Initialized Array:</h2>";
4675 [Link] +=
4676 "<pre>" + [Link](array, null, 2) + "</pre>";
4677 }
4678 </script>
4679
4680 <h4>
4681 [Link] a JavaScript program to Join all given URL segments together,
4682 then normalizes the resulting URL.
4683 </h4>
4684 <form id="urlForm">
4685 <label for="urlSegments">URL Segments:</label>
4686 <input
4687 type="text"
4688 id="urlSegments"
4689 placeholder="e.g., [Link] /path, ?query=value"
4690 />
4691 <br />
4692 <button type="button" onclick="normalizeURL()">Normalize URL</button>
4693 </form>
4694
4695 <div id="result"></div>
4696
4697 <script>
4698 function normalizeURL() {
4699 const urlSegments = [Link]("urlSegments").[Link]();
4700
4701 try {
4702 // Join URL segments
4703 const joinedURL = new URL(urlSegments, "[Link]
4704
4705 // Normalize URL
4706 const normalizedURL = [Link];
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 79/298
1/31/24, 9:21 AM [Link]
4707
4708 // Display the normalized URL
4709 const resultElement = [Link]("result");
4710 [Link] = "<h2>Normalized URL:</h2>";
4711 [Link] += `<p>${normalizedURL}</p>`;
4712 } catch (error) {
4713 [Link]("Invalid URL:", error);
4714 const resultElement = [Link]("result");
4715 [Link] = "<h2>Error:</h2>";
4716 [Link] += `<p>${[Link]}</p>`;
4717 }
4718 }
4719 </script>
4720 <hr />
4721
4722 <h4>
4723 [Link] a JavaScript program to check whether all elements in a given
4724 array are equal or not.
4725 </h4>
4726 <form id="arrayForm">
4727 <label for="arrayInput">Enter array elements separated by commas:</label>
4728 <input type="text" id="arrayInput" placeholder="e.g., 1, 1, 1" />
4729 <br />
4730 <button type="button" onclick="checkEquality()">Check Equality</button>
4731 </form>
4732
4733 <div id="result"></div>
4734
4735 <script>
4736 function checkEquality() {
4737 const arrayInput = [Link]("arrayInput").[Link]();
4738 const array = [Link](",").map((item) => [Link]());
4739
4740 let areEqual = true;
4741 for (let i = 1; i < [Link]; i++) {
4742 if (array[i] !== array[0]) {
4743 areEqual = false;
4744 break;
4745 }
4746 }
4747
4748 const resultElement = [Link]("result");
4749 [Link] = "<h2>Result:</h2>";
4750 if (areEqual) {
4751 [Link] += "<p>All elements are equal.</p>";
4752 } else {
4753 [Link] += "<p>Not all elements are equal.</p>";
4754 }
4755 }
4756 </script>
4757 <hr />
4758
4759 <h4>
4760 [Link] a JavaScript program to compute the average of an array, after
4761 mapping each element to a value using the provided function.
4762 </h4>
4763 <form id="arrayForm">
4764 <label for="arrayInput">Enter array elements separated by commas:</label>
4765 <input type="text" id="arrayInput" placeholder="e.g., 1, 2, 3" />
4766 <br />
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 80/298
1/31/24, 9:21 AM [Link]
4767 <label for="mappingFunction">Mapping Function:</label>
4768 <input type="text" id="mappingFunction" placeholder="e.g., x => x * 2" />
4769 <br />
4770 <button type="button" onclick="computeAverage()">Compute Average</button>
4771 </form>
4772
4773 <div id="result"></div>
4774
4775 <script>
4776 function computeAverage() {
4777 const arrayInput = [Link]("arrayInput").[Link]();
4778 const array = arrayInput
4779 .split(",")
4780 .map((item) => parseFloat([Link]()));
4781
4782 const mappingFunctionString = document
4783 .getElementById("mappingFunction")
4784 .[Link]();
4785 const mappingFunction = new Function(
4786 "x",
4787 `return ${mappingFunctionString};`
4788 );
4789
4790 const mappedArray = [Link](mappingFunction);
4791 const sum = [Link]((acc, val) => acc + val, 0);
4792 const average = sum / [Link];
4793
4794 const resultElement = [Link]("result");
4795 [Link] = "<h2>Result:</h2>";
4796 [Link] += `<p>Mapped Array: [${[Link](
4797 ", "
4798 )}]</p>`;
4799 [Link] += `<p>Average: ${average}</p>`;
4800 }
4801 </script>
4802 <hr />
4803
4804 <h4>
4805 [Link] a JavaScript program to split values into two groups according
4806 to a predicate function, which specifies which group an element in the
4807 input collection belongs to.
4808 </h4>
4809 <form id="splitForm">
4810 <label for="arrayInput">Enter array elements separated by commas:</label>
4811 <input type="text" id="arrayInput" placeholder="e.g., 1, 2, 3" />
4812 <br />
4813 <label for="predicateFunction">Predicate Function:</label>
4814 <input
4815 type="text"
4816 id="predicateFunction"
4817 placeholder="e.g., x => x % 2 === 0"
4818 />
4819 <br />
4820 <button type="button" onclick="splitValues()">Split Values</button>
4821 </form>
4822
4823 <div id="result"></div>
4824
4825 <script>
4826 function splitValues() {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 81/298
1/31/24, 9:21 AM [Link]
4827 const arrayInput = [Link]("arrayInput").[Link]();
4828 const array = arrayInput
4829 .split(",")
4830 .map((item) => parseFloat([Link]()));
4831
4832 const predicateFunctionString = document
4833 .getElementById("predicateFunction")
4834 .[Link]();
4835 const predicateFunction = new Function(
4836 "x",
4837 `return ${predicateFunctionString};`
4838 );
4839
4840 const trueGroup = [];
4841 const falseGroup = [];
4842
4843 for (const element of array) {
4844 if (predicateFunction(element)) {
4845 [Link](element);
4846 } else {
4847 [Link](element);
4848 }
4849 }
4850
4851 const resultElement = [Link]("result");
4852 [Link] = "<h2>Result:</h2>";
4853 [Link] += `<p>True Group: [${[Link](
4854 ", "
4855 )}]</p>`;
4856 [Link] += `<p>False Group: [${[Link](
4857 ", "
4858 )}]</p>`;
4859 }
4860 </script>
4861 <hr />
4862
4863 <h4>
4864 [Link] a JavaScript program to create a function that invokes fn with a
4865 given context, optionally adding any additional supplied parameters to the
4866 beginning of the arguments.
4867 </h4>
4868 <form id="invokeForm">
4869 <label for="context">Context Object:</label>
4870 <input type="text" id="context" placeholder="e.g., window" />
4871 <br />
4872 <label for="functionName">Function Name:</label>
4873 <input type="text" id="functionName" placeholder="e.g., [Link]" />
4874 <br />
4875 <label for="additionalParams"
4876 >Additional Parameters (comma-separated):</label
4877 >
4878 <input
4879 type="text"
4880 id="additionalParams"
4881 placeholder="e.g., 'Hello', 123"
4882 />
4883 <br />
4884 <button type="button" onclick="invokeFunction()">Invoke Function</button>
4885 </form>
4886
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 82/298
1/31/24, 9:21 AM [Link]
4887 <div id="result"></div>
4888
4889 <script>
4890 function invokeFunction() {
4891 const context = [Link]("context").[Link]();
4892 const functionName = document
4893 .getElementById("functionName")
4894 .[Link]();
4895 const additionalParamsInput = document
4896 .getElementById("additionalParams")
4897 .[Link]();
4898 const additionalParams = additionalParamsInput
4899 .split(",")
4900 .map((param) => {
4901 param = [Link]();
4902 // Check if the parameter is a string or a number
4903 if (/^['"].*['"]$/.test(param)) {
4904 return [Link](1, -1); // Remove surrounding quotes for strings
4905 } else if (!isNaN(parseFloat(param))) {
4906 return parseFloat(param); // Convert to number if possible
4907 } else {
4908 return param; // Keep as is
4909 }
4910 });
4911
4912 // Retrieve the context object
4913 const contextObject = eval(context);
4914
4915 // Retrieve the function from the context object
4916 const fn = contextObject[functionName];
4917
4918 // Invoke the function with the context and additional parameters
4919 const result = [Link](contextObject, additionalParams);
4920
4921 const resultElement = [Link]("result");
4922 [Link] = "<h2>Result:</h2>";
4923 [Link] += `<p>${result}</p>`;
4924 }
4925 </script>
4926 <hr />
4927
4928 <h4>
4929 [Link] a JavaScript program to create a function that invokes the
4930 method at a given key of an object, optionally adding any additional
4931 supplied parameters to the beginning of the arguments.
4932 </h4>
4933 <form id="invokeMethodForm">
4934 <label for="object">Object:</label>
4935 <input type="text" id="object" placeholder="e.g., window" />
4936 <br />
4937 <label for="methodKey">Method Key:</label>
4938 <input type="text" id="methodKey" placeholder="e.g., alert" />
4939 <br />
4940 <label for="additionalParams"
4941 >Additional Parameters (comma-separated):</label
4942 >
4943 <input
4944 type="text"
4945 id="additionalParams"
4946 placeholder="e.g., 'Hello', 123"
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 83/298
1/31/24, 9:21 AM [Link]
4947 />
4948 <br />
4949 <button type="button" onclick="invokeMethod()">Invoke Method</button>
4950 </form>
4951
4952 <div id="result"></div>
4953
4954 <script>
4955 function invokeMethod() {
4956 const object = [Link]("object").[Link]();
4957 const methodKey = [Link]("methodKey").[Link]();
4958 const additionalParamsInput = document
4959 .getElementById("additionalParams")
4960 .[Link]();
4961 const additionalParams = additionalParamsInput
4962 .split(",")
4963 .map((param) => {
4964 param = [Link]();
4965 // Check if the parameter is a string or a number
4966 if (/^['"].*['"]$/.test(param)) {
4967 return [Link](1, -1); // Remove surrounding quotes for strings
4968 } else if (!isNaN(parseFloat(param))) {
4969 return parseFloat(param); // Convert to number if possible
4970 } else {
4971 return param; // Keep as is
4972 }
4973 });
4974
4975 // Retrieve the object
4976 const obj = eval(object);
4977
4978 // Retrieve the method from the object
4979 const method = obj[methodKey];
4980
4981 // Invoke the method with additional parameters
4982 const result = [Link](obj, additionalParams);
4983
4984 const resultElement = [Link]("result");
4985 [Link] = "<h2>Result:</h2>";
4986 [Link] += `<p>${result}</p>`;
4987 }
4988 </script>
4989 <hr />
4990
4991 <h4>
4992 [Link] a JavaScript program to cast the provided value as an array if
4993 it's not one.
4994 </h4>
4995 <form id="castValueForm">
4996 <label for="value">Value:</label>
4997 <input type="text" id="value" placeholder="Enter a value" />
4998 <button type="button" onclick="castValue()">Cast to Array</button>
4999 </form>
5000
5001 <div id="result"></div>
5002
5003 <script>
5004 function castValue() {
5005 const value = [Link]("value").[Link]();
5006 let result;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 84/298
1/31/24, 9:21 AM [Link]
5007
5008 // Check if the value is already an array
5009 if ([Link](value)) {
5010 result = value;
5011 } else {
5012 // If not an array, cast it to an array
5013 result = [value];
5014 }
5015
5016 const resultElement = [Link]("result");
5017 [Link] = "<h2>Result:</h2>";
5018 [Link] += `<p>${[Link](result)}</p>`;
5019 }
5020 </script>
5021 <hr />
5022
5023 <h4>[Link] a JavaScript program to chain asynchronous functions</h4>
5024 <h1>Asynchronous Function Chaining</h1>
5025
5026 <script>
5027 function asyncFunction1() {
5028 return new Promise((resolve) => {
5029 setTimeout(() => {
5030 [Link]("Async function 1");
5031 resolve();
5032 }, 1000);
5033 });
5034 }
5035
5036 function asyncFunction2() {
5037 return new Promise((resolve) => {
5038 setTimeout(() => {
5039 [Link]("Async function 2");
5040 resolve();
5041 }, 1000);
5042 });
5043 }
5044
5045 function asyncFunction3() {
5046 return new Promise((resolve) => {
5047 setTimeout(() => {
5048 [Link]("Async function 3");
5049 resolve();
5050 }, 1000);
5051 });
5052 }
5053
5054 async function chainAsyncFunctions() {
5055 await asyncFunction1();
5056 await asyncFunction2();
5057 await asyncFunction3();
5058 }
5059
5060 // Call the function to chain asynchronous functions
5061 chainAsyncFunctions();
5062 </script>
5063 <hr />
5064
5065 <h4>[Link] a JavaScript program to clone a given regular expression.</h4>
5066 <script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 85/298
1/31/24, 9:21 AM [Link]
5067 function cloneRegExp(regExp) {
5068 // Extract the pattern and flags from the original RegExp
5069 const pattern = [Link];
5070 const flags = [Link];
5071
5072 // Create a new RegExp object with the same pattern and flags
5073 return new RegExp(pattern, flags);
5074 }
5075
5076 // Example usage:
5077 const originalRegExp = /[a-z]+/gi;
5078 const clonedRegExp = cloneRegExp(originalRegExp);
5079
5080 [Link]("Original RegExp:", originalRegExp);
5081 [Link]("Cloned RegExp:", clonedRegExp);
5082 </script>
5083 <hr />
5084
5085 <h4>
5086 [Link] a JavaScript program to get the first non-null / undefined
5087 argument.
5088 </h4>
5089 <h1>Get First Non-Null/Undefined Argument</h1>
5090
5091 <script>
5092 function getFirstNonNullUndefined(...args) {
5093 return [Link]((arg) => arg !== null && arg !== undefined);
5094 }
5095
5096 // Example usage:
5097 const firstArg = getFirstNonNullUndefined(
5098 null,
5099 undefined,
5100 5,
5101 "Hello",
5102 true
5103 );
5104 [Link]("First non-null/undefined argument:", firstArg);
5105 </script>
5106 <hr />
5107
5108 <h4>
5109 [Link] a JavaScript program to add special characters to text to print
5110 in color in the console (combined with [Link]()).
5111 </h4>
5112 <script>
5113 // Function to print colored text in the console
5114 function printColoredText(text, color) {
5115 const colors = {
5116 black: "\x1b[30m",
5117 red: "\x1b[31m",
5118 green: "\x1b[32m",
5119 yellow: "\x1b[33m",
5120 blue: "\x1b[34m",
5121 magenta: "\x1b[35m",
5122 cyan: "\x1b[36m",
5123 white: "\x1b[37m",
5124 reset: "\x1b[0m", // Reset color to default
5125 };
5126
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 86/298
1/31/24, 9:21 AM [Link]
5127 // Check if the specified color exists in the colors object
5128 const colorCode = colors[color] || [Link]; // Default to white if color is
not found
5129
5130 // Print the colored text to the console
5131 [Link](`${colorCode}${text}${[Link]}`);
5132 }
5133
5134 // Example usage:
5135 printColoredText("This is red text", "red");
5136 printColoredText("This is blue text", "blue");
5137 printColoredText("This is green text", "green");
5138 printColoredText("This is yellow text", "yellow");
5139 printColoredText("This is magenta text", "magenta");
5140 </script>
5141 <hr />
5142
5143 <h4>
5144 [Link] a JavaScript program to perform right-to-left function
5145 composition.
5146 </h4>
5147 <script>
5148 // Function to perform right-to-left function composition
5149 function compose(...functions) {
5150 return function (arg) {
5151 return [Link]((result, fn) => fn(result), arg);
5152 };
5153 }
5154
5155 // Example functions
5156 function add2(x) {
5157 return x + 2;
5158 }
5159
5160 function multiply3(x) {
5161 return x * 3;
5162 }
5163
5164 function subtract5(x) {
5165 return x - 5;
5166 }
5167
5168 // Example of composing functions
5169 const composedFunction = compose(subtract5, multiply3, add2);
5170
5171 // Example usage
5172 const result = composedFunction(10);
5173 [Link]("Result of composing functions:", result); // Output: ((10 + 2) * 3) -
5 = 31
5174 </script>
5175 <hr />
5176
5177 <h4>
5178 [Link] a JavaScript program to perform left-to-right function
5179 composition
5180 </h4>
5181 <script>
5182 // Function to perform left-to-right function composition
5183 function compose(...functions) {
5184 return function (arg) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 87/298
1/31/24, 9:21 AM [Link]
5185 return [Link]((result, fn) => fn(result), arg);
5186 };
5187 }
5188
5189 // Example functions
5190 function add2(x) {
5191 return x + 2;
5192 }
5193
5194 function multiply3(x) {
5195 return x * 3;
5196 }
5197
5198 function subtract5(x) {
5199 return x - 5;
5200 }
5201
5202 // Example of composing functions
5203 const composedFunction = compose(add2, multiply3, subtract5);
5204
5205 // Example usage
5206 const result = composedFunction(10);
5207 [Link]("Result of composing functions:", result); // Output: ((10 - 5) * 3) +
2 = 29
5208 </script>
5209 <hr />
5210
5211 <h4>
5212 [Link] a JavaScript program that accepts a converging function and a
5213 list of branching functions and returns a function that applies each
5214 branching function to the arguments and the results of the branching
5215 functions are passed as arguments to the converging function.
5216 </h4>
5217 <script>
5218 // Function to perform left-to-right function composition
5219 function compose(...functions) {
5220 return function (arg) {
5221 return [Link]((result, fn) => fn(result), arg);
5222 };
5223 }
5224
5225 // Example functions
5226 function add2(x) {
5227 return x + 2;
5228 }
5229
5230 function multiply3(x) {
5231 return x * 3;
5232 }
5233
5234 function subtract5(x) {
5235 return x - 5;
5236 }
5237
5238 // Example of composing functions
5239 const composedFunction = compose(add2, multiply3, subtract5);
5240
5241 // Example usage
5242 const result = composedFunction(10);
5243 [Link]("Result of composing functions:", result); // Output: ((10 - 5) * 3) +
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 88/298
1/31/24, 9:21 AM [Link]
2 = 29
5244 </script>
5245 <hr />
5246
5247 <h4>
5248 [Link] a JavaScript program to group the elements of an array based on
5249 the given function and returns the count of elements in each group
5250 </h4>
5251 <script>
5252 // Function to group elements of an array based on a given function
5253 function groupBy(arr, func) {
5254 const groups = {};
5255
5256 [Link]((element) => {
5257 const key = func(element);
5258 groups[key] = groups[key] ? groups[key] + 1 : 1;
5259 });
5260
5261 return groups;
5262 }
5263
5264 // Example array
5265 const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
5266
5267 // Example grouping function (grouping by even and odd numbers)
5268 function groupFunc(num) {
5269 return num % 2 === 0 ? "Even" : "Odd";
5270 }
5271
5272 // Group the elements of the array based on the grouping function
5273 const groupedCounts = groupBy(numbers, groupFunc);
5274
5275 // Output the result
5276 [Link]("Grouped Counts:", groupedCounts);
5277 </script>
5278 <hr />
5279
5280 <h4>
5281 [Link] a JavaScript program to count the occurrences of a value in an
5282 array
5283 </h4>
5284 <script>
5285 // Function to count occurrences of a value in an array
5286 function countOccurrences(arr, value) {
5287 let count = 0;
5288 for (let i = 0; i < [Link]; i++) {
5289 if (arr[i] === value) {
5290 count++;
5291 }
5292 }
5293 return count;
5294 }
5295
5296 // Example array
5297 const numbers = [1, 2, 3, 4, 5, 2, 2, 3, 4, 2];
5298
5299 // Value to count occurrences
5300 const valueToCount = 2;
5301
5302 // Count occurrences of the value in the array
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 89/298
1/31/24, 9:21 AM [Link]
5303 const occurrences = countOccurrences(numbers, valueToCount);
5304
5305 // Output the result
5306 [Link](`Occurrences of ${valueToCount}: ${occurrences}`);
5307 </script>
5308 <hr />
5309
5310 <h4>[Link] a JavaScript program to create a deep clone of an object.</h4>
5311 <h1>Deep Clone of an Object</h1>
5312
5313 <script>
5314 // Function to deep clone an object
5315 function deepClone(obj) {
5316 if (obj === null || typeof obj !== "object") {
5317 return obj;
5318 }
5319
5320 let clone = [Link](obj) ? [] : {};
5321
5322 for (let key in obj) {
5323 if ([Link](key)) {
5324 clone[key] = deepClone(obj[key]);
5325 }
5326 }
5327
5328 return clone;
5329 }
5330
5331 // Example object to clone
5332 const originalObject = {
5333 name: "John",
5334 age: 30,
5335 address: {
5336 city: "New York",
5337 country: "USA",
5338 },
5339 hobbies: ["Reading", "Traveling"],
5340 };
5341
5342 // Deep clone the object
5343 const clonedObject = deepClone(originalObject);
5344
5345 // Modify the cloned object to verify deep cloning
5346 [Link] = "Jane";
5347 [Link] = "Los Angeles";
5348 [Link]("Cooking");
5349
5350 // Output the original and cloned objects
5351 [Link]("Original Object:", originalObject);
5352 [Link]("Cloned Object:", clonedObject);
5353 </script>
5354 <hr />
5355
5356 <h4>
5357 [Link] a JavaScript program to detect whether the website is being
5358 opened in a mobile device or a desktop/laptop.
5359 </h4>
5360 <script>
5361 // Function to detect the device type
5362 function detectDevice() {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 90/298
1/31/24, 9:21 AM [Link]
5363 const userAgent = [Link]();
5364 const mobileKeywords = [
5365 "mobile",
5366 "iphone",
5367 "ipad",
5368 "android",
5369 "blackberry",
5370 "windows phone",
5371 ];
5372
5373 for (let keyword of mobileKeywords) {
5374 if ([Link](keyword) !== -1) {
5375 return "Mobile Device";
5376 }
5377 }
5378
5379 return "Desktop/Laptop";
5380 }
5381
5382 // Check the device type and display the result
5383 const deviceType = detectDevice();
5384 [Link]("Device Type:", deviceType);
5385 alert("Device Type: " + deviceType);
5386 </script>
5387 <hr />
5388
5389 <h4>
5390 [Link] a JavaScript program to return the difference between two
5391 arrays, after applying the provided function to each array element of
5392 both.
5393 </h4>
5394 <script>
5395 // Function to return the difference between two arrays after applying the
provided function to each element
5396 function differenceWith(arr1, arr2, func) {
5397 const mappedArr1 = [Link](func);
5398 const mappedArr2 = [Link](func);
5399
5400 return [Link]((item) => );
5401 }
5402
5403 // Example function to be applied to array elements
5404 function square(x) {
5405 return x * x;
5406 }
5407
5408 // Example arrays
5409 const array1 = [1, 2, 3, 4, 5];
5410 const array2 = [2, 3, 4, 5, 6];
5411
5412 // Calculate the difference between the arrays after squaring each element
5413 const result = differenceWith(array1, array2, square);
5414
5415 // Output the result
5416 [Link]("Difference after applying square function:", result);
5417 </script>
5418 <hr />
5419
5420 <h4>
5421 [Link] a JavaScript program to filter out all values from an array for
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 91/298
1/31/24, 9:21 AM [Link]
5422 which the comparator function does not return true.
5423 </h4>
5424
5425 <script>
5426 // Function to filter out values from an array based on a comparator function
5427 function filterWithComparator(array, comparator) {
5428 return [Link](comparator);
5429 }
5430
5431 // Example comparator function
5432 function isEven(value) {
5433 return value % 2 === 0;
5434 }
5435
5436 // Example array
5437 const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
5438
5439 // Filter out values from the array where the comparator function returns true
5440 const filteredArray = filterWithComparator(array, isEven);
5441
5442 // Output the filtered array
5443 [Link]("Filtered Array:", filteredArray);
5444 </script>
5445 <hr />
5446
5447 <h4>
5448 [Link] a JavaScript program to compute the new ratings between two or
5449 more opponents using the Elo rating system. It takes an array of
5450 pre-ratings and returns an array containing post-ratings. The array should
5451 be ordered from best performer to worst performer (winner -> loser).
5452 </h4>
5453 <script>
5454 // Function to compute the new ratings using the Elo rating system
5455 function computeEloRatings(preRatings, kFactor, scores) {
5456 const postRatings = [];
5457
5458 // Loop through each player
5459 for (let i = 0; i < [Link]; i++) {
5460 const ratingDifference = scores[i] - expectedScore(preRatings, i);
5461 const newRating = preRatings[i] + kFactor * ratingDifference;
5462 [Link](newRating);
5463 }
5464
5465 return postRatings;
5466 }
5467
5468 // Function to calculate the expected score of a player
5469 function expectedScore(ratings, index) {
5470 const myRating = ratings[index];
5471 let totalSum = 0;
5472
5473 for (let i = 0; i < [Link]; i++) {
5474 if (i !== index) {
5475 totalSum += 1 / (1 + [Link](10, (ratings[i] - myRating) / 400));
5476 }
5477 }
5478
5479 return totalSum;
5480 }
5481
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 92/298
1/31/24, 9:21 AM [Link]
5482 // Example input data
5483 const preRatings = [1200, 1400, 1600];
5484 const kFactor = 32; // K-Factor is a parameter in the Elo rating system
5485 const scores = [1, 0.5, 0]; // Example scores where 1 represents a win, 0.5
represents a draw, and 0 represents a loss
5486
5487 // Compute new ratings using the Elo rating system
5488 const postRatings = computeEloRatings(preRatings, kFactor, scores);
5489
5490 // Output the new ratings
5491 [Link]("Pre-Ratings:", preRatings);
5492 [Link]("Post-Ratings:", postRatings);
5493 </script>
5494 <hr />
5495
5496 <h4>
5497 [Link] a JavaScript program to execute a provided function once for
5498 each array element, starting from the array's last element.
5499 </h4>
5500 <script>
5501 // Function to execute a provided function once for each array element, starting
from the array's last element
5502 function executeFunctionForArrayFromLast(array, callback) {
5503 for (let i = [Link] - 1; i >= 0; i--) {
5504 callback(array[i], i, array);
5505 }
5506 }
5507
5508 // Example function to be executed for each array element
5509 function processElement(element, index) {
5510 [Link](`Element at index ${index}: ${element}`);
5511 }
5512
5513 // Example array
5514 const array = [1, 2, 3, 4, 5];
5515
5516 // Execute the function for each array element, starting from the last element
5517 executeFunctionForArrayFromLast(array, processElement);
5518 </script>
5519
5520 <h4>
5521 [Link] a JavaScript program to iterate over all own properties of an
5522 object, running a callback for each one.
5523 </h4>
5524 <script>
5525 // Function to iterate over all own properties of an object and run a callback for
each one
5526 function iterateOverObjectProperties(obj, callback) {
5527 for (let prop in obj) {
5528 if ([Link](prop)) {
5529 callback(prop, obj[prop]);
5530 }
5531 }
5532 }
5533
5534 // Example object
5535 const person = {
5536 name: "John",
5537 age: 30,
5538 city: "New York",
5539 };
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 93/298
1/31/24, 9:21 AM [Link]
5540
5541 // Callback function to be executed for each property
5542 function processProperty(property, value) {
5543 [Link](`${property}: ${value}`);
5544 }
5545
5546 // Iterate over object properties and execute the callback function for each one
5547 iterateOverObjectProperties(person, processProperty);
5548 </script>
5549 <hr />
5550
5551 <h4>
5552 [Link] a JavaScript program to invert the key-value pairs of an object,
5553 without mutating it. The corresponding inverted value of each inverted key
5554 is an array of keys responsible for generating the inverted value. If a
5555 function is supplied, it is applied to each inverted key.
5556 </h4>
5557 <script>
5558 // Function to invert the key-value pairs of an object
5559 function invertObject(obj, fn) {
5560 const invertedObj = {};
5561
5562 for (let key in obj) {
5563 const value = obj[key];
5564 const invertedKey = typeof fn === "function" ? fn(key) : key;
5565
5566 if (!(invertedKey in invertedObj)) {
5567 invertedObj[invertedKey] = [];
5568 }
5569
5570 invertedObj[invertedKey].push(value);
5571 }
5572
5573 return invertedObj;
5574 }
5575
5576 // Example object
5577 const obj = {
5578 a: 1,
5579 b: 2,
5580 c: 1,
5581 d: 3,
5582 };
5583
5584 // Function to apply to each inverted key (optional)
5585 function capitalizeKey(key) {
5586 return [Link]();
5587 }
5588
5589 // Invert the key-value pairs of the object
5590 const invertedObject = invertObject(obj, capitalizeKey);
5591 [Link](invertedObject);
5592 </script>
5593 <hr />
5594
5595 <h4>
5596 [Link] a JavaScript program to take any number of iterable objects or
5597 objects with a length property and returns the longest one.
5598 </h4>
5599 <script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 94/298
1/31/24, 9:21 AM [Link]
5600 // Function to find the longest iterable object or object with a length property
5601 function findLongest(...args) {
5602 let longest = null;
5603
5604 for (let arg of args) {
5605 if (!longest || [Link] > [Link]) {
5606 longest = arg;
5607 }
5608 }
5609
5610 return longest;
5611 }
5612
5613 // Example iterable objects
5614 const arr1 = [1, 2, 3];
5615 const arr2 = ["a", "b", "c", "d"];
5616 const str = "Hello, world!";
5617 const set = new Set([1, 2, 3, 4]);
5618 const map = new Map([
5619 ["a", 1],
5620 ["b", 2],
5621 ["c", 3],
5622 ]);
5623
5624 // Find the longest iterable object
5625 const longestObject = findLongest(arr1, arr2, str, set, map);
5626 [Link](longestObject);
5627 </script>
5628 <hr />
5629
5630 <h4>
5631 [Link] a JavaScript program to implement the Luhn Algorithm used to
5632 validate a variety of identification numbers, such as credit card numbers,
5633 IMEI numbers, National Provider Identifier numbers etc
5634 </h4>
5635 <script>
5636 // Function to validate a number using the Luhn algorithm
5637 function luhnCheck(number) {
5638 // Convert the number to a string and remove any non-digit characters
5639 const str = String(number).replace(/\D/g, "");
5640
5641 // Convert the string to an array of digits and reverse it
5642 const digits = [Link]("").map(Number).reverse();
5643
5644 // Initialize variables
5645 let sum = 0;
5646 let double = false;
5647
5648 // Iterate over the digits, starting from the rightmost digit
5649 for (let digit of digits) {
5650 if (double) {
5651 // Double every second digit
5652 digit *= 2;
5653 if (digit > 9) {
5654 digit -= 9;
5655 }
5656 }
5657 // Add the digit to the sum
5658 sum += digit;
5659 // Toggle the flag to double the next digit
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 95/298
1/31/24, 9:21 AM [Link]
5660 double = !double;
5661 }
5662
5663 // The number is valid if the sum is divisible by 10
5664 return sum % 10 === 0;
5665 }
5666
5667 // Test credit card numbers
5668 const creditCardNumbers = [
5669 "4539677908016808", // Valid Visa card number
5670 "4539677908016809", // Invalid Visa card number
5671 "6011313653323954", // Valid Discover card number
5672 "6011313653323955", // Invalid Discover card number
5673 ];
5674
5675 // Validate each credit card number
5676 [Link]((number) => {
5677 const isValid = luhnCheck(number);
5678 [Link](`${number} is ${isValid ? "valid" : "invalid"}`);
5679 });
5680 </script>
5681 <hr />
5682
5683 <h4>
5684 [Link] a JavaScript program to create an object with keys generated by
5685 running the provided function for each key and the same values as the
5686 provided object
5687 </h4>
5688 <script>
5689 // Function to create an object with keys generated by a function
5690 function createObjectWithGeneratedKeys(obj, keyFn) {
5691 const result = {};
5692 // Iterate over the keys of the provided object
5693 for (let key in obj) {
5694 // Generate a new key using the provided function
5695 const newKey = keyFn(key);
5696 // Assign the value of the original key to the new key in the result object
5697 result[newKey] = obj[key];
5698 }
5699 return result;
5700 }
5701
5702 // Example object
5703 const originalObject = {
5704 a: 1,
5705 b: 2,
5706 c: 3,
5707 };
5708
5709 // Function to generate new keys (adding 'new_' prefix to each key)
5710 function generateNewKey(key) {
5711 return "new_" + key;
5712 }
5713
5714 // Create a new object with keys generated by the function
5715 const newObj = createObjectWithGeneratedKeys(
5716 originalObject,
5717 generateNewKey
5718 );
5719 [Link](newObj); // Output the new object
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 96/298
1/31/24, 9:21 AM [Link]
5720 </script>
5721 <hr />
5722
5723 <h4>
5724 [Link] a JavaScript program to map the values of an array to an object
5725 using a function, where the key -value pairs consist of the original value
5726 as the key and the mapped value
5727 </h4>
5728 <script>
5729 // Function to map array values to an object using a provided mapping function
5730 function mapArrayValuesToObject(arr, mapFn) {
5731 const result = {};
5732 // Iterate over the array
5733 [Link]((value) => {
5734 // Map the value using the provided function
5735 result[value] = mapFn(value);
5736 });
5737 return result;
5738 }
5739
5740 // Example array
5741 const originalArray = [1, 2, 3, 4, 5];
5742
5743 // Function to map each value to its square
5744 function mapToSquare(value) {
5745 return value * value;
5746 }
5747
5748 // Map array values to an object using the mapping function
5749 const mappedObject = mapArrayValuesToObject(originalArray, mapToSquare);
5750 [Link](mappedObject); // Output the mapped object
5751 </script>
5752 <hr />
5753
5754 <h4>
5755 [Link] a JavaScript program to create a new string with the results of
5756 calling a provided function on every character in the calling string.
5757 </h4>
5758 <script>
5759 // Function to map a function to each character in a string
5760 [Link] = function (mapFn) {
5761 // Convert the string to an array of characters, map the function, and join the
result back into a string
5762 return [Link](this, mapFn).join("");
5763 };
5764
5765 // Example function to convert each character to its uppercase equivalent
5766 function toUpperCase(char) {
5767 return [Link]();
5768 }
5769
5770 // Example string
5771 const originalString = "hello world";
5772
5773 // Map the toUpperCase function to each character in the string
5774 const mappedString = [Link](toUpperCase);
5775 [Link](mappedString); // Output the mapped string
5776 </script>
5777 <hr />
5778
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 97/298
1/31/24, 9:21 AM [Link]
5779 <h4>
5780 [Link] a JavaScript program to create an object with the same keys as
5781 the provided object and values generated by running the provided function
5782 for each value.
5783 </h4>
5784 <script>
5785 // Function to create an object with values generated by a provided function
5786 function mapObjectValues(obj, mapFn) {
5787 const mappedObj = {};
5788 // Iterate over the keys of the input object
5789 for (const key in obj) {
5790 // Check if the property is not inherited from prototype
5791 if ([Link](obj, key)) {
5792 // Apply the provided function to the value and assign it to the
corresponding key in the new object
5793 mappedObj[key] = mapFn(obj[key]);
5794 }
5795 }
5796 return mappedObj;
5797 }
5798
5799 // Example function to double each value
5800 function doubleValue(value) {
5801 return value * 2;
5802 }
5803
5804 // Example object
5805 const originalObject = {
5806 a: 1,
5807 b: 2,
5808 c: 3,
5809 };
5810
5811 // Map the doubleValue function to each value in the object
5812 const mappedObject = mapObjectValues(originalObject, doubleValue);
5813 [Link](mappedObject); // Output the mapped object
5814 </script>
5815 <hr />
5816
5817 <h4>
5818 [Link] a JavaScript program to replace all but the last number of
5819 characters with the specified mask character.
5820 </h4>
5821 <script>
5822 // Function to replace characters with mask
5823 function replaceWithMask(str, maskChar, numToShow) {
5824 if (numToShow >= [Link]) {
5825 return str;
5826 }
5827 const maskLength = [Link] - numToShow;
5828 const mask = [Link](maskLength);
5829 const visibleChars = [Link](-numToShow);
5830 return mask + visibleChars;
5831 }
5832
5833 // Example usage
5834 const originalString = "1234567890";
5835 const maskedString = replaceWithMask(originalString, "*", 4);
5836 [Link](maskedString); // Output the masked string
5837 </script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 98/298
1/31/24, 9:21 AM [Link]
5838 <hr />
5839
5840 <h4>
5841 [Link] a JavaScript program to get the maximum value of an array, after
5842 mapping each element to a value using the provided function.
5843 </h4>
5844 <script>
5845 // Function to get the maximum value after mapping
5846 function getMaxAfterMapping(arr, mapFn) {
5847 // Map each element of the array using the provided function
5848 const mappedArray = [Link](mapFn);
5849 // Find the maximum value in the mapped array
5850 const max = [Link](...mappedArray);
5851 return max;
5852 }
5853
5854 // Example usage
5855 const array = [1, 2, 3, 4, 5];
5856 const mapFunction = (num) => num * 2; // Double each element
5857 const maxValue = getMaxAfterMapping(array, mapFunction);
5858 [Link]("Maximum value after mapping:", maxValue); // Output the maximum value
5859 </script>
5860 <hr />
5861
5862 <h4>
5863 [Link] a JavaScript program to get the n maximum elements from the
5864 provided array. If n is greater than or equal to the provided array's
5865 length, then return the original array(sorted in descending order).
5866 </h4>
5867 <script>
5868 // Function to get the maximum value after mapping
5869 function getMaxAfterMapping(arr, mapFn) {
5870 // Map each element of the array using the provided function
5871 const mappedArray = [Link](mapFn);
5872 // Find the maximum value in the mapped array
5873 const max = [Link](...mappedArray);
5874 return max;
5875 }
5876
5877 // Example usage
5878 const array = [1, 2, 3, 4, 5];
5879 const mapFunction = (num) => num * 2; // Double each element
5880 const maxValue = getMaxAfterMapping(array, mapFunction);
5881 [Link]("Maximum value after mapping:", maxValue); // Output the maximum value
5882 </script>
5883 <hr />
5884
5885 <h4>
5886 [Link] a JavaScript program to get the median of an array of numbers
5887 </h4>
5888 <script>
5889 // Function to get the median of an array of numbers
5890 function getMedian(arr) {
5891 // Sort the array
5892 [Link]((a, b) => a - b);
5893
5894 const length = [Link];
5895
5896 // If the array has an odd number of elements
5897 if (length % 2 !== 0) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 99/298
1/31/24, 9:21 AM [Link]
5898 return arr[[Link](length / 2)];
5899 } else {
5900 // If the array has an even number of elements
5901 const midIndex = length / 2;
5902 return (arr[midIndex - 1] + arr[midIndex]) / 2;
5903 }
5904 }
5905
5906 // Example usage
5907 const numbers = [7, 2, 1, 4, 5, 6, 3];
5908 const median = getMedian(numbers);
5909 [Link]("Median:", median);
5910 </script>
5911 <hr />
5912
5913 <h4>[Link] a JavaScript program to negates a predicate function.</h4>
5914 <script>
5915 // Function to negate a predicate function
5916 function negate(predicate) {
5917 return function () {
5918 // Call the original predicate function with arguments
5919 // Convert the result to boolean and negate it
5920 return !Boolean([Link](this, arguments));
5921 };
5922 }
5923
5924 // Predicate function example: checks if a number is even
5925 function isEven(num) {
5926 return num % 2 === 0;
5927 }
5928
5929 // Negate the isEven function
5930 const isOdd = negate(isEven);
5931
5932 // Test the negated function
5933 [Link](isOdd(5)); // Output: true (5 is odd)
5934 [Link](isOdd(6)); // Output: false (6 is not odd)
5935 </script>
5936 <hr />
5937
5938 <h4>
5939 [Link] a JavaScript program to nest a given flat array of objects
5940 linked to one another recursively.
5941 </h4>
5942 <script>
5943 // Function to nest a flat array of objects recursively
5944 function nestObjects(array, parentId = null) {
5945 const nested = [];
5946 [Link]((item) => {
5947 if ([Link] === parentId) {
5948 const children = nestObjects(array, [Link]);
5949 if ([Link]) {
5950 [Link] = children;
5951 }
5952 [Link](item);
5953 }
5954 });
5955 return nested;
5956 }
5957
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 100/298
1/31/24, 9:21 AM [Link]
5958 // Example flat array of objects
5959 const flatArray = [
5960 { id: 1, name: "Parent 1", parentId: null },
5961 { id: 2, name: "Child 1.1", parentId: 1 },
5962 { id: 3, name: "Child 1.2", parentId: 1 },
5963 { id: 4, name: "Parent 2", parentId: null },
5964 { id: 5, name: "Child 2.1", parentId: 4 },
5965 { id: 6, name: "Child 2.2", parentId: 4 },
5966 { id: 7, name: "Grandchild 2.2.1", parentId: 6 },
5967 ];
5968
5969 // Nest the flat array of objects
5970 const nestedArray = nestObjects(flatArray);
5971
5972 // Display the nested array
5973 [Link]([Link](nestedArray, null, 2));
5974 </script>
5975 <hr />
5976
5977 <h4>
5978 [Link] a JavaScript program that will return true if the provided
5979 predicate function returns false for all elements in a collection, false
5980 otherwise
5981 </h4>
5982 <script>
5983 // Function to check if the predicate function returns false for all elements
5984 function checkPredicate(collection, predicate) {
5985 for (const element of collection) {
5986 if (predicate(element)) {
5987 return false; // Return false if predicate is true for any element
5988 }
5989 }
5990 return true; // Return true if predicate is false for all elements
5991 }
5992
5993 // Example collection
5994 const collection1 = [2, 4, 6, 8, 10];
5995 const collection2 = [2, 4, 5, 8, 10];
5996
5997 // Example predicate function (returns true for even numbers)
5998 function isEven(num) {
5999 return num % 2 === 0;
6000 }
6001
6002 // Check if the predicate function returns false for all elements in the
collections
6003 const result1 = checkPredicate(collection1, isEven);
6004 const result2 = checkPredicate(collection2, isEven);
6005
6006 // Display the results
6007 [Link]("Result 1:", result1); // Should return true because all numbers are
even
6008 [Link]("Result 2:", result2); // Should return false because there's an odd
number
6009 </script>
6010 <hr />
6011
6012 <h4>
6013 [Link] a JavaScript program to create a function that gets the argument
6014 at index n. If n is negative, the nth argument from the end is returned.
6015 </h4>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 101/298
1/31/24, 9:21 AM [Link]
6016 <script>
6017 // Function to get the argument at index n
6018 function getArgumentAtIndex(n) {
6019 return function (...args) {
6020 // If n is negative, adjust index from the end
6021 const index = n < 0 ? [Link] + n : n;
6022 return args[index];
6023 };
6024 }
6025
6026 // Create functions to get the 2nd and -2nd arguments
6027 const getSecondArgument = getArgumentAtIndex(1);
6028 const getSecondFromLastArgument = getArgumentAtIndex(-2);
6029
6030 // Example function calls with arguments
6031 [Link]("First Example:");
6032 [Link](getSecondArgument("a", "b", "c", "d")); // Output: b
6033 [Link]("Second Example:");
6034 [Link](getSecondFromLastArgument("x", "y", "z")); // Output: y
6035 </script>
6036 <hr />
6037
6038 <h4>
6039 [Link] a JavaScript program to remove an event listener from an
6040 element.
6041 </h4>
6042
6043 <button id="myButton">Click me</button>
6044
6045 <script>
6046 // Function to handle the click event
6047 function handleClick() {
6048 [Link]("Button clicked!");
6049 }
6050
6051 // Get the button element
6052 const button = [Link]("myButton");
6053
6054 // Add click event listener
6055 [Link]("click", handleClick);
6056
6057 // Function to remove event listener
6058 function removeClickListener() {
6059 // Remove click event listener
6060 [Link]("click", handleClick);
6061 [Link]("Click event listener removed!");
6062 }
6063
6064 // Call the function to remove event listener after 5 seconds
6065 setTimeout(removeClickListener, 5000);
6066 </script>
6067 <hr />
6068
6069 <h4>
6070 [Link] a JavaScript program to move the specified amount of elements to
6071 the end of the array
6072 </h4>
6073 <script>
6074 function moveElementsToEnd(arr, count) {
6075 // Check if count is valid
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 102/298
1/31/24, 9:21 AM [Link]
6076 if (count <= 0 || count >= [Link]) {
6077 [Link]("Invalid count value");
6078 return arr; // No need to move elements
6079 }
6080
6081 // Remove the specified number of elements from the beginning of the array
6082 const elementsToMove = [Link](0, count);
6083
6084 // Add the removed elements to the end of the array
6085 [Link](...elementsToMove);
6086
6087 return arr;
6088 }
6089
6090 // Example usage:
6091 const array = [1, 2, 3, 4, 5];
6092 const count = 2;
6093 const result = moveElementsToEnd(array, count);
6094 [Link](result); // Output: [3, 4, 5, 1, 2]
6095 </script>
6096 <hr />
6097
6098 <h4>
6099 [Link] a JavaScript program to add an event listener to an element with
6100 the ability to use event delegation.
6101 </h4>
6102 <script>
6103 // Function to handle the event
6104 function handleClick(event) {
6105 // Check if the event target matches the desired child element
6106 if ([Link](".child-element")) {
6107 // Perform actions specific to the child element
6108 [Link]("Child element clicked:", [Link]);
6109 }
6110 }
6111
6112 // Add event listener to a parent element
6113 const parentElement = [Link]("parent-element");
6114 [Link]("click", handleClick);
6115 </script>
6116 <hr />
6117
6118 <h4>
6119 [Link] a JavaScript program to pick the key-value pairs corresponding
6120 to the given keys from an object
6121 </h4>
6122 <script>
6123 function pick(obj, keys) {
6124 return [Link]((acc, key) => {
6125 if ([Link](key)) {
6126 acc[key] = obj[key];
6127 }
6128 return acc;
6129 }, {});
6130 }
6131
6132 // Example usage:
6133 const sampleObject = {
6134 a: 1,
6135 b: 2,
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 103/298
1/31/24, 9:21 AM [Link]
6136 c: 3,
6137 d: 4,
6138 };
6139 const keysToPick = ["a", "c"];
6140
6141 const pickedPairs = pick(sampleObject, keysToPick);
6142 [Link](pickedPairs); // Output: { a: 1, c: 3 }
6143 </script>
6144 <hr />
6145
6146 <h4>
6147 [Link] a JavaScript program to create an object composed of the
6148 properties the given function returns truthy for. The function is invoked
6149 with two arguments: (value, key).
6150 </h4>
6151 <script>
6152 function pickBy(obj, fn) {
6153 return [Link](
6154 [Link](obj).filter(([key, value]) => fn(value, key))
6155 );
6156 }
6157
6158 // Example usage:
6159 const sampleObject = {
6160 a: 1,
6161 b: 2,
6162 c: 3,
6163 d: 4,
6164 };
6165
6166 // Function to check if the value is even
6167 function isEven(value) {
6168 return value % 2 === 0;
6169 }
6170
6171 const pickedByFunction = pickBy(sampleObject, isEven);
6172 [Link](pickedByFunction); // Output: { b: 2, d: 4 }
6173 </script>
6174 <hr />
6175
6176 <h4>
6177 [Link] a JavaScript program to filter an array of objects based on a
6178 condition while also filtering out unspecified keys.
6179 </h4>
6180 <script>
6181 function filterObjectsByCondition(array, condition, keys) {
6182 return [Link]((obj) =>
6183 [Link](
6184 [Link](obj).filter(
6185 ([key, value]) => [Link](key) && condition(value, key)
6186 )
6187 )
6188 );
6189 }
6190
6191 // Example usage:
6192 const data = [
6193 { name: "John", age: 30, gender: "male" },
6194 { name: "Alice", age: 25, gender: "female" },
6195 { name: "Bob", age: 40, gender: "male" },
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 104/298
1/31/24, 9:21 AM [Link]
6196 ];
6197
6198 // Filter objects where age is greater than 25 and only include name and age keys
6199 const filteredData = filterObjectsByCondition(
6200 data,
6201 (value, key) => (key === "age" ? value > 25 : true),
6202 ["name", "age"]
6203 );
6204 [Link](filteredData);
6205 </script>
6206 <hr />
6207
6208 <h4>
6209 [Link] a JavaScript program to hash a given input string into a whole
6210 number.
6211 </h4>
6212 <script>
6213 function djb2Hash(input) {
6214 let hash = 5381;
6215 for (let i = 0; i < [Link]; i++) {
6216 hash = (hash * 33) ^ [Link](i);
6217 }
6218 return hash >>> 0; // Ensure the result is a positive integer
6219 }
6220
6221 // Example usage:
6222 const inputString = "hello";
6223 const hashedValue = djb2Hash(inputString);
6224 [Link]("Hashed value:", hashedValue);
6225 </script>
6226 <hr />
6227
6228 <h4>
6229 [Link] a JavaScript program to create an array of elements, grouped
6230 based on the position in the original arrays and using function as the
6231 last value to specify how grouped values should be combined
6232 </h4>
6233 <script>
6234 function zipWith(arrays, combiner) {
6235 return arrays[0].map((_, index) =>
6236 combiner(...[Link]((array) => array[index]))
6237 );
6238 }
6239
6240 // Example usage:
6241 const array1 = [1, 2, 3];
6242 const array2 = [4, 5, 6];
6243 const array3 = [7, 8, 9];
6244
6245 const combinedArray = zipWith([array1, array2, array3], (...values) =>
6246 [Link]((acc, curr) => acc + curr, 0)
6247 );
6248 [Link](combinedArray); // Output: [12, 15, 18]
6249 </script>
6250 <hr />
6251
6252 <h4>
6253 [Link] a JavaScript program to return the object associating the
6254 properties to the values of a given array of valid property identifiers
6255 and an array of values
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 105/298
1/31/24, 9:21 AM [Link]
6256 </h4>
6257 <script>
6258 function zipObject(props, values) {
6259 return [Link]((obj, prop, index) => {
6260 obj[prop] = values[index];
6261 return obj;
6262 }, {});
6263 }
6264
6265 // Example usage:
6266 const properties = ["name", "age", "country"];
6267 const values = ["John", 30, "USA"];
6268
6269 const resultObject = zipObject(properties, values);
6270 [Link](resultObject); // Output: { name: 'John', age: 30, country: 'USA' }
6271 </script>
6272 <hr />
6273
6274 <h4>
6275 [Link] a JavaScript program to create an array of elements, grouped
6276 based on the position in the original arrays.
6277 </h4>
6278 <script>
6279 function zipArrays(...arrays) {
6280 const maxLength = [Link](...[Link]((arr) => [Link]));
6281 const result = [];
6282 for (let i = 0; i < maxLength; i++) {
6283 [Link]([Link]((arr) => arr[i]));
6284 }
6285 return result;
6286 }
6287
6288 // Example usage:
6289 const array1 = [1, 2, 3];
6290 const array2 = ["a", "b", "c"];
6291 const array3 = [true, false, true];
6292
6293 const groupedArray = zipArrays(array1, array2, array3);
6294 [Link](groupedArray);
6295 </script>
6296 <hr />
6297
6298 <h4>
6299 [Link] a JavaScript program to convert a given string into an array of
6300 words.
6301 </h4>
6302 <script>
6303 function stringToArrayOfWords(str) {
6304 // Using split() to split the string into an array of words
6305 return [Link](/\s+/);
6306 }
6307
6308 // Example usage:
6309 const sentence = "Hello world! This is a test.";
6310 const wordsArray = stringToArrayOfWords(sentence);
6311 [Link](wordsArray);
6312 </script>
6313 <hr />
6314
6315 <h4>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 106/298
1/31/24, 9:21 AM [Link]
6316 [Link] a JavaScript program to test a value, x, against a predicate
6317 function. If true, return fn(x). Else, return x.
6318 </h4>
6319 <script>
6320 function testValueWithPredicate(x, predicate, fn) {
6321 // Check if the predicate function returns true for the value x
6322 if (predicate(x)) {
6323 // If true, apply the provided function fn to x and return the result
6324 return fn(x);
6325 } else {
6326 // If false, return the original value x
6327 return x;
6328 }
6329 }
6330
6331 // Example usage:
6332 const value = 10;
6333
6334 // Define a predicate function to check if a number is even
6335 const isEven = (num) => num % 2 === 0;
6336
6337 // Define a function to double a number
6338 const double = (num) => num * 2;
6339
6340 // Test the value against the predicate function and apply the function if true
6341 const result = testValueWithPredicate(value, isEven, double);
6342
6343 [Link](result); // Output: 20 (since 10 is even, it is doubled)
6344 </script>
6345 <hr />
6346
6347 <h4>
6348 [Link] a JavaScript program that return true if the given value is a
6349 number, false otherwise.
6350 </h4>
6351 <script>
6352 function isNumber(value) {
6353 return typeof value === "number" && !isNaN(value);
6354 }
6355
6356 // Example usage:
6357 [Link](isNumber(5)); // Output: true
6358 [Link](isNumber("5")); // Output: false
6359 [Link](isNumber("five")); // Output: false
6360 </script>
6361 <hr />
6362
6363 <h4>
6364 [Link] a JavaScript program to create an array of elements, ungrouping
6365 the elements in an array produced by zip and applying the provided
6366 function.
6367 </h4>
6368 <script>
6369 // Define the zip function
6370 function zip(...arrays) {
6371 const length = [Link](...[Link]((arr) => [Link]));
6372 return [Link]({ length }, (_, i) => [Link]((arr) => arr[i]));
6373 }
6374
6375 // Define the unzip function
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 107/298
1/31/24, 9:21 AM [Link]
6376 function unzip(arr, fn) {
6377 return [Link]((acc, tuple) => {
6378 [Link](fn(...tuple));
6379 return acc;
6380 }, []);
6381 }
6382
6383 // Example usage
6384 const zippedArray = zip([1, 2, 3], ["a", "b", "c"], [true, false, true]);
6385 [Link]("Zipped Array:", zippedArray);
6386
6387 const unzippedArray = unzip(
6388 zippedArray,
6389 (num, str, bool) => `${num}-${str}-${bool}`
6390 );
6391 [Link]("Unzipped Array:", unzippedArray);
6392 </script>
6393 <hr />
6394
6395 <h4>
6396 [Link] a JavaScript program to get all unique values (form the right
6397 side of the array) of an array, based on a provided comparator function.
6398 </h4>
6399 <script>
6400 function getUniqueValuesFromRight(arr, comparator) {
6401 const uniqueValues = new Set();
6402 for (let i = [Link] - 1; i >= 0; i--) {
6403 const currentValue = arr[i];
6404 let isUnique = true;
6405 for (const value of uniqueValues) {
6406 if (comparator(currentValue, value)) {
6407 isUnique = false;
6408 break;
6409 }
6410 }
6411 if (isUnique) {
6412 [Link](currentValue);
6413 }
6414 }
6415 return [Link](uniqueValues);
6416 }
6417
6418 // Example usage:
6419 const array = [1, 2, 3, 2, 4, 5, 1, 6];
6420 const uniqueValues = getUniqueValuesFromRight(array, (a, b) => a === b);
6421 [Link](uniqueValues); // Output: [6, 5, 4, 3]
6422 </script>
6423 <hr />
6424
6425 <h4>
6426 [Link] a JavaScript program to get all unique values of an array, based
6427 on a provided comparator function
6428 </h4>
6429 <script>
6430 function getUniqueValues(arr, comparator) {
6431 const uniqueValues = new Set();
6432 [Link]((element) => {
6433 let isUnique = true;
6434 [Link]((value) => {
6435 if (comparator(element, value)) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 108/298
1/31/24, 9:21 AM [Link]
6436 isUnique = false;
6437 }
6438 });
6439 if (isUnique) {
6440 [Link](element);
6441 }
6442 });
6443 return [Link](uniqueValues);
6444 }
6445
6446 // Example usage:
6447 const array = [1, 2, 3, 2, 4, 5, 1, 6];
6448 const uniqueValues = getUniqueValues(array, (a, b) => a === b);
6449 [Link](uniqueValues); // Output: [1, 2, 3, 4, 5, 6]
6450 </script>
6451 <hr />
6452
6453 <h4>
6454 [Link] a JavaScript program to get the nth element of a given array.
6455 </h4>
6456 <script>
6457 function getNthElement(arr, n) {
6458 // Check if the array is not empty and if the index is within bounds
6459 if ([Link] > 0 && n >= 0 && n < [Link]) {
6460 return arr[n];
6461 } else {
6462 return undefined; // Return undefined if index is out of bounds or array is
empty
6463 }
6464 }
6465
6466 // Example usage:
6467 const array = [1, 2, 3, 4, 5];
6468 [Link](getNthElement(array, 2)); // Output: 3 (index starts from 0)
6469 [Link](getNthElement(array, 0)); // Output: 1
6470 [Link](getNthElement(array, 5)); // Output: undefined (index out of bounds)
6471 </script>
6472 <hr />
6473
6474 <h4>
6475 [Link] a JavaScript program to get every element that exists in any of
6476 the two arrays once.
6477 </h4>
6478 <script>
6479 function getUniqueElements(arr1, arr2) {
6480 // Combine both arrays using the spread operator
6481 const combinedArray = [...arr1, ...arr2];
6482 // Filter out duplicate elements using Set
6483 const uniqueElements = [...new Set(combinedArray)];
6484 return uniqueElements;
6485 }
6486
6487 // Example usage:
6488 const array1 = [1, 2, 3];
6489 const array2 = [3, 4, 5];
6490 [Link](getUniqueElements(array1, array2)); // Output: [1, 2, 3, 4, 5]
6491 </script>
6492 <hr />
6493
6494 <h4>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 109/298
1/31/24, 9:21 AM [Link]
6495 [Link] a JavaScript program to build an array, using an iterator
6496 function and an initial seed value.
6497 </h4>
6498 <script>
6499 function buildArray(iteratorFn, seedValue, length) {
6500 const result = [];
6501 let currentValue = seedValue;
6502
6503 for (let i = 0; i < length; i++) {
6504 [Link](currentValue);
6505 currentValue = iteratorFn(currentValue);
6506 }
6507
6508 return result;
6509 }
6510
6511 // Example usage:
6512 const iteratorFn = (value) => value * 2; // Iterator function doubles the value
6513 const seedValue = 1;
6514 const length = 5;
6515 [Link](buildArray(iteratorFn, seedValue, length)); // Output: [1, 2, 4, 8,
16]
6516 </script>
6517 <hr />
6518
6519 <h4>
6520 [Link] a JavaScript program to unflatten an object with the paths for
6521 keys.
6522 </h4>
6523 <script>
6524 function unflattenObject(flatObject) {
6525 const result = {};
6526
6527 for (const key in flatObject) {
6528 const path = [Link](".");
6529 let current = result;
6530
6531 for (let i = 0; i < [Link] - 1; i++) {
6532 const segment = path[i];
6533 current[segment] = current[segment] || {};
6534 current = current[segment];
6535 }
6536
6537 current[path[[Link] - 1]] = flatObject[key];
6538 }
6539
6540 return result;
6541 }
6542
6543 // Example usage:
6544 const flatObject = {
6545 "a.b.c": 1,
6546 "a.d.e": 2,
6547 f: 3,
6548 };
6549 [Link](unflattenObject(flatObject));
6550 // Output: { a: { b: { c: 1 }, d: { e: 2 } }, f: 3 }
6551 </script>
6552 <hr />
6553
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 110/298
1/31/24, 9:21 AM [Link]
6554 <h4>[Link] a JavaScript program to unescape escaped HTML characters.</h4>
6555 <script>
6556 function unescapeHTML(htmlString) {
6557 const div = [Link]("div");
6558 [Link] = htmlString;
6559 return [Link] || [Link];
6560 }
6561
6562 // Example usage:
6563 const escapedString = "<p>Hello & world</p>";
6564 [Link](unescapeHTML(escapedString));
6565 // Output: <p>Hello & world</p>
6566 </script>
6567 <hr />
6568
6569 <h4>[Link] a JavaScript program to uncurry a function up to depth n.</h4>
6570 <script>
6571 function uncurry(fn, depth = 1) {
6572 if (depth <= 0 || typeof fn !== "function") {
6573 return fn;
6574 }
6575 return function (...args) {
6576 let result = fn;
6577 for (let i = 0; i < depth; i++) {
6578 if (typeof result === "function") {
6579 result = result(...args);
6580 } else {
6581 break;
6582 }
6583 }
6584 return result;
6585 };
6586 }
6587
6588 // Example usage:
6589 function add(a) {
6590 return function (b) {
6591 return function (c) {
6592 return a + b + c;
6593 };
6594 };
6595 }
6596
6597 const curriedAdd = add;
6598 const uncurriedAdd = uncurry(curriedAdd, 3); // Uncurry up to depth 3
6599
6600 [Link](uncurriedAdd(1, 2, 3)); // Output: 6
6601 </script>
6602 <hr />
6603
6604 <h4>
6605 [Link] a JavaScript program to create a function that accepts up to one
6606 argument, ignoring any additional arguments.
6607 </h4>
6608 <script>
6609 function unary(fn) {
6610 return function (arg) {
6611 return fn(arg);
6612 };
6613 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 111/298
1/31/24, 9:21 AM [Link]
6614
6615 // Example usage:
6616 function greet(name) {
6617 return "Hello, " + name + "!";
6618 }
6619
6620 const unaryGreet = unary(greet);
6621
6622 [Link](unaryGreet("Alice")); // Output: Hello, Alice!
6623 [Link](unaryGreet("Bob", "extra")); // Output: Hello, Bob!
6624 </script>
6625 <hr />
6626
6627 <h4>
6628 [Link] a JavaScript program to check if the predicate (second argument)
6629 is truthy on all elements of a collection (first argument)
6630 </h4>
6631 <script>
6632 function truthCheck(collection, predicate) {
6633 return [Link]((item) => Boolean(item[predicate]));
6634 }
6635
6636 // Example usage:
6637 const collection1 = [
6638 { name: "Alice", age: 30 },
6639 { name: "Bob", age: 25 },
6640 { name: "Charlie", age: 40 },
6641 ];
6642
6643 const collection2 = [
6644 { name: "Alice", age: 30 },
6645 { name: "Bob", age: 25 },
6646 { name: "Charlie", age: undefined },
6647 ];
6648
6649 [Link](truthCheck(collection1, "age")); // Output: true
6650 [Link](truthCheck(collection2, "age")); // Output: false
6651 </script>
6652 <hr />
6653
6654 <h4>
6655 [Link] a JavaScript program to truncate a string up to a specified
6656 length.
6657 </h4>
6658 <script>
6659 function truncateString(str, maxLength) {
6660 if ([Link] <= maxLength) {
6661 return str;
6662 } else {
6663 return [Link](0, maxLength) + "...";
6664 }
6665 }
6666
6667 // Example usage:
6668 const originalString =
6669 "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
6670 const maxLength = 20;
6671
6672 [Link](truncateString(originalString, maxLength)); // Output: "Lorem ipsum
dolor s..."
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 112/298
1/31/24, 9:21 AM [Link]
6673 </script>
6674 <hr />
6675
6676 <h4>
6677 [Link] a JavaScript program to apply a function against an accumulator
6678 and each key in the object (from left to right)
6679 </h4>
6680 <script>
6681 function applyFunctionToObject(object, func, initialValue) {
6682 return [Link](object).reduce((accumulator, key) => {
6683 return func(accumulator, key, object[key]);
6684 }, initialValue);
6685 }
6686
6687 // Example usage:
6688 const obj = { a: 1, b: 2, c: 3 };
6689
6690 const sumValues = (acc, key, value) => acc + value;
6691 const result = applyFunctionToObject(obj, sumValues, 0);
6692
6693 [Link](result); // Output: 6 (1 + 2 + 3)
6694 </script>
6695 <hr />
6696
6697 <h4>
6698 [Link] a JavaScript program to create tomorrow's date in a string
6699 representation
6700 </h4>
6701 <script>
6702 function getTomorrowsDate() {
6703 const today = new Date();
6704 const tomorrow = new Date(today);
6705 [Link]([Link]() + 1);
6706
6707 // Format the date into a string representation (e.g., "YYYY-MM-DD")
6708 const year = [Link]();
6709 const month = String([Link]() + 1).padStart(2, "0");
6710 const day = String([Link]()).padStart(2, "0");
6711
6712 return `${year}-${month}-${day}`;
6713 }
6714
6715 // Example usage:
6716 const tomorrowDate = getTomorrowsDate();
6717 [Link](tomorrowDate); // Output: "2024-01-30" (assuming today is "2024-01-29"
)
6718 </script>
6719 <hr />
6720
6721 <h4>[Link] a JavaScript program to convert a string to snake case.</h4>
6722 <script>
6723 function toSnakeCase(str) {
6724 // Replace spaces with underscores and convert to lowercase
6725 return [Link](/\s+/g, "_").toLowerCase();
6726 }
6727
6728 // Example usage:
6729 const inputString = "Convert This String To Snake Case";
6730 const snakeCaseString = toSnakeCase(inputString);
6731 [Link](snakeCaseString); // Output: "convert_this_string_to_snake_case"
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 113/298
1/31/24, 9:21 AM [Link]
6732 </script>
6733 <hr />
6734
6735 <h4>
6736 [Link] a JavaScript program to convert a value to a safe integer.
6737 </h4>
6738 <script>
6739 function toSafeInteger(value) {
6740 // If the value is already a safe integer, return it
6741 if ([Link](value)) {
6742 return value;
6743 }
6744
6745 // Otherwise, return the closest safe integer value
6746 return [Link](value);
6747 }
6748
6749 // Example usage:
6750 [Link](toSafeInteger(3.14)); // Output: 3
6751 [Link](toSafeInteger(9007199254740992)); // Output: 9007199254740992 (safe
integer)
6752 [Link](toSafeInteger(1e21)); // Output: 1000000000000000000000
6753 </script>
6754 <hr />
6755
6756 <h4>
6757 [Link] a JavaScript program to add an ordinal suffix to a number.
6758 </h4>
6759 <script>
6760 function addOrdinalSuffix(num) {
6761 if (typeof num !== "number" || isNaN(num)) {
6762 return NaN;
6763 }
6764
6765 const lastDigit = num % 10;
6766 const lastTwoDigits = num % 100;
6767
6768 if (lastTwoDigits >= 11 && lastTwoDigits <= 13) {
6769 return num + "th";
6770 }
6771
6772 switch (lastDigit) {
6773 case 1:
6774 return num + "st";
6775 case 2:
6776 return num + "nd";
6777 case 3:
6778 return num + "rd";
6779 default:
6780 return num + "th";
6781 }
6782 }
6783
6784 // Example usage:
6785 [Link](addOrdinalSuffix(1)); // Output: 1st
6786 [Link](addOrdinalSuffix(22)); // Output: 22nd
6787 [Link](addOrdinalSuffix(333)); // Output: 333rd
6788 [Link](addOrdinalSuffix(404)); // Output: 404th
6789 </script>
6790 <hr />
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 114/298
1/31/24, 9:21 AM [Link]
6791
6792 <h4>[Link] a JavaScript program to convert a string to kebab case.</h4>
6793 <script>
6794 function toKebabCase(str) {
6795 return str
6796 .replace(/[\s_]+/g, "-")
6797 .replace(/[A-Z]/g, (match) => "-" + [Link]())
6798 .replace(/^-+/g, "")
6799 .replace(/-+/g, "-");
6800 }
6801
6802 // Example usage:
6803 [Link](toKebabCase("Hello World")); // Output: hello-world
6804 [Link](toKebabCase("camelCaseExample")); // Output: camel-case-example
6805 [Link](toKebabCase("kebab_case_example")); // Output: kebab-case-example
6806 </script>
6807 <hr />
6808
6809 <h4>
6810 [Link] a JavaScript program to reduce a given Array-like into a value
6811 hash (keyed data store).
6812 </h4>
6813 <script>
6814 function reduceToHash(arrayLike, keyField) {
6815 return [Link](arrayLike).reduce((hash, item) => {
6816 const key = item[keyField];
6817 hash[key] = item;
6818 return hash;
6819 }, {});
6820 }
6821
6822 // Example usage:
6823 const arrayLike = [
6824 { id: 1, name: "John" },
6825 { id: 2, name: "Alice" },
6826 { id: 3, name: "Bob" },
6827 ];
6828
6829 const hash = reduceToHash(arrayLike, "id");
6830 [Link](hash);
6831 </script>
6832 <hr />
6833
6834 <h4>
6835 [Link] a JavaScript program to convert a float-point arithmetic to the
6836 Decimal mark form and It will make a comma separated string from a number
6837 </h4>
6838 <script>
6839 function convertToDecimalMark(number) {
6840 return [Link]("en-US");
6841 }
6842
6843 // Example usage:
6844 const floatingNumber = 1234567.89;
6845 const decimalMarkString = convertToDecimalMark(floatingNumber);
6846 [Link](decimalMarkString); // Output: "1,234,567.89"
6847 </script>
6848 <hr />
6849
6850 <h4>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 115/298
1/31/24, 9:21 AM [Link]
6851 [Link] a JavaScript program to create a specified currency formatting
6852 from a given number.
6853 </h4>
6854 <script>
6855 function formatCurrency(number, currency = "USD", locale = "en-US") {
6856 return new [Link](locale, {
6857 style: "currency",
6858 currency: currency,
6859 }).format(number);
6860 }
6861
6862 // Example usage:
6863 const amount = 123456.78;
6864 const formattedCurrency = formatCurrency(amount, "USD", "en-US");
6865 [Link](formattedCurrency); // Output: "$123,456.78"
6866 </script>
6867 <hr />
6868
6869 <h4>[Link] a JavaScript program to Iterate over a callback n times.</h4>
6870 <script>
6871 function iterateNTimes(n, callback) {
6872 for (let i = 0; i < n; i++) {
6873 callback(i);
6874 }
6875 }
6876
6877 // Example usage:
6878 function printIndex(index) {
6879 [Link](`Iteration ${index + 1}`);
6880 }
6881
6882 iterateNTimes(5, printIndex);
6883 </script>
6884 <hr />
6885
6886 <h4>
6887 [Link] a JavaScript program to get removed elements of a given array
6888 until the passed function returns true
6889 </h4>
6890 <script>
6891 function removeElementsUntil(arr, func) {
6892 const removed = [];
6893 let index = 0;
6894
6895 while (index < [Link] && !func(arr[index])) {
6896 [Link]([Link](index, 1)[0]);
6897 }
6898
6899 return removed;
6900 }
6901
6902 // Example usage:
6903 const numbers = [1, 2, 3, 4, 5, 6];
6904 const isEven = (num) => num % 2 === 0;
6905
6906 const removed = removeElementsUntil(numbers, isEven);
6907 [Link]("Removed elements:", removed); // Output: [1, 3, 5]
6908 [Link]("Remaining elements:", numbers); // Output: [2, 4, 6]
6909 </script>
6910 <hr />
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 116/298
1/31/24, 9:21 AM [Link]
6911
6912 <h4>
6913 [Link] a JavaScript program to get removed elements from the end of a
6914 given array until the passed function returns true.
6915 </h4>
6916 <script>
6917 function removeElementsFromEndUntil(arr, func) {
6918 const removed = [];
6919 let index = [Link] - 1;
6920
6921 while (index >= 0 && !func(arr[index])) {
6922 [Link]([Link]());
6923 index--;
6924 }
6925
6926 return removed;
6927 }
6928
6929 // Example usage:
6930 const numbers = [1, 2, 3, 4, 5, 6];
6931 const isEven = (num) => num % 2 === 0;
6932
6933 const removed = removeElementsFromEndUntil(numbers, isEven);
6934 [Link]("Removed elements:", removed); // Output: [6, 4]
6935 [Link]("Remaining elements:", numbers); // Output: [1, 2, 3, 5]
6936 </script>
6937 <hr />
6938
6939 <h4>
6940 [Link] a JavaScript program to remove n elements from the end of a
6941 given array.
6942 </h4>
6943 <script>
6944 function removeElementsFromEnd(arr, n) {
6945 return [Link](0, -n);
6946 }
6947
6948 // Example usage:
6949 const numbers = [1, 2, 3, 4, 5, 6];
6950 const n = 3;
6951
6952 const result = removeElementsFromEnd(numbers, n);
6953 [Link]("Array after removal:", result); // Output: [1, 2, 3]
6954 </script>
6955 <hr />
6956
6957 <h4>
6958 [Link] a JavaScript program to get an array with n elements removed
6959 from the beginning from a given array
6960 </h4>
6961 <script>
6962 function removeElementsFromBeginning(arr, n) {
6963 return [Link](n);
6964 }
6965
6966 // Example usage:
6967 const numbers = [1, 2, 3, 4, 5, 6];
6968 const n = 3;
6969
6970 const result = removeElementsFromBeginning(numbers, n);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 117/298
1/31/24, 9:21 AM [Link]
6971 [Link]("Array after removal:", result); // Output: [4, 5, 6]
6972 </script>
6973 <hr />
6974
6975 <h4>
6976 [Link] a JavaScript program to get the symmetric difference between two
6977 given arrays, using a provided function as a comparator.
6978 </h4>
6979 <script>
6980 function symmetricDifferenceWith(arr1, arr2, comparator) {
6981 const diff1 = [Link]((x) =>  => comparator(x, y)));
6982 const diff2 = [Link]((x) =>  => comparator(x, y)));
6983 return [Link](diff2);
6984 }
6985
6986 // Example usage:
6987 const arr1 = [1, 2, 3, 4];
6988 const arr2 = [3, 4, 5, 6];
6989
6990 const comparator = (a, b) => a === b; // Example comparator function
6991
6992 const result = symmetricDifferenceWith(arr1, arr2, comparator);
6993 [Link]("Symmetric difference:", result); // Output: [1, 2, 5, 6]
6994 </script>
6995 <hr />
6996
6997 <h4>
6998 [Link] a JavaScript program to get the symmetric difference between two
6999 given arrays, after applying the provided function to each array element
7000 of both.
7001 </h4>
7002 <script>
7003 function symmetricDifferenceBy(arr1, arr2, fn) {
7004 const set1 = new Set([Link](fn));
7005 const set2 = new Set([Link](fn));
7006
7007 const diff1 = [Link]((x) => )).map(fn);
7008 const diff2 = [Link]((x) => )).map(fn);
7009
7010 return [Link](diff2);
7011 }
7012
7013 // Example usage:
7014 const arr1 = [1.2, 2.3, 3.4];
7015 const arr2 = [3.5, 4.6, 5.7];
7016
7017 const result = symmetricDifferenceBy(arr1, arr2, [Link]);
7018 [Link]("Symmetric difference:", result); // Output: [1, 2, 4, 5]
7019 </script>
7020 <hr />
7021
7022 <h4>
7023 [Link] a JavaScript program to get the symmetric difference between two
7024 given arrays.
7025 </h4>
7026 <script>
7027 function symmetricDifference(arr1, arr2) {
7028 const set1 = new Set(arr1);
7029 const set2 = new Set(arr2);
7030
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 118/298
1/31/24, 9:21 AM [Link]
7031 const diff1 = [Link]((x) => );
7032 const diff2 = [Link]((x) => );
7033
7034 return [Link](diff2);
7035 }
7036
7037 // Example usage:
7038 const arr1 = [1, 2, 3, 4, 5];
7039 const arr2 = [3, 4, 5, 6, 7];
7040
7041 const result = symmetricDifference(arr1, arr2);
7042 [Link]("Symmetric difference:", result); // Output: [1, 2, 6, 7]
7043 </script>
7044 <hr />
7045
7046 <h4>
7047 [Link] a JavaScript program to get the sum of the powers of all the
7048 numbers from start to end (both inclusive).
7049 </h4>
7050 <script>
7051 function sumOfPowers(start, end, power) {
7052 let sum = 0;
7053 for (let i = start; i <= end; i++) {
7054 sum += [Link](i, power);
7055 }
7056 return sum;
7057 }
7058
7059 // Example usage:
7060 const start = 1;
7061 const end = 5;
7062 const power = 2;
7063
7064 const result = sumOfPowers(start, end, power);
7065 [Link]("Sum of powers:", result); // Output: 55 (1^2 + 2^2 + 3^2 + 4^2 + 5^2
= 55)
7066 </script>
7067 <hr />
7068
7069 <h4>
7070 [Link] a JavaScript program to generate all permutations of a string
7071 (contains duplicates).
7072 </h4>
7073 <script>
7074 function permuteStringWithDuplicates(str) {
7075 const permutations = [];
7076
7077 // Helper function to recursively generate permutations
7078 function generatePermutations(current, remaining) {
7079 if ([Link] === 0) {
7080 [Link](current);
7081 return;
7082 }
7083
7084 const uniqueChars = new Set();
7085 for (let i = 0; i < [Link]; i++) {
7086 if () {
7087 [Link](remaining[i]);
7088 generatePermutations(
7089 current + remaining[i],
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 119/298
1/31/24, 9:21 AM [Link]
7090 [Link](0, i) + [Link](i + 1)
7091 );
7092 }
7093 }
7094 }
7095
7096 generatePermutations("", str);
7097 return permutations;
7098 }
7099
7100 // Example usage:
7101 const str = "aab";
7102 const result = permuteStringWithDuplicates(str);
7103 [Link]("Permutations:", result);
7104 </script>
7105 <hr />
7106
7107 <h4>
7108 [Link] a JavaScript program to perform stable sorting of an array,
7109 preserving the initial indexes of items when their values are the same. Do
7110 not mutate the original array, but returns a new array instead.
7111 </h4>
7112 <script>
7113 function stableSort(array) {
7114 // Create an array of objects containing both the original value and its index
7115 const indexedArray = [Link]((value, index) => ({ value, index }));
7116
7117 // Custom comparator function to sort the indexedArray
7118 const comparator = (a, b) => {
7119 if ([Link] === [Link]) {
7120 return [Link] - [Link]; // Preserve the original index if values are equal
7121 }
7122 return [Link] - [Link]; // Otherwise, sort by value
7123 };
7124
7125 // Sort the indexedArray using the custom comparator
7126 [Link](comparator);
7127
7128 // Extract and return the sorted values from the indexedArray
7129 return [Link](({ value }) => value);
7130 }
7131
7132 // Example usage:
7133 const array = [4, 2, 1, 3, 2];
7134 const sortedArray = stableSort(array);
7135 [Link]("Original Array:", array);
7136 [Link]("Stable Sorted Array:", sortedArray);
7137 </script>
7138 <hr />
7139
7140 <h4>
7141 [Link] a JavaScript program that takes a variadic function and returns
7142 a closure that accepts an array of arguments to map to the inputs of the
7143 function
7144 </h4>
7145 <script>
7146 function spreadOver(fn) {
7147 return function (argsArr) {
7148 return fn(...argsArr);
7149 };
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 120/298
1/31/24, 9:21 AM [Link]
7150 }
7151
7152 // Example usage:
7153 function sum(a, b, c) {
7154 return a + b + c;
7155 }
7156
7157 const spreadSum = spreadOver(sum);
7158 const result = spreadSum([1, 2, 3]);
7159 [Link]("Result:", result); // Output: 6
7160 </script>
7161 <hr />
7162
7163 <h4>
7164 [Link] a JavaScript program to split a multiline string into an array
7165 of lines.
7166 </h4>
7167 <script>
7168 function splitLines(str) {
7169 return [Link]("\n");
7170 }
7171
7172 // Example usage:
7173 const multilineString = `Line 1
7174 Line 2
7175 Line 3`;
7176
7177 const linesArray = splitLines(multilineString);
7178 [Link](linesArray);
7179 </script>
7180 <hr />
7181
7182 <h4>
7183 [Link] a JavaScript program to get the highest index at which value
7184 should be inserted into array in order to maintain its sort order, based
7185 on a provided iterator function.
7186 </h4>
7187 <script>
7188 function findHighestIndex(arr, value, iteratorFn) {
7189 return [Link]((el, idx) => {
7190 const result = iteratorFn(value, el);
7191 return result < 0 || (result === 0 && idx === [Link] - 1);
7192 });
7193 }
7194
7195 // Example usage:
7196 const numbers = [10, 20, 30, 40, 50];
7197 const value = 35;
7198
7199 // Define the iterator function
7200 function compareFn(a, b) {
7201 return a - b; // Ascending order comparison
7202 }
7203
7204 const highestIndex = findHighestIndex(numbers, value, compareFn);
7205 [Link]("Highest index:", highestIndex);
7206 </script>
7207 <hr />
7208
7209 <h4>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 121/298
1/31/24, 9:21 AM [Link]
7210 [Link] a JavaScript program to get the highest index at which value
7211 should be inserted into array in order to maintain its sort order
7212 </h4>
7213 <script>
7214 function findHighestIndex(arr, value) {
7215 let left = 0;
7216 let right = [Link] - 1;
7217 let result = -1;
7218
7219 while (left <= right) {
7220 const mid = [Link]((left + right) / 2);
7221
7222 if (arr[mid] <= value) {
7223 result = mid;
7224 left = mid + 1;
7225 } else {
7226 right = mid - 1;
7227 }
7228 }
7229
7230 return result + 1; // Add 1 to get the index for insertion
7231 }
7232
7233 // Example usage:
7234 const numbers = [10, 20, 30, 40, 50];
7235 const value = 35;
7236
7237 const highestIndex = findHighestIndex(numbers, value);
7238 [Link]("Highest index:", highestIndex);
7239 </script>
7240 <hr />
7241
7242 <h4>
7243 [Link] a JavaScript program to get the lowest index at which value
7244 should be inserted into array in order to maintain its sort order.
7245 </h4>
7246 <script>
7247 function findLowestIndex(arr, value) {
7248 let left = 0;
7249 let right = [Link] - 1;
7250 let result = [Link]; // Set to array length as default
7251
7252 while (left <= right) {
7253 const mid = [Link]((left + right) / 2);
7254
7255 if (arr[mid] >= value) {
7256 result = mid;
7257 right = mid - 1;
7258 } else {
7259 left = mid + 1;
7260 }
7261 }
7262
7263 return result; // The lowest index for insertion
7264 }
7265
7266 // Example usage:
7267 const numbers = [10, 20, 30, 40, 50];
7268 const value = 35;
7269
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 122/298
1/31/24, 9:21 AM [Link]
7270 const lowestIndex = findLowestIndex(numbers, value);
7271 [Link]("Lowest index:", lowestIndex);
7272 </script>
7273 <hr />
7274
7275 <h4>
7276 [Link] a JavaScript program to sort the characters of a string
7277 Alphabetically.
7278 </h4>
7279 <script>
7280 function sortStringAlphabetically(str) {
7281 // Convert the string to an array of characters, sort them, then join back into
a string
7282 return [Link]("").sort().join("");
7283 }
7284
7285 // Example usage:
7286 const inputString = "hello";
7287 const sortedString = sortStringAlphabetically(inputString);
7288 [Link]("Original string:", inputString);
7289 [Link]("Sorted string:", sortedString);
7290 </script>
7291 <hr />
7292
7293 <h4>
7294 [Link] a JavaScript program to get an array of elements that appear in
7295 both arrays
7296 </h4>
7297 <script>
7298 function commonElements(array1, array2) {
7299 // Filter the elements of array1 that also exist in array2
7300 const common = [Link]((element) => [Link](element));
7301 return common;
7302 }
7303
7304 // Example usage:
7305 const arr1 = [1, 2, 3, 4, 5];
7306 const arr2 = [3, 4, 5, 6, 7];
7307
7308 const commonElementsArray = commonElements(arr1, arr2);
7309 [Link]("Common Elements:", commonElementsArray); // Output: [3, 4, 5]
7310 </script>
7311 <hr />
7312
7313 <h4>
7314 [Link] a JavaScript program to randomize the order of the values of an
7315 array, returning a new array.
7316 </h4>
7317 <script>
7318 function shuffleArray(array) {
7319 // Create a copy of the original array
7320 const newArray = [Link]();
7321
7322 // Implement Fisher-Yates shuffle algorithm
7323 for (let i = [Link] - 1; i > 0; i--) {
7324 const j = [Link]([Link]() * (i + 1));
7325 [newArray[i], newArray[j]] = [newArray[j], newArray[i]]; // Swap elements
7326 }
7327
7328 return newArray;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 123/298
1/31/24, 9:21 AM [Link]
7329 }
7330
7331 // Example usage:
7332 const originalArray = [1, 2, 3, 4, 5];
7333 const randomizedArray = shuffleArray(originalArray);
7334 [Link]("Original Array:", originalArray);
7335 [Link]("Randomized Array:", randomizedArray);
7336 </script>
7337 <hr />
7338
7339 <h4>
7340 [Link] a JavaScript program to create a shallow clone of an object
7341 </h4>
7342 <script>
7343 // Using object spread syntax
7344 function shallowCloneObject(obj) {
7345 return { ...obj };
7346 }
7347
7348 // Using [Link]()
7349 function shallowCloneObject(obj) {
7350 return [Link]({}, obj);
7351 }
7352
7353 // Example usage:
7354 const originalObject = { a: 1, b: { c: 2 } };
7355 const clonedObject = shallowCloneObject(originalObject);
7356
7357 [Link]("Original Object:", originalObject);
7358 [Link]("Cloned Object:", clonedObject);
7359
7360 // Modifying the cloned object to demonstrate shallow cloning
7361 clonedObject.a = 3;
7362 clonedObject.b.c = 4;
7363
7364 [Link]("Modified Cloned Object:", clonedObject); // Note: Modification
affects nested object
7365 [Link]("Original Object (unchanged):", originalObject);
7366 </script>
7367 <hr />
7368
7369 <h4>
7370 [Link] a JavaScript program to serialize a cookie name-value pair into
7371 a Set-Cookie header string.
7372 </h4>
7373 <script>
7374 function serializeCookie(name, value, options = {}) {
7375 const { expires, maxAge, domain, path, secure, httpOnly } = options;
7376 let cookieStr = `${name}=${encodeURIComponent(value)}`;
7377
7378 if (expires instanceof Date) {
7379 cookieStr += `; Expires=${[Link]()}`;
7380 }
7381 if (typeof maxAge === "number") {
7382 cookieStr += `; Max-Age=${maxAge}`;
7383 }
7384 if (domain) {
7385 cookieStr += `; Domain=${domain}`;
7386 }
7387 if (path) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 124/298
1/31/24, 9:21 AM [Link]
7388 cookieStr += `; Path=${path}`;
7389 }
7390 if (secure) {
7391 cookieStr += `; Secure`;
7392 }
7393 if (httpOnly) {
7394 cookieStr += `; HttpOnly`;
7395 }
7396
7397 return cookieStr;
7398 }
7399
7400 // Example usage:
7401 const cookieName = "user";
7402 const cookieValue = "john_doe";
7403 const options = {
7404 expires: new Date([Link]() + 86400000), // Expires in 1 day (86400000
milliseconds)
7405 domain: ".[Link]",
7406 path: "/",
7407 secure: true,
7408 httpOnly: true,
7409 };
7410
7411 const setCookieHeader = serializeCookie(cookieName, cookieValue, options);
7412 [Link](setCookieHeader);
7413 </script>
7414 <hr />
7415
7416 <h4>
7417 [Link] a JavaScript program to hash the input string into a whole
7418 number
7419 </h4>
7420 <script>
7421 function hashString(input) {
7422 let hash = 5381;
7423 for (let i = 0; i < [Link]; i++) {
7424 hash = (hash * 33) ^ [Link](i);
7425 }
7426 return hash >>> 0; // Convert to unsigned 32-bit integer
7427 }
7428
7429 // Example usage:
7430 const inputString = "hello";
7431 const hashedNumber = hashString(inputString);
7432 [Link](hashedNumber);
7433 </script>
7434 <hr />
7435
7436 <h4>
7437 299. Write a JavaScript program to get a random element from an array.
7438 </h4>
7439 <script>
7440 function getRandomElement(array) {
7441 const randomIndex = [Link]([Link]() * [Link]);
7442 return array[randomIndex];
7443 }
7444
7445 // Example usage:
7446 const myArray = [1, 2, 3, 4, 5];
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 125/298
1/31/24, 9:21 AM [Link]
7447 const randomElement = getRandomElement(myArray);
7448 [Link](randomElement);
7449 </script>
7450 <hr />
7451
7452 <h4>
7453 [Link] a JavaScript program to run a given array of promises in series
7454 </h4>
7455 <script>
7456 async function runPromisesInSeries(promises) {
7457 const results = [];
7458 for (const promise of promises) {
7459 const result = await promise;
7460 [Link](result);
7461 }
7462 return results;
7463 }
7464
7465 // Example usage:
7466 const promise1 = new Promise((resolve) =>
7467 setTimeout(() => resolve("result 1"), 1000)
7468 );
7469 const promise2 = new Promise((resolve) =>
7470 setTimeout(() => resolve("result 2"), 2000)
7471 );
7472 const promise3 = new Promise((resolve) =>
7473 setTimeout(() => resolve("result 3"), 1500)
7474 );
7475
7476 const promises = [promise1, promise2, promise3];
7477
7478 runPromisesInSeries(promises)
7479 .then((results) => [Link](results))
7480 .catch((error) => [Link](error));
7481 </script>
7482 <hr />
7483
7484 <!-- -------------------- 101 -200 ------------------ -->
7485 <!-- Question 101 -->
7486 <h3>Question 101:</h3>
7487 <p>
7488 Write a JavaScript program to check whether a given string contains only
7489 Latin letters and no two uppercase and no two lowercase letters are in
7490 adjacent positions.
7491 </p>
7492
7493 <!-- Answer 101 -->
7494 <script>
7495 function isValidString(str) {
7496 for (let i = 0; i < [Link] - 1; i++) {
7497 if (
7498 (str[i] >= "a" &&
7499 str[i] <= "z" &&
7500 str[i + 1] >= "a" &&
7501 str[i + 1] <= "z") ||
7502 (str[i] >= "A" &&
7503 str[i] <= "Z" &&
7504 str[i + 1] >= "A" &&
7505 str[i + 1] <= "Z")
7506 ) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 126/298
1/31/24, 9:21 AM [Link]
7507 return false;
7508 }
7509 }
7510 return true;
7511 }
7512 </script>
7513
7514 <!-- Question 102 -->
7515 <h3>Question 102:</h3>
7516 <p>
7517 Write a JavaScript program to find the number of inversions of a given
7518 array of integers. Note: Two elements of the array a stored at positions i
7519 and j form an inversion if a[i] > a[j] and i < j.
7520 </p>
7521
7522 <!-- Answer 102 -->
7523 <script>
7524 function countInversions(arr) {
7525 let count = 0;
7526 for (let i = 0; i < [Link]; i++) {
7527 for (let j = i + 1; j < [Link]; j++) {
7528 if (arr[i] > arr[j]) {
7529 count++;
7530 }
7531 }
7532 }
7533 return count;
7534 }
7535 </script>
7536
7537 <!-- Question 103 -->
7538 <h3>Question 103:</h3>
7539 <p>
7540 Write a JavaScript program to find the maximal number from a given
7541 positive integer by deleting exactly one digit of the given number.
7542 </p>
7543
7544 <!-- Answer 103 -->
7545 <script>
7546 function findMaximalNumber(num) {
7547 const numStr = [Link]();
7548 let maxNum = 0;
7549
7550 for (let i = 0; i < [Link]; i++) {
7551 const updatedNum = parseInt([Link](0, i) + [Link](i + 1));
7552 maxNum = [Link](maxNum, updatedNum);
7553 }
7554
7555 return maxNum;
7556 }
7557 </script>
7558
7559 <!-- Question 104 -->
7560 <h3>Question 104:</h3>
7561 <p>
7562 Write a JavaScript program to find two elements of the array such that
7563 their absolute difference is not greater than a given integer but is as
7564 close to the said integer.
7565 </p>
7566
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 127/298
1/31/24, 9:21 AM [Link]
7567 <!-- Answer 104 -->
7568 <script>
7569 function findClosestElements(arr, target) {
7570 // Implementation goes here...
7571 }
7572 </script>
7573
7574 <!-- Question 105 -->
7575 <h3>Question 105:</h3>
7576 <p>
7577 Write a JavaScript program to find the number of times to replace a given
7578 number with the sum of its digits until it converts to a single-digit
7579 number.
7580 </p>
7581
7582 <!-- Answer 105 -->
7583 <script>
7584 function countDigitSumReplacementSteps(num) {
7585 // Implementation goes here...
7586 }
7587 </script>
7588
7589 <!-- Question 106 -->
7590 <h3>Question 106:</h3>
7591 <p>
7592 Write a JavaScript program to divide an integer by another integer as long
7593 as the result is an integer and return the result.
7594 </p>
7595
7596 <!-- Answer 106 -->
7597 <script>
7598 function divideIntegers(dividend, divisor) {
7599 // Implementation goes here...
7600 }
7601 </script>
7602
7603 <!-- Question 107 -->
7604 <h3>Question 107:</h3>
7605 <p>
7606 Write a JavaScript program to find the number of sorted pairs formed by
7607 its elements of a given array of integers such that one element in the
7608 pair is divisible by the other one.
7609 </p>
7610
7611 <!-- Answer 107 -->
7612 <script>
7613 function countSortedPairs(arr) {
7614 // Implementation goes here...
7615 }
7616 </script>
7617
7618 <!-- Question 108 -->
7619 <h3>Question 108:</h3>
7620 <p>
7621 Write a JavaScript program to create the dot products of two given 3D
7622 vectors. Note: The dot product is the sum of the products of the
7623 corresponding entries of the two sequences of numbers.
7624 </p>
7625
7626 <!-- Answer 108 -->
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 128/298
1/31/24, 9:21 AM [Link]
7627 <script>
7628 function calculateDotProduct(vector1, vector2) {
7629 // Implementation goes here...
7630 }
7631 </script>
7632
7633 <!-- Question 109 -->
7634 <h3>Question 109:</h3>
7635 <p>
7636 Write a JavaScript program to sort an array of all prime numbers between 1
7637 and a given integer.
7638 </p>
7639
7640 <!-- Answer 109 -->
7641 <script>
7642 function sortPrimeNumbers(limit) {
7643 // Implementation goes here...
7644 }
7645 </script>
7646
7647 <!-- Question 110 -->
7648 <h3>Question 110:</h3>
7649 <p>
7650 Write a JavaScript program to find the number of even values in sequence
7651 before the first occurrence of a given number.
7652 </p>
7653
7654 <!-- Answer 110 -->
7655 <script>
7656 function countEvenValuesBeforeNumber(sequence, targetNumber) {
7657 // Implementation goes here...
7658 }
7659 </script>
7660 <!-- Question 111 -->
7661 <h3>Question 111:</h3>
7662 <p>
7663 Write a JavaScript program to check whether a given string contains only
7664 Latin letters and no two uppercase and no two lowercase letters are in
7665 adjacent positions.
7666 </p>
7667
7668 <!-- Answer 111 -->
7669 <script>
7670 function isValidString(str) {
7671 // Implementation goes here...
7672 }
7673 </script>
7674
7675 <!-- Question 112 -->
7676 <h3>Question 112:</h3>
7677 <p>
7678 Write a JavaScript program to find the number of inversions of a given
7679 array of integers. Note: Two elements of the array a stored at positions i
7680 and j form an inversion if a[i] > a[j] and i < j.
7681 </p>
7682
7683 <!-- Answer 112 -->
7684 <script>
7685 function countInversions(arr) {
7686 // Implementation goes here...
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 129/298
1/31/24, 9:21 AM [Link]
7687 }
7688 </script>
7689
7690 <!-- Question 113 -->
7691 <h3>Question 113:</h3>
7692 <p>
7693 Write a JavaScript program to find the maximal number from a given
7694 positive integer by deleting exactly one digit of the given number.
7695 </p>
7696
7697 <!-- Answer 113 -->
7698 <script>
7699 function findMaximalNumber(num) {
7700 // Implementation goes here...
7701 }
7702 </script>
7703
7704 <!-- Question 114 -->
7705 <h3>Question 114:</h3>
7706 <p>
7707 Write a JavaScript program to find two elements of the array such that
7708 their absolute difference is not greater than a given integer but is as
7709 close to the said integer.
7710 </p>
7711
7712 <!-- Answer 114 -->
7713 <script>
7714 function findClosestElements(arr, target) {
7715 // Implementation goes here...
7716 }
7717 </script>
7718
7719 <!-- Question 115 -->
7720 <h3>Question 115:</h3>
7721 <p>
7722 Write a JavaScript program to find the number of times to replace a given
7723 number with the sum of its digits until it converts to a single-digit
7724 number.
7725 </p>
7726
7727 <!-- Answer 115 -->
7728 <script>
7729 function countDigitSumReplacementSteps(num) {
7730 // Implementation goes here...
7731 }
7732 </script>
7733
7734 <!-- Question 116 -->
7735 <h3>Question 116:</h3>
7736 <p>
7737 Write a JavaScript program to find all the possible options to replace the
7738 hash in a string (Consists of digits and one hash (#)) with a digit to
7739 produce an integer divisible by 3. For a string "2*0", the output should
7740 be : ["210", "240", "270"]
7741 </p>
7742
7743 <!-- Answer 116 -->
7744 <script>
7745 function replaceHashForDivisibleBy3(str) {
7746 const results = [];
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 130/298
1/31/24, 9:21 AM [Link]
7747 for (let i = 0; i < 10; i++) {
7748 const replacedStr = [Link]("#", i);
7749 if (parseInt(replacedStr) % 3 === 0) {
7750 [Link](replacedStr);
7751 }
7752 }
7753 return results;
7754 }
7755 </script>
7756
7757 <!-- Question 117 -->
7758 <h3>Question 117:</h3>
7759 <p>
7760 Write a JavaScript program to check whether a given matrix is an identity
7761 matrix. Note: In linear algebra, the identity matrix, or sometimes
7762 ambiguously called a unit matrix, of size n is the n × n square matrix
7763 with ones on the main diagonal and zeros elsewhere. [[1, 0, 0], [0, 1, 0],
7764 [0, 0, 1]] -> true [[1, 0, 0], [0, 1, 0], [1, 0, 1]] -> false
7765 </p>
7766
7767 <!-- Answer 117 -->
7768 <script>
7769 function isIdentityMatrix(matrix) {
7770 for (let i = 0; i < [Link]; i++) {
7771 for (let j = 0; j < matrix[i].length; j++) {
7772 if (
7773 (i === j && matrix[i][j] !== 1) ||
7774 (i !== j && matrix[i][j] !== 0)
7775 ) {
7776 return false;
7777 }
7778 }
7779
7780 return true;
7781 }
7782
7783 // Implementation goes here...
7784 }
7785 </script>
7786
7787 <!-- Question 118 -->
7788 <h3>Question 118:</h3>
7789 <p>
7790 Write a JavaScript program to check whether a given number is in a given
7791 range.
7792 </p>
7793
7794 <!-- Answer 118 -->
7795 <script>
7796 function isNumberInRange(number, rangeStart, rangeEnd) {
7797 return number >= rangeStart && number <= rangeEnd;
7798 }
7799 </script>
7800
7801 <!-- Question 119 -->
7802 <h3>Question 119:</h3>
7803 <p>
7804 Write a JavaScript program to check whether a given integer has an
7805 increasing digits sequence.
7806 </p>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 131/298
1/31/24, 9:21 AM [Link]
7807
7808 <!-- Answer 119 -->
7809 <script>
7810 function hasIncreasingDigitsSequence(number) {
7811 const digits = [Link]().split("").map(Number);
7812 for (let i = 1; i < [Link]; i++) {
7813 if (digits[i] <= digits[i - 1]) {
7814 return false;
7815 }
7816 }
7817 return true;
7818 }
7819 </script>
7820
7821 <!-- Question 120 -->
7822 <h3>Question 120:</h3>
7823 <p>
7824 Write a JavaScript program to check whether a point lies strictly inside a
7825 given circle. Input: Center of the circle (x, y) Radius of circle: r Point
7826 inside a circle (a, b)
7827 </p>
7828
7829 <!-- Answer 120 -->
7830 <script>
7831 function isPointInsideCircle(centerX, centerY, radius, pointX, pointY) {
7832 const distance = [Link](
7833 [Link](pointX - centerX, 2) + [Link](pointY - centerY, 2)
7834 );
7835 return distance < radius;
7836 }
7837 </script>
7838
7839 <!-- Question 121 -->
7840 <h3>Question 121:</h3>
7841 <p>
7842 Write a JavaScript program to check whether a given matrix is lower
7843 triangular or not.
7844 </p>
7845
7846 <!-- Answer 121 -->
7847 <script>
7848 function isLowerTriangular(matrix) {
7849 for (let i = 0; i < [Link]; i++) {
7850 for (let j = i + 1; j < matrix[i].length; j++) {
7851 if (matrix[i][j] !== 0) {
7852 return false;
7853 }
7854 }
7855 }
7856 return true;
7857 }
7858 </script>
7859
7860 <!-- Question 122 -->
7861 <h3>Question 122:</h3>
7862 <p>
7863 Write a JavaScript program to check whether a given array of integers
7864 represents either a strictly increasing or a strictly decreasing sequence.
7865 </p>
7866
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 132/298
1/31/24, 9:21 AM [Link]
7867 <!-- Answer 122 -->
7868 <script>
7869 function isStrictSequence(arr) {
7870 const increasing = [Link](
7871 (num, index) => index === 0 || num > arr[index - 1]
7872 );
7873 const decreasing = [Link](
7874 (num, index) => index === 0 || num < arr[index - 1]
7875 );
7876
7877 return increasing || decreasing;
7878 }
7879 </script>
7880
7881 <!-- Question 123 -->
7882 <h3>Question 123:</h3>
7883 <p>
7884 Write a JavaScript program to find whether the members of a given array of
7885 integers are a permutation of numbers from 1 to a given integer.
7886 </p>
7887
7888 <!-- Answer 123 -->
7889 <script>
7890 function isPermutation(arr, n) {
7891 const sortedArr = [Link]().sort((a, b) => a - b);
7892 const expectedArray = [Link]({ length: n }, (_, i) => i + 1);
7893
7894 return [Link](sortedArr) === [Link](expectedArray);
7895 }
7896 </script>
7897
7898 <!-- Question 124 -->
7899 <h3>Question 124:</h3>
7900 <p>
7901 Write a JavaScript program to create the value of NOR of two given
7902 booleans.
7903 </p>
7904
7905 <!-- Answer 124 -->
7906 <script>
7907 function logicalNor(x, y) {
7908 return !(x || y);
7909 }
7910 </script>
7911
7912 <!-- Question 125 -->
7913 <h3>Question 125:</h3>
7914 <p>
7915 Write a JavaScript program to find the longest string from a given array.
7916 </p>
7917
7918 <!-- Answer 125 -->
7919 <script>
7920 function findLongestString(arr) {
7921 return [Link](
7922 (longest, current) =>
7923 [Link] > [Link] ? current : longest,
7924 ""
7925 );
7926 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 133/298
1/31/24, 9:21 AM [Link]
7927 </script>
7928 <!-- Question 126 -->
7929 <h3>Question 126:</h3>
7930 <p>
7931 Write a JavaScript program to get the largest even number from an array of
7932 integers.
7933 </p>
7934
7935 <!-- Answer 126 -->
7936 <script>
7937 function largestEvenNumber(arr) {
7938 const evenNumbers = [Link]((num) => num % 2 === 0);
7939 return [Link](...evenNumbers);
7940 }
7941 </script>
7942
7943 <!-- Question 127 -->
7944 <h3>Question 127:</h3>
7945 <p>
7946 Write a JavaScript program to reverse the order of the bits in a given
7947 integer.
7948 </p>
7949
7950 <!-- Answer 127 -->
7951 <script>
7952 function reverseBits(num) {
7953 return parseInt([Link](2).split("").reverse().join(""), 2);
7954 }
7955 </script>
7956
7957 <!-- Question 128 -->
7958 <h3>Question 128:</h3>
7959 <p>
7960 Write a JavaScript program to find the smallest round number that is not
7961 less than a given value.
7962 </p>
7963
7964 <!-- Answer 128 -->
7965 <script>
7966 function smallestRoundNumber(value) {
7967 while (value % 10 !== 0) {
7968 value++;
7969 }
7970 return value;
7971 }
7972 </script>
7973
7974 <!-- Question 129 -->
7975 <h3>Question 129:</h3>
7976 <p>
7977 Write a JavaScript program to find the smallest prime number strictly
7978 greater than a given number.
7979 </p>
7980
7981 <!-- Answer 129 -->
7982 <script>
7983 function isPrime(num) {
7984 if (num <= 1) return false;
7985 for (let i = 2; i <= [Link](num); i++) {
7986 if (num % i === 0) return false;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 134/298
1/31/24, 9:21 AM [Link]
7987 }
7988 return true;
7989 }
7990
7991 function smallestPrimeGreaterThan(value) {
7992 let currentNum = value + 1;
7993 while (!isPrime(currentNum)) {
7994 currentNum++;
7995 }
7996 return currentNum;
7997 }
7998 </script>
7999
8000 <!-- Question 130 -->
8001 <h3>Question 130:</h3>
8002 <p>
8003 Write a JavaScript program to find the number of even digits in a given
8004 integer.
8005 </p>
8006
8007 <!-- Answer 130 -->
8008 <script>
8009 function countEvenDigits(num) {
8010 const numStr = [Link](num).toString();
8011 return [Link]("").filter((digit) => digit % 2 === 0).length;
8012 }
8013 </script>
8014 <!-- Question 131 -->
8015 <h3>Question 131:</h3>
8016 <p>
8017 Write a JavaScript program to create an array of prefix sums of the given
8018 array.
8019 </p>
8020
8021 <!-- Answer 131 -->
8022 <script>
8023 function prefixSums(arr) {
8024 let sum = 0;
8025 return [Link]((num) => (sum += num));
8026 }
8027 </script>
8028
8029 <!-- Question 132 -->
8030 <h3>Question 132:</h3>
8031 <p>
8032 Write a JavaScript program to find all distinct prime factors of a given
8033 integer.
8034 </p>
8035
8036 <!-- Answer 132 -->
8037 <script>
8038 function distinctPrimeFactors(num) {
8039 const factors = [];
8040 for (let i = 2; i <= [Link](num); i++) {
8041 while (num % i === 0) {
8042 if () {
8043 [Link](i);
8044 }
8045 num /= i;
8046 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 135/298
1/31/24, 9:21 AM [Link]
8047 }
8048 if (num > 1 && ) {
8049 [Link](num);
8050 }
8051 return factors;
8052 }
8053 </script>
8054
8055 <!-- Question 133 -->
8056 <h3>Question 133:</h3>
8057 <p>
8058 Write a JavaScript program to check whether a given fraction is proper or
8059 not.
8060 </p>
8061
8062 <!-- Answer 133 -->
8063 <script>
8064 function isProperFraction(numerator, denominator) {
8065 return numerator < denominator && numerator >= 0 && denominator > 0;
8066 }
8067 </script>
8068
8069 <!-- Question 134 -->
8070 <h3>Question 134:</h3>
8071 <p>
8072 Write a JavaScript program to change the characters (lower case) in a
8073 string where a turns into z, b turns into y, c turns into x, ..., n turns
8074 into m, m turns into n, ..., z turns into a.
8075 </p>
8076
8077 <!-- Answer 134 -->
8078 <script>
8079 function transformString(str) {
8080 const transformed = [Link](/[a-z]/g, (char) =>
8081 [Link](219 - [Link](0))
8082 );
8083 return transformed;
8084 }
8085 </script>
8086
8087 <!-- Question 135 -->
8088 <h3>Question 135:</h3>
8089 <p>
8090 Write a JavaScript program to remove all characters from a given string
8091 that appear more than once.
8092 </p>
8093
8094 <!-- Answer 135 -->
8095 <script>
8096 function removeDuplicates(str) {
8097 const charCount = {};
8098 let result = "";
8099
8100 for (const char of str) {
8101 charCount[char] = (charCount[char] || 0) + 1;
8102 if (charCount[char] === 1) {
8103 result += char;
8104 }
8105 }
8106
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 136/298
1/31/24, 9:21 AM [Link]
8107 return result;
8108 }
8109 </script>
8110
8111 <!-- Question 136 -->
8112 <h3>Question 136:</h3>
8113 <p>
8114 Write a JavaScript program to replace the first digit in a string (should
8115 contain at least one digit) with $ character.
8116 </p>
8117
8118 <!-- Answer 136 -->
8119 <script>
8120 function replaceFirstDigit(str) {
8121 return [Link](/\d/, "$");
8122 }
8123 </script>
8124
8125 <!-- Question 137 -->
8126 <h3>Question 137:</h3>
8127 <p>
8128 Write a JavaScript program to test whether a given integer is greater than
8129 15. Return the given number, otherwise return 15.
8130 </p>
8131
8132 <!-- Answer 137 -->
8133 <script>
8134 function checkNumber(num) {
8135 return num > 15 ? num : 15;
8136 }
8137 </script>
8138
8139 <!-- Question 138 -->
8140 <h3>Question 138:</h3>
8141 <p>
8142 Write a JavaScript program to reverse the bits of a given 16 bits unsigned
8143 short integer.
8144 </p>
8145
8146 <!-- Answer 138 -->
8147 <script>
8148 function reverseBitsShortInteger(num) {
8149 return parseInt(
8150 [Link](2).padStart(16, "0").split("").reverse().join(""),
8151 2
8152 );
8153 }
8154 </script>
8155
8156 <!-- Question 139 -->
8157 <h3>Question 139:</h3>
8158 <p>
8159 Write a JavaScript program to find the position of a rightmost round
8160 number in an array of integers. Returns 0 if there are no round numbers.
8161 </p>
8162
8163 <!-- Answer 139 -->
8164 <script>
8165 function rightmostRoundNumberPosition(arr) {
8166 for (let i = [Link] - 1; i >= 0; i--) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 137/298
1/31/24, 9:21 AM [Link]
8167 if (arr[i] % 10 === 0) {
8168 return i + 1;
8169 }
8170 }
8171 return 0;
8172 }
8173 </script>
8174
8175 <!-- Question 140 -->
8176 <h3>Question 140:</h3>
8177 <p>
8178 Write a JavaScript program to check whether all the digits in a given
8179 number are the same or not.
8180 </p>
8181
8182 <!-- Answer 140 -->
8183 <script>
8184 function areAllDigitsSame(num) {
8185 const digits = [Link]().split("");
8186 return [Link]((digit) => digit === digits[0]);
8187 }
8188 </script>
8189
8190 <!-- Question 141 -->
8191 <h3>Question 141:</h3>
8192 <p>
8193 Write a JavaScript program to find the number of elements which present in
8194 both of the given arrays.
8195 </p>
8196
8197 <!-- Answer 141 -->
8198 <script>
8199 function commonElementsCount(arr1, arr2) {
8200 const set1 = new Set(arr1);
8201 const set2 = new Set(arr2);
8202 return [...set1].filter((item) => [Link](item)).length;
8203 }
8204 </script>
8205
8206 <!-- Question 142 -->
8207 <h3>Question 142:</h3>
8208 <p>
8209 Write a JavaScript program to simplify a given absolute path for a file in
8210 Unix-style.
8211 </p>
8212
8213 <!-- Answer 142 -->
8214 <script>
8215 function simplifyAbsolutePath(path) {
8216 const parts = [Link]("/");
8217 const result = [];
8218
8219 for (const part of parts) {
8220 if (part === "..") {
8221 [Link]();
8222 } else if (part && part !== ".") {
8223 [Link](part);
8224 }
8225 }
8226
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 138/298
1/31/24, 9:21 AM [Link]
8227 return "/" + [Link]("/");
8228 }
8229 </script>
8230
8231 <!-- Question 143 -->
8232 <h3>Question 143:</h3>
8233 <p>
8234 Write a JavaScript program to sort the strings of a given array of strings
8235 in the order of increasing lengths. Note: Do not change the order if the
8236 lengths of two strings are the same.
8237 </p>
8238
8239 <!-- Answer 143 -->
8240 <script>
8241 function sortStringsByLengths(arr) {
8242 return [Link]((a, b) => [Link] - [Link]);
8243 }
8244 </script>
8245
8246 <!-- Question 144 -->
8247 <h3>Question 144:</h3>
8248 <p>
8249 Write a JavaScript program to break an address of a URL and put its parts
8250 into an array.
8251 </p>
8252
8253 <!-- Answer 144 -->
8254 <script>
8255 function breakUrlAddress(url) {
8256 return [Link]("/");
8257 }
8258 </script>
8259
8260 <!-- Question 145 -->
8261 <h3>Question 145:</h3>
8262 <p>
8263 Write a JavaScript program to find the maximum integer n such that 1 + 2 +
8264 ... + n <= a given integer.
8265 </p>
8266
8267 <!-- Answer 145 -->
8268 <script>
8269 function maxNForSumLessThanEqual(a) {
8270 let n = 1;
8271 while ((n * (n + 1)) / 2 <= a) {
8272 n++;
8273 }
8274 return n - 1;
8275 }
8276 </script>
8277
8278 <!-- Question 146 -->
8279 <h3>Question 146:</h3>
8280 <p>
8281 Write a JavaScript program to compute the sum of cubes of all integers
8282 from 1 to a given integer.
8283 </p>
8284
8285 <!-- Answer 146 -->
8286 <script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 139/298
1/31/24, 9:21 AM [Link]
8287 function sumOfCubes(n) {
8288 return ((n * (n + 1)) / 2) ** 2;
8289 }
8290 </script>
8291
8292 <!-- Question 147 -->
8293 <h3>Question 147:</h3>
8294 <p>
8295 Write a JavaScript program to compute the sum of all digits that occur in
8296 a given string.
8297 </p>
8298
8299 <!-- Answer 147 -->
8300 <script>
8301 function sumOfDigitsInString(str) {
8302 return str
8303 .replace(/\D/g, "")
8304 .split("")
8305 .reduce((sum, digit) => sum + parseInt(digit), 0);
8306 }
8307 </script>
8308
8309 <!-- Question 148 -->
8310 <h3>Question 148:</h3>
8311 <p>
8312 Write a JavaScript program to swap two halves of a given array of integers
8313 of even length.
8314 </p>
8315
8316 <!-- Answer 148 -->
8317 <script>
8318 function swapArrayHalves(arr) {
8319 const mid = [Link] / 2;
8320 return [...[Link](mid), ...[Link](0, mid)];
8321 }
8322 </script>
8323
8324 <!-- Question 149 -->
8325 <h3>Question 149:</h3>
8326 <p>
8327 Write a JavaScript program to change the capitalization of all letters in
8328 a given string.
8329 </p>
8330
8331 <!-- Answer 149 -->
8332 <script>
8333 function changeCapitalization(str) {
8334 return str
8335 .split("")
8336 .map((char) =>
8337 char === [Link]()
8338 ? [Link]()
8339 : [Link]()
8340 )
8341 .join("");
8342 }
8343 </script>
8344
8345 <!-- Question 150 -->
8346 <h3>Question 150:</h3>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 140/298
1/31/24, 9:21 AM [Link]
8347 <p>
8348 Write a JavaScript program to swap pairs of adjacent digits of a given
8349 integer of even length.
8350 </p>
8351
8352 <!-- Answer 150 -->
8353 <script>
8354 function swapAdjacentDigits(num) {
8355 const digits = [Link]().split("");
8356 for (let i = 0; i < [Link]; i += 2) {
8357 const temp = digits[i];
8358 digits[i] = digits[i + 1];
8359 digits[i + 1] = temp;
8360 }
8361 return parseInt([Link](""));
8362 }
8363 </script>
8364 <!-- Question 151 -->
8365 <h3>Question 151:</h3>
8366 <p>
8367 Write a JavaScript program to compare two objects to determine if the
8368 first one contains equivalent property values to the second one.
8369 </p>
8370
8371 <!-- Answer 151 -->
8372 <script>
8373 function compareObjects(obj1, obj2) {
8374 const keys1 = [Link](obj1);
8375 const keys2 = [Link](obj2);
8376
8377 if ([Link] !== [Link]) {
8378 return false;
8379 }
8380
8381 for (const key of keys1) {
8382 if (obj1[key] !== obj2[key]) {
8383 return false;
8384 }
8385 }
8386
8387 return true;
8388 }
8389 </script>
8390
8391 <!-- Question 152 -->
8392 <h3>Question 152:</h3>
8393 <p>Write a JavaScript program to copy a string to the clipboard.</p>
8394
8395 <!-- Answer 152 -->
8396 <script>
8397 function copyToClipboard(str) {
8398 const textarea = [Link]("textarea");
8399 [Link] = str;
8400 [Link](textarea);
8401 [Link]();
8402 [Link]("copy");
8403 [Link](textarea);
8404 }
8405 </script>
8406
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 141/298
1/31/24, 9:21 AM [Link]
8407 <!-- Question 153 -->
8408 <h3>Question 153:</h3>
8409 <p>
8410 Write a JavaScript program to convert a comma-separated values (CSV)
8411 string to a 2D array.
8412 </p>
8413
8414 <!-- Answer 153 -->
8415 <script>
8416 function csvToArray(csvString) {
8417 return [Link]("\n").map((row) => [Link](","));
8418 }
8419 </script>
8420
8421 <!-- Question 154 -->
8422 <h3>Question 154:</h3>
8423 <p>
8424 Write a JavaScript program to convert a comma-separated values (CSV)
8425 string to a 2D array of objects. The first row of the string is used as
8426 the title row.
8427 </p>
8428
8429 <!-- Answer 154 -->
8430 <script>
8431 function csvToObjectArray(csvString) {
8432 const rows = [Link]("\n");
8433 const titles = [Link]().split(",");
8434 return [Link]((row) => {
8435 const values = [Link](",");
8436 const obj = {};
8437 [Link]((title, i) => (obj[title] = values[i]));
8438 return obj;
8439 });
8440 }
8441 </script>
8442
8443 <!-- Question 155 -->
8444 <h3>Question 155:</h3>
8445 <p>
8446 Write a JavaScript program to convert an array of objects to a
8447 comma-separated values (CSV) string that contains only the columns
8448 specified.
8449 </p>
8450
8451 <!-- Answer 155 -->
8452 <script>
8453 function objectsToCsv(objects, columns) {
8454 const csvArray = [Link]((obj) =>
8455 [Link]((col) => obj[col]).join(",")
8456 );
8457 return [Link]("\n");
8458 }
8459 </script>
8460
8461 <!-- Question 156 -->
8462 <h3>Question 156:</h3>
8463 <p>
8464 Write a JavaScript program to target a given value in a nested JSON
8465 object, based on the given key.
8466 </p>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 142/298
1/31/24, 9:21 AM [Link]
8467
8468 <!-- Answer 156 -->
8469 <script>
8470 function getValueByKey(obj, key) {
8471 for (const prop in obj) {
8472 if (prop === key) {
8473 return obj[prop];
8474 } else if (typeof obj[prop] === "object") {
8475 const result = getValueByKey(obj[prop], key);
8476 if (result !== undefined) {
8477 return result;
8478 }
8479 }
8480 }
8481 }
8482 </script>
8483
8484 <!-- Question 157 -->
8485 <h3>Question 157:</h3>
8486 <p>
8487 Write a JavaScript program to converts a specified number to an array of
8488 digits.
8489 </p>
8490
8491 <!-- Answer 157 -->
8492 <script>
8493 function numberToDigits(num) {
8494 return [Link](String(num), Number);
8495 }
8496 </script>
8497
8498 <!-- Question 158 -->
8499 <h3>Question 158:</h3>
8500 <p>
8501 Write a JavaScript program to filter out the specified values from a
8502 specified array. Return the original array without the filtered values.
8503 </p>
8504
8505 <!-- Answer 158 -->
8506 <script>
8507 function filterValues(arr, valuesToFilter) {
8508 return [Link]((value) => );
8509 }
8510 </script>
8511
8512 <!-- Question 159 -->
8513 <h3>Question 159:</h3>
8514 <p>
8515 Write a JavaScript program to combine the numbers of a given array into an
8516 array containing all combinations.
8517 </p>
8518
8519 <!-- Answer 159 -->
8520 <script>
8521 function combineNumbers(arr) {
8522 const combinations = [];
8523 for (let i = 0; i < [Link]; i++) {
8524 for (let j = i + 1; j < [Link]; j++) {
8525 [Link]([arr[i], arr[j]]);
8526 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 143/298
1/31/24, 9:21 AM [Link]
8527 }
8528 return combinations;
8529 }
8530 </script>
8531
8532 <!-- Question 160 -->
8533 <h3>Question 160:</h3>
8534 <p>
8535 Write a JavaScript program to extract out the values at the specified
8536 indexes from a specified array.
8537 </p>
8538
8539 <!-- Answer 160 -->
8540 <script>
8541 function extractValuesAtIndexes(arr, indexes) {
8542 return [Link]((index) => arr[index]);
8543 }
8544 </script>
8545
8546 <!-- Question 161 -->
8547 <h3>Question 161:</h3>
8548 <p>
8549 Write a JavaScript program to generate a random hexadecimal color code.
8550 </p>
8551
8552 <!-- Answer 161 -->
8553 <script>
8554 function randomHexColor() {
8555 return "#" + [Link]([Link]() * 16777215).toString(16);
8556 }
8557 </script>
8558
8559 <!-- Question 162 -->
8560 <h3>Question 162:</h3>
8561 <p>
8562 Write a JavaScript program to remove non-printable ASCII characters from a
8563 given string.
8564 </p>
8565
8566 <!-- Answer 162 -->
8567 <script>
8568 function removeNonPrintableCharacters(str) {
8569 return [Link](/[^ -~]/g, "");
8570 }
8571 </script>
8572
8573 <!-- Question 163 -->
8574 <h3>Question 163:</h3>
8575 <p>
8576 Write a JavaScript program to convert the length of a given string in
8577 bytes.
8578 </p>
8579
8580 <!-- Answer 163 -->
8581 <script>
8582 function stringLengthInBytes(str) {
8583 return new Blob([str]).size;
8584 }
8585 </script>
8586
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 144/298
1/31/24, 9:21 AM [Link]
8587 <!-- Question 164 -->
8588 <h3>Question 164:</h3>
8589 <p>
8590 Write a JavaScript program to replace the names of multiple object keys
8591 with the values provided.
8592 </p>
8593
8594 <!-- Answer 164 -->
8595 <script>
8596 function replaceKeysWithValues(obj, keyValues) {
8597 for (const key in keyValues) {
8598 if ([Link](key)) {
8599 obj[keyValues[key]] = obj[key];
8600 delete obj[key];
8601 }
8602 }
8603 }
8604 </script>
8605
8606 <!-- Question 165 -->
8607 <h3>Question 165:</h3>
8608 <p>
8609 Write a JavaScript program to return the minimum-maximum value of an
8610 array, after applying the provided function to set comparing rule.
8611 </p>
8612
8613 <!-- Answer 165 -->
8614 <script>
8615 function minMaxWithRule(arr, compareFunction) {
8616 return [[Link](...arr), [Link](...arr)].sort(compareFunction);
8617 }
8618 </script>
8619
8620 <!-- Question 166 -->
8621 <h3>Question 166:</h3>
8622 <p>
8623 Write a JavaScript function that returns true if the provided predicate
8624 function returns true for all elements in a collection, false otherwise.
8625 </p>
8626
8627 <!-- Answer 166 -->
8628 <script>
8629 function allTrue(collection, predicateFunction) {
8630 return [Link](predicateFunction);
8631 }
8632 </script>
8633
8634 <!-- Question 167 -->
8635 <h3>Question 167:</h3>
8636 <p>
8637 Write a JavaScript program to split values of two given arrays into two
8638 groups. If an element in the filter is truthy, the corresponding element
8639 in the collection belongs to the first group; otherwise, it belongs to the
8640 second group.
8641 </p>
8642
8643 <!-- Answer 167 -->
8644 <script>
8645 function splitArraysByFilter(collection, filter) {
8646 return [Link](
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 145/298
1/31/24, 9:21 AM [Link]
8647 (result, value, index) => {
8648 filter[index] ? result[0].push(value) : result[1].push(value);
8649 return result;
8650 },
8651 [[], []]
8652 );
8653 }
8654 </script>
8655
8656 <!-- Question 168 -->
8657 <h3>Question 168:</h3>
8658 <p>
8659 Write a JavaScript program to remove specified elements from the left of a
8660 given array of elements.
8661 </p>
8662
8663 <!-- Answer 168 -->
8664 <script>
8665 function removeLeftElements(arr, count) {
8666 return [Link](count);
8667 }
8668 </script>
8669
8670 <!-- Question 169 -->
8671 <h3>Question 169:</h3>
8672 <p>
8673 Write a JavaScript program to remove specified elements from the right of
8674 a given array of elements.
8675 </p>
8676
8677 <!-- Answer 169 -->
8678 <script>
8679 function removeRightElements(arr, count) {
8680 return [Link](0, -count);
8681 }
8682 </script>
8683
8684 <!-- Question 170 -->
8685 <h3>Question 170:</h3>
8686 <p>
8687 Write a JavaScript program to extend a 3-digit color code to a 6-digit
8688 color code.
8689 </p>
8690
8691 <!-- Answer 170 -->
8692 <script>
8693 function extendColorCode(colorCode) {
8694 return [Link] === 3
8695 ? colorCode
8696 .split("")
8697 .map((char) => [Link](2))
8698 .join("")
8699 : colorCode;
8700 }
8701 </script>
8702
8703 <!-- Question 171 -->
8704 <h3>Question 171:</h3>
8705 <p>Write a JavaScript program to get every nth element in a given array.</p>
8706
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 146/298
1/31/24, 9:21 AM [Link]
8707 <!-- Answer 171 -->
8708 <script>
8709 function getEveryNthElement(arr, n) {
8710 return [Link]((_, index) => (index + 1) % n === 0);
8711 }
8712 </script>
8713
8714 <!-- Question 172 -->
8715 <h3>Question 172:</h3>
8716 <p>
8717 Write a JavaScript program to filter out the non-unique values in an
8718 array.
8719 </p>
8720
8721 <!-- Answer 172 -->
8722 <script>
8723 function filterNonUniqueValues(arr) {
8724 return [Link](
8725 (value, index, array) =>
8726 [Link](value) === [Link](value)
8727 );
8728 }
8729 </script>
8730
8731 <!-- Question 173 -->
8732 <h3>Question 173:</h3>
8733 <p>
8734 Write a JavaScript program to filter out the non-unique values in an
8735 array, based on a provided comparator function.
8736 </p>
8737
8738 <!-- Answer 173 -->
8739 <script>
8740 function filterNonUniqueValuesWithComparator(arr, comparator) {
8741 return [Link](
8742 (value, index, array) =>
8743 [Link]((item) => comparator(value, item)) ===
8744 [Link](value)
8745 );
8746 }
8747 </script>
8748
8749 <!-- Question 174 -->
8750 <h3>Question 174:</h3>
8751 <p>
8752 Write a JavaScript program to dcapitalize the first letter of a string.
8753 </p>
8754
8755 <!-- Answer 174 -->
8756 <script>
8757 function dcapitalizeFirstLetter(str) {
8758 return [Link](0).toLowerCase() + [Link](1);
8759 }
8760 </script>
8761
8762 <!-- Question 175 -->
8763 <h3>Question 175:</h3>
8764 <p>
8765 Write a JavaScript program to create a new array out of the two supplied
8766 by creating each possible pair from the arrays.
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 147/298
1/31/24, 9:21 AM [Link]
8767 </p>
8768
8769 <!-- Answer 175 -->
8770 <script>
8771 function createPossiblePairs(arr1, arr2) {
8772 return [Link]((item1) => [Link]((item2) => [item1, item2]));
8773 }
8774 </script>
8775
8776 <!-- Question 176 -->
8777 <h3>Question 176:</h3>
8778 <p>
8779 Write a JavaScript program that will return true if the string is y/yes or
8780 false if the string is n/no.
8781 </p>
8782
8783 <!-- Answer 176 -->
8784 <script>
8785 function isYesOrNo(str) {
8786 const lowerStr = [Link]();
8787 return lowerStr === "y" || lowerStr === "yes";
8788 }
8789 </script>
8790
8791 <!-- Question 177 -->
8792 <h3>Question 177:</h3>
8793 <p>
8794 Write a JavaScript program to find every element that exists in any of the
8795 two given arrays once, using a provided comparator function.
8796 </p>
8797
8798 <!-- Answer 177 -->
8799 <script>
8800 function findUniqueElementsWithComparator(arr1, arr2, comparator) {
8801 return arr1
8802 .concat(arr2)
8803 .filter(
8804 (value, index, array) =>
8805 [Link](0, index).every((item) => !comparator(value, item)) &&
8806 [Link](index + 1).every((item) => !comparator(value, item))
8807 );
8808 }
8809 </script>
8810
8811 <!-- Question 178 -->
8812 <h3>Question 178:</h3>
8813 <p>
8814 Write a JavaScript program to measure the time taken by a function to
8815 execute.
8816 </p>
8817
8818 <!-- Answer 178 -->
8819 <script>
8820 function measureExecutionTime(func) {
8821 const startTime = [Link]();
8822 func();
8823 const endTime = [Link]();
8824 return endTime - startTime;
8825 }
8826 </script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 148/298
1/31/24, 9:21 AM [Link]
8827
8828 <!-- Question 179 -->
8829 <h3>Question 179:</h3>
8830 <p>Write a JavaScript program to convert a value to a safe integer.</p>
8831
8832 <!-- Answer 179 -->
8833 <script>
8834 function toSafeInteger(value) {
8835 const safeInt = [Link](Number(value));
8836 return [Link](safeInt) ? safeInt : 0;
8837 }
8838 </script>
8839
8840 <!-- Question 180 -->
8841 <h3>Question 180:</h3>
8842 <p>
8843 Write a JavaScript program to filter out the element(s) of a given array,
8844 that have one of the specified values.
8845 </p>
8846
8847 <!-- Answer 180 -->
8848 <script>
8849 function filterElementsByValues(arr, valuesToFilter) {
8850 return [Link]((value) => );
8851 }
8852 </script>
8853
8854 <!-- Question 181 -->
8855 <h3>Question 181:</h3>
8856 <p>
8857 Write a JavaScript program to find all elements in a given array except
8858 for the first one. Return the whole array if the array's length is 1.
8859 </p>
8860
8861 <!-- Answer 181 -->
8862 <script>
8863 function getAllExceptFirst(arr) {
8864 return [Link] > 1 ? [Link](1) : arr;
8865 }
8866 </script>
8867
8868 <!-- Question 182 -->
8869 <h3>Question 182:</h3>
8870 <p>
8871 Write a JavaScript program to get the sum of a given array, after mapping
8872 each element to a value using the provided function.
8873 </p>
8874
8875 <!-- Answer 182 -->
8876 <script>
8877 function sumAfterMapping(arr, mappingFunction) {
8878 return [Link](mappingFunction).reduce((sum, value) => sum + value, 0);
8879 }
8880 </script>
8881
8882 <!-- Question 183 -->
8883 <h3>Question 183:</h3>
8884 <p>
8885 Write a JavaScript program to get a random number in the specified range.
8886 </p>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 149/298
1/31/24, 9:21 AM [Link]
8887
8888 <!-- Answer 183 -->
8889 <script>
8890 function getRandomNumberInRange(min, max) {
8891 return [Link]() * (max - min) + min;
8892 }
8893 </script>
8894
8895 <!-- Question 184 -->
8896 <h3>Question 184:</h3>
8897 <p>
8898 Write a JavaScript program to get a random integer in the specified range.
8899 </p>
8900
8901 <!-- Answer 184 -->
8902 <script>
8903 function getRandomIntegerInRange(min, max) {
8904 return [Link]([Link]() * (max - min + 1)) + min;
8905 }
8906 </script>
8907
8908 <!-- Question 185 -->
8909 <h3>Question 185:</h3>
8910 <p>
8911 Write a JavaScript program to get an array of given n random integers in
8912 the specified range.
8913 </p>
8914
8915 <!-- Answer 185 -->
8916 <script>
8917 function getArrayOfRandomIntegers(n, min, max) {
8918 return [Link]({ length: n }, () =>
8919 getRandomIntegerInRange(min, max)
8920 );
8921 }
8922 </script>
8923
8924 <!-- Question 186 -->
8925 <h3>Question 186:</h3>
8926 <p>
8927 Write a JavaScript program to create a function that invokes each provided
8928 function with the arguments it receives and returns the results.
8929 </p>
8930
8931 <!-- Answer 186 -->
8932 <script>
8933 function invokeFunctions(...functions) {
8934 return function (...args) {
8935 return [Link]((func) => func(...args));
8936 };
8937 }
8938 </script>
8939
8940 <!-- Question 187 -->
8941 <h3>Question 187:</h3>
8942 <p>
8943 Write a JavaScript program to get a sorted array of objects ordered by
8944 properties and orders.
8945 </p>
8946
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 150/298
1/31/24, 9:21 AM [Link]
8947 <!-- Answer 187 -->
8948 <script>
8949 function sortArrayOfObjects(arr, orders) {
8950 return [Link]((a, b) => {
8951 for (const order of orders) {
8952 const prop = order[0];
8953 const sortOrder = order[1] === "asc" ? 1 : -1;
8954 if (a[prop] < b[prop]) return -sortOrder;
8955 if (a[prop] > b[prop]) return sortOrder;
8956 }
8957 return 0;
8958 });
8959 }
8960 </script>
8961
8962 <!-- Question 188 -->
8963 <h3>Question 188:</h3>
8964 <p>
8965 Write a JavaScript program to pad a string on both sides with the
8966 specified character, if it's shorter than the specified length.
8967 </p>
8968
8969 <!-- Answer 188 -->
8970 <script>
8971 function padString(str, length, char) {
8972 const padding = [Link]([Link](0, length - [Link]));
8973 return (
8974 [Link](0, [Link]([Link] / 2)) +
8975 str +
8976 [Link]([Link]([Link] / 2))
8977 );
8978 }
8979 </script>
8980
8981 <!-- Question 189 -->
8982 <h3>Question 189:</h3>
8983 <p>
8984 Write a JavaScript program to remove the key-value pairs corresponding to
8985 the given keys from an object.
8986 </p>
8987
8988 <!-- Answer 189 -->
8989 <script>
8990 function removeKeyValues(obj, keysToRemove) {
8991 for (const key of keysToRemove) {
8992 delete obj[key];
8993 }
8994 }
8995 </script>
8996
8997 <!-- Question 190 -->
8998 <h3>Question 190:</h3>
8999 <p>
9000 Write a JavaScript program to create an array of key-value pair arrays
9001 from a given object.
9002 </p>
9003
9004 <!-- Answer 190 -->
9005 <script>
9006 function objectToArrayOfArrays(obj) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 151/298
1/31/24, 9:21 AM [Link]
9007 return [Link](obj);
9008 }
9009 </script>
9010 <!-- Question 191 -->
9011 <h3>Question 191:</h3>
9012 <p>
9013 Write a JavaScript program to create an object from the given key-value
9014 pairs.
9015 </p>
9016
9017 <!-- Answer 191 -->
9018 <script>
9019 function createObjectFromKeyValuePairs(keyValuePairs) {
9020 return [Link](keyValuePairs);
9021 }
9022 </script>
9023
9024 <!-- Question 192 -->
9025 <h3>Question 192:</h3>
9026 <p>
9027 Write a JavaScript program to get a customized coalesce function that
9028 returns the first argument that returns true from the provided argument
9029 validation function.
9030 </p>
9031
9032 <!-- Answer 192 -->
9033 <script>
9034 function getCustomizedCoalesce(validationFunction) {
9035 return (...args) => [Link](validationFunction);
9036 }
9037 </script>
9038
9039 <!-- Question 193 -->
9040 <h3>Question 193:</h3>
9041 <p>
9042 Write a JavaScript program to change a function that accepts an array into
9043 a variadic function.
9044 </p>
9045
9046 <!-- Answer 193 -->
9047 <script>
9048 function arrayToVariadicFunction(func) {
9049 return (...args) => func(args);
9050 }
9051 </script>
9052
9053 <!-- Question 194 -->
9054 <h3>Question 194:</h3>
9055 <p>
9056 Write a JavaScript program to remove falsey values from a given array.
9057 </p>
9058
9059 <!-- Answer 194 -->
9060 <script>
9061 function removeFalseyValues(arr) {
9062 return [Link](Boolean);
9063 }
9064 </script>
9065
9066 <!-- Question 195 -->
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 152/298
1/31/24, 9:21 AM [Link]
9067 <h3>Question 195:</h3>
9068 <p>
9069 Write a JavaScript program to split values into two groups. If an element
9070 in filter is truthy, the corresponding element in the collection belongs
9071 to the first group; otherwise, it belongs to the second group.
9072 </p>
9073
9074 <!-- Answer 195 -->
9075 <script>
9076 function splitValuesIntoTwoGroups(collection, filter) {
9077 return [Link](
9078 (result, value, index) => {
9079 filter[index] ? result[0].push(value) : result[1].push(value);
9080 return result;
9081 },
9082 [[], []]
9083 );
9084 }
9085 </script>
9086
9087 <!-- Question 196 -->
9088 <h3>Question 196:</h3>
9089 <p>Write a JavaScript program to curry (curries) a function.</p>
9090
9091 <!-- Answer 196 -->
9092 <script>
9093 function curry(func) {
9094 return function curried(...args) {
9095 if ([Link] >= [Link]) {
9096 return func(...args);
9097 } else {
9098 return function (...moreArgs) {
9099 return curried(...args, ...moreArgs);
9100 };
9101 }
9102 };
9103 }
9104 </script>
9105
9106 <!-- Question 197 -->
9107 <h3>Question 197:</h3>
9108 <p>
9109 Write a JavaScript program to perform a deep comparison between two values
9110 to determine if they are equivalent.
9111 </p>
9112
9113 <!-- Answer 197 -->
9114 <script>
9115 function deepEqual(a, b) {
9116 if (a === b) return true;
9117
9118 if (
9119 typeof a !== "object" ||
9120 typeof b !== "object" ||
9121 a === null ||
9122 b === null
9123 )
9124 return false;
9125
9126 const keysA = [Link](a);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 153/298
1/31/24, 9:21 AM [Link]
9127 const keysB = [Link](b);
9128
9129 if ([Link] !== [Link]) return false;
9130
9131 for (const key of keysA) {
9132 if ( || !deepEqual(a[key], b[key])) return false;
9133 }
9134
9135 return true;
9136 }
9137 </script>
9138
9139 <!-- Question 198 -->
9140 <h3>Question 198:</h3>
9141 <p>
9142 Write a JavaScript program to get an array of function property names from
9143 own (and optionally inherited) enumerable properties of an object.
9144 </p>
9145
9146 <!-- Answer 198 -->
9147 <script>
9148 function getFunctionPropertyNames(obj, includeInherited = false) {
9149 const propertyNames = [];
9150
9151 for (const key in obj) {
9152 if (typeof obj[key] === "function") {
9153 [Link](key);
9154 }
9155 }
9156
9157 if (includeInherited) {
9158 const prototype = [Link](obj);
9159 if (prototype) {
9160 [Link](...getFunctionPropertyNames(prototype, true));
9161 }
9162 }
9163
9164 return propertyNames;
9165 }
9166 </script>
9167
9168 <!-- Question 199 -->
9169 <h3>Question 199:</h3>
9170 <p>
9171 Write a JavaScript program to retrieve a set of properties indicated by
9172 the given selectors from an object.
9173 </p>
9174
9175 <!-- Answer 199 -->
9176 <script>
9177 function retrievePropertiesBySelectors(obj, selectors) {
9178 const result = {};
9179 [Link]((selector) => {
9180 if ([Link](selector)) {
9181 result[selector] = obj[selector];
9182 }
9183 });
9184 return result;
9185 }
9186 </script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 154/298
1/31/24, 9:21 AM [Link]
9187
9188 <!-- Question 200 -->
9189 <h3>Question 200:</h3>
9190 <p>
9191 Write a JavaScript program to convert an integer to a suffixed string,
9192 adding am or pm based on its value.
9193 </p>
9194
9195 <!-- Answer 200 -->
9196 <script>
9197 function convertIntegerToSuffixedString(integer) {
9198 const suffix = integer < 12 ? "am" : "pm";
9199 return integer % 12 || 12 + suffix;
9200 }
9201 </script>
9202 <!-- ----------------------------- 401 ----------------------- -->
9203
9204 <h4>[Link] a JavaScript program to write a JSON object to a file</h4>
9205 <script>
9206 const fs = require("fs");
9207
9208 // Sample JSON object
9209 const jsonObject = {
9210 name: "John Doe",
9211 age: 30,
9212 city: "New York",
9213 };
9214
9215 // Convert JSON object to a string
9216 const jsonString = [Link](jsonObject);
9217
9218 // File path where you want to write the JSON data
9219 const filePath = "[Link]";
9220
9221 // Write JSON data to file
9222 [Link](filePath, jsonString, (err) => {
9223 if (err) {
9224 [Link]("Error writing JSON to file:", err);
9225 return;
9226 }
9227 [Link]("JSON data has been written to", filePath);
9228 });
9229 </script>
9230 <hr />
9231
9232 <h4>[Link] a JavaScript program to write a JSON object to a file.</h4>
9233 <script>
9234 // Sample JSON object
9235 const jsonObject = {
9236 name: "John Doe",
9237 age: 30,
9238 city: "New York",
9239 };
9240
9241 // Convert JSON object to a string
9242 const jsonString = [Link](jsonObject);
9243
9244 // Create a Blob object with JSON string
9245 const blob = new Blob([jsonString], { type: "application/json" });
9246
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 155/298
1/31/24, 9:21 AM [Link]
9247 // Create a temporary URL for the Blob
9248 const url = [Link](blob);
9249
9250 // Create a link element
9251 const link = [Link]("a");
9252
9253 // Set link's href attribute to the temporary URL
9254 [Link] = url;
9255
9256 // Set link's download attribute to specify the filename
9257 [Link] = "[Link]";
9258
9259 // Append the link to the document body
9260 [Link](link);
9261
9262 // Click the link programmatically to trigger the download
9263 [Link]();
9264
9265 // Cleanup: remove the link and revoke the URL
9266 [Link](link);
9267 [Link](url);
9268 </script>
9269 <hr />
9270
9271 <h4>
9272 [Link] a JavaScript program to convert the values of RGB components to
9273 a color code.
9274 </h4>
9275 <script>
9276 // Function to convert decimal to hexadecimal
9277 function decimalToHex(decimal) {
9278 const hex = [Link](16);
9279 return [Link] === 1 ? "0" + hex : hex;
9280 }
9281
9282 // Function to convert RGB components to a color code
9283 function rgbToColorCode(red, green, blue) {
9284 // Convert each RGB component to hexadecimal
9285 const redHex = decimalToHex(red);
9286 const greenHex = decimalToHex(green);
9287 const blueHex = decimalToHex(blue);
9288
9289 // Concatenate the hexadecimal values
9290 const colorCode = "#" + redHex + greenHex + blueHex;
9291
9292 return colorCode;
9293 }
9294
9295 // Example usage:
9296 const red = 255;
9297 const green = 165;
9298 const blue = 0;
9299
9300 const colorCode = rgbToColorCode(red, green, blue);
9301 [Link](colorCode); // Output: #ffa500
9302 </script>
9303 <hr />
9304
9305 <h4>[Link] a JavaScript program to generate a UUID in a browser.</h4>
9306 <script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 156/298
1/31/24, 9:21 AM [Link]
9307 function generateUUID() {
9308 // Generate random bytes
9309 const buffer = new Uint8Array(16);
9310 [Link](buffer);
9311
9312 // Set version (4) and variant (2)
9313 buffer[6] = (buffer[6] & 0x0f) | 0x40;
9314 buffer[8] = (buffer[8] & 0x3f) | 0x80;
9315
9316 // Convert buffer to UUID string
9317 const hexCodes = [Link](buffer).map((byte) =>
9318 [Link](16).padStart(2, "0")
9319 );
9320 const uuid = [
9321 [Link](0, 4).join(""),
9322 [Link](4, 6).join(""),
9323 [Link](6, 8).join(""),
9324 [Link](8, 10).join(""),
9325 [Link](10).join(""),
9326 ].join("-");
9327
9328 return uuid;
9329 }
9330
9331 // Example usage:
9332 const uuid = generateUUID();
9333 [Link](uuid); // Output: a29b6144-8c60-4efb-a6f3-c3aebef5fd7d
9334 </script>
9335 <hr />
9336
9337 <h4>
9338 [Link] a JavaScript program to generate a UUID in [Link]. Use crypto
9339 API to generate a UUID, compliant with RFC4122 version 4.
9340 </h4>
9341 <script>
9342 const crypto = require("crypto");
9343
9344 function generateUUID() {
9345 const buffer = [Link](16);
9346
9347 // Set version (4) and variant (2)
9348 buffer[6] = (buffer[6] & 0x0f) | 0x40;
9349 buffer[8] = (buffer[8] & 0x3f) | 0x80;
9350
9351 const uuid = [
9352 [Link]("hex", 0, 4),
9353 [Link]("hex", 4, 6),
9354 [Link]("hex", 6, 8),
9355 [Link]("hex", 8, 10),
9356 [Link]("hex", 10),
9357 ].join("-");
9358
9359 return uuid;
9360 }
9361
9362 // Example usage:
9363 const uuid = generateUUID();
9364 [Link](uuid); // Output: a29b6144-8c60-4efb-a6f3-c3aebef5fd7d
9365 </script>
9366 <hr />
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 157/298
1/31/24, 9:21 AM [Link]
9367
9368 <h4>
9369 [Link] a JavaScript program that will return true if the provided
9370 predicate function returns true for at least one element in a collection,
9371 false otherwise
9372 </h4>
9373 <script>
9374 function some(collection, predicate) {
9375 // Iterate over each element in the collection
9376 for (const element of collection) {
9377 // If the predicate function returns true for any element, return true
9378 if (predicate(element)) {
9379 return true;
9380 }
9381 }
9382 // If no element satisfies the predicate, return false
9383 return false;
9384 }
9385
9386 // Example usage:
9387 const numbers = [1, 2, 3, 4, 5];
9388
9389 // Predicate function to check if a number is even
9390 function isEven(num) {
9391 return num % 2 === 0;
9392 }
9393
9394 // Check if there is at least one even number in the array
9395 [Link](some(numbers, isEven)); // Output: true
9396 </script>
9397 <hr />
9398
9399 <h4>
9400 [Link] a JavaScript program to check if two given numbers are
9401 approximately equal to each other.
9402 </h4>
9403 <script>
9404 function some(collection, predicate) {
9405 // Iterate over each element in the collection
9406 for (const element of collection) {
9407 // If the predicate function returns true for any element, return true
9408 if (predicate(element)) {
9409 return true;
9410 }
9411 }
9412 // If no element satisfies the predicate, return false
9413 return false;
9414 }
9415
9416 // Example usage:
9417 const numbers = [1, 2, 3, 4, 5];
9418
9419 // Predicate function to check if a number is even
9420 function isEven(num) {
9421 return num % 2 === 0;
9422 }
9423
9424 // Check if there is at least one even number in the array
9425 [Link](some(numbers, isEven)); // Output: true
9426 </script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 158/298
1/31/24, 9:21 AM [Link]
9427 <hr />
9428
9429 <h4>
9430 [Link] a JavaScript program to convert a 2D array to a comma-separated
9431 values (CSV) string.
9432 </h4>
9433 <script>
9434 function arrayToCSV(arr) {
9435 return [Link]((row) => [Link](",")).join("\n");
9436 }
9437
9438 // Example usage:
9439 const twoDArray = [
9440 ["Name", "Age", "City"],
9441 ["John", 30, "New York"],
9442 ["Alice", 25, "Los Angeles"],
9443 ["Bob", 35, "Chicago"],
9444 ];
9445
9446 const csvString = arrayToCSV(twoDArray);
9447 [Link](csvString);
9448 </script>
9449 <hr />
9450
9451 <h4>
9452 [Link] a JavaScript program to create a function that accepts up to n
9453 arguments, ignoring any additional arguments.
9454 </h4>
9455 <script>
9456 function acceptUpToN(...args) {
9457 return [Link](0, n);
9458 }
9459
9460 // Example usage:
9461 function sumUpToThree(a, b, c) {
9462 const [arg1, arg2, arg3] = acceptUpToN(a, b, c);
9463 return arg1 + arg2 + arg3;
9464 }
9465
9466 [Link](sumUpToThree(1, 2, 3)); // Output: 6
9467 [Link](sumUpToThree(1, 2, 3, 4)); // Output: 6 (ignores the fourth argument)
9468 </script>
9469 <hr />
9470
9471 <h4>
9472 [Link] a JavaScript program to decode a string of data which has been
9473 encoded using base-64 encoding
9474 </h4>
9475 <script>
9476 function decodeBase64(encodedString) {
9477 return atob(encodedString);
9478 }
9479
9480 // Example usage:
9481 const encodedString = "SGVsbG8gV29ybGQh"; // "Hello World!"
9482 const decodedString = decodeBase64(encodedString);
9483 [Link](decodedString); // Output: "Hello World!"
9484 </script>
9485 <hr />
9486
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 159/298
1/31/24, 9:21 AM [Link]
9487 <h4>
9488 [Link] a JavaScript program to evaluate the binomial coefficient of two
9489 integers n and k.
9490 </h4>
9491 <script>
9492 // Function to calculate the factorial of a number
9493 function factorial(n) {
9494 if (n === 0 || n === 1) {
9495 return 1;
9496 } else {
9497 return n * factorial(n - 1);
9498 }
9499 }
9500
9501 // Function to calculate the binomial coefficient
9502 function binomialCoefficient(n, k) {
9503 if (k < 0 || k > n) {
9504 return 0;
9505 } else {
9506 return factorial(n) / (factorial(k) * factorial(n - k));
9507 }
9508 }
9509
9510 // Example usage:
9511 const n = 5;
9512 const k = 2;
9513 const result = binomialCoefficient(n, k);
9514 [Link](`C(${n}, ${k}) = ${result}`);
9515 </script>
9516 <hr />
9517
9518 <h4>
9519 411. Write a JavaScript program that will return true if the bottom of the
9520 page is visible, false otherwise.
9521 </h4>
9522 <script>
9523 function isBottomVisible() {
9524 // Viewport height
9525 const windowHeight = [Link];
9526
9527 // Total height of the document
9528 const fullHeight = [Link];
9529
9530 // Vertical scroll position
9531 const scrollPosition =
9532 [Link] ||
9533 [Link] ||
9534 [Link];
9535
9536 // Check if the bottom of the page is visible
9537 return windowHeight + scrollPosition >= fullHeight;
9538 }
9539
9540 // Example usage:
9541 [Link]("scroll", function () {
9542 if (isBottomVisible()) {
9543 [Link]("Bottom of the page is visible");
9544 } else {
9545 [Link]("Bottom of the page is not visible");
9546 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 160/298
1/31/24, 9:21 AM [Link]
9547 });
9548 </script>
9549 <hr />
9550
9551 <h4>
9552 [Link] a JavaScript program to create a base-64 encoded ASCII string
9553 from a String object in which each character in the string is treated as a
9554 byte of binary data.
9555 </h4>
9556 <script>
9557 function stringToBase64(str) {
9558 // Using btoa() function to convert the string to base-64
9559 return btoa(unescape(encodeURIComponent(str)));
9560 }
9561
9562 // Example usage:
9563 const originalString = "Hello, world!";
9564 const base64String = stringToBase64(originalString);
9565 [Link]("Base64 encoded string:", base64String);
9566 </script>
9567 <hr />
9568
9569 <h4>
9570 [Link] a JavaScript program to capitalize the first letter of a string
9571 </h4>
9572 <script>
9573 function capitalizeFirstLetter(str) {
9574 // Check if the string is not empty
9575 if ([Link] === 0) {
9576 return str;
9577 }
9578 // Capitalize the first letter and concatenate it with the rest of the string
9579 return [Link](0).toUpperCase() + [Link](1);
9580 }
9581
9582 // Example usage:
9583 const originalString = "hello, world!";
9584 const capitalizedString = capitalizeFirstLetter(originalString);
9585 [Link]("Capitalized string:", capitalizedString);
9586 s;
9587 </script>
9588 <hr />
9589
9590 <h4>
9591 [Link] a JavaScript program to capitalize the first letter of every
9592 word in a string.
9593 </h4>
9594 <script>
9595 function capitalizeEveryWord(str) {
9596 // Split the string into words
9597 const words = [Link](" ");
9598 // Capitalize the first letter of each word
9599 const capitalizedWords = [Link](
9600 (word) => [Link](0).toUpperCase() + [Link](1)
9601 );
9602 // Join the capitalized words back into a single string
9603 return [Link](" ");
9604 }
9605
9606 // Example usage:
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 161/298
1/31/24, 9:21 AM [Link]
9607 const originalString = "hello world, how are you?";
9608 const capitalizedString = capitalizeEveryWord(originalString);
9609 [Link]("Capitalized string:", capitalizedString);
9610 </script>
9611 <hr />
9612
9613 <h4>
9614 [Link] a JavaScript program to chunk an array into smaller arrays of a
9615 specified size.
9616 </h4>
9617 <script>
9618 function chunkArray(array, size) {
9619 const chunkedArray = [];
9620 for (let i = 0; i < [Link]; i += size) {
9621 const chunk = [Link](i, i + size);
9622 [Link](chunk);
9623 }
9624 return chunkedArray;
9625 }
9626
9627 // Example usage:
9628 const originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
9629 const chunkSize = 3;
9630 const chunkedArray = chunkArray(originalArray, chunkSize);
9631 [Link]("Chunked Array:", chunkedArray);
9632 </script>
9633 <hr />
9634
9635 <h4>
9636 [Link] a JavaScript program to clamp a number within the inclusive
9637 range specified by the given boundary values a and b.
9638 </h4>
9639 <script>
9640 function clamp(number, min, max) {
9641 return [Link](min, [Link](number, max));
9642 }
9643
9644 // Example usage:
9645 const num = 5;
9646 const min = 1;
9647 const max = 10;
9648 const clampedNum = clamp(num, min, max);
9649 [Link]("Clamped Number:", clampedNum); // Output: 5
9650
9651 // Testing with values outside the range
9652 [Link]("Clamped Number:", clamp(15, min, max)); // Output: 10 (max)
9653 [Link]("Clamped Number:", clamp(-5, min, max)); // Output: 1 (min)
9654 </script>
9655 <hr />
9656
9657 <h4>
9658 [Link] a JavaScript function that reverse a number. Example x = 32243;
9659 Expected Output : 34223
9660 </h4>
9661 <script>
9662 function reverseNumber(num) {
9663 const reversed = parseInt([Link]().split("").reverse().join(""));
9664 return reversed * [Link](num);
9665 }
9666
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 162/298
1/31/24, 9:21 AM [Link]
9667 // Example usage:
9668 const x = 32243;
9669 const reversedX = reverseNumber(x);
9670 [Link]("Reversed Number:", reversedX); // Output: 34223
9671 </script>
9672 <hr />
9673
9674 <h4>
9675 [Link] a JavaScript function that checks whether a passed string is
9676 palindrome or not? A palindrome is word, phrase, or sequence that reads
9677 the same backward as forward, e.g., madam or nurses run
9678 </h4>
9679 <script>
9680 function isPalindrome(str) {
9681 // Remove non-alphanumeric characters and convert to lowercase
9682 const cleanStr = [Link]().replace(/[^a-z0-9]/g, "");
9683 // Compare the clean string with its reverse
9684 return cleanStr === [Link]("").reverse().join("");
9685 }
9686
9687 // Test the function
9688 const testString1 = "madam";
9689 [Link](testString1 + " is a palindrome:", isPalindrome(testString1)); //
Output: true
9690
9691 const testString2 = "nurses run";
9692 [Link](testString2 + " is a palindrome:", isPalindrome(testString2)); //
Output: true
9693
9694 const testString3 = "hello";
9695 [Link](testString3 + " is a palindrome:", isPalindrome(testString3)); //
Output: false
9696 </script>
9697 <hr />
9698
9699 <h4>
9700 [Link] a JavaScript function that generates all combinations of a
9701 string. Example string : 'dog' Expected Output : d,do,dog,o,og,g
9702 </h4>
9703 <script>
9704 function allCombinations(str) {
9705 const result = [];
9706
9707 // Recursive function to generate combinations
9708 function generateCombinations(prefix, remaining) {
9709 // Add the current prefix to the result
9710 [Link](prefix);
9711
9712 // Loop through the remaining characters
9713 for (let i = 0; i < [Link]; i++) {
9714 // Generate combinations with the current character removed
9715 generateCombinations(prefix + remaining[i], [Link](i + 1));
9716 }
9717 }
9718
9719 // Start the recursive process
9720 generateCombinations("", str);
9721
9722 return result;
9723 }
9724
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 163/298
1/31/24, 9:21 AM [Link]
9725 // Test the function
9726 const inputString = "dog";
9727 [Link](
9728 'All combinations of "' + inputString + '":',
9729 allCombinations(inputString)
9730 );
9731 </script>
9732 <hr />
9733
9734 <h4>
9735 [Link] a JavaScript function that returns a passed string with letters
9736 in alphabetical order. Example string : 'webmaster' Expected Output :
9737 'abeemrstw'
9738 </h4>
9739 <script>
9740 function sortStringAlphabetically(str) {
9741 // Split the string into an array of characters, sort them alphabetically, and
join them back into a string
9742 return [Link]("").sort().join("");
9743 }
9744
9745 // Test the function
9746 const inputString = "webmaster";
9747 [Link]("Sorted string:", sortStringAlphabetically(inputString));
9748 </script>
9749 <hr />
9750
9751 <h4>
9752 [Link] a JavaScript function that accepts a string as a parameter and
9753 converts the first letter of each word of the string in upper case.
9754 Example string : 'the quick brown fox' Expected Output : 'The Quick Brown
9755 Fox '
9756 </h4>
9757 <script>
9758 function capitalizeFirstLetter(str) {
9759 // Split the string into an array of words
9760 let words = [Link](" ");
9761
9762 // Iterate over each word in the array
9763 for (let i = 0; i < [Link]; i++) {
9764 // Capitalize the first letter of each word
9765 words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
9766 }
9767
9768 // Join the capitalized words back into a single string
9769 return [Link](" ");
9770 }
9771
9772 // Test the function
9773 const inputString = "the quick brown fox";
9774 [Link]("Capitalized string:", capitalizeFirstLetter(inputString));
9775 </script>
9776 <hr />
9777
9778 <h4>
9779 [Link] a JavaScript function that accepts a string as a parameter and
9780 find the longest word within the string. Example string : 'Web Development
9781 Tutorial' Expected Output : 'Development'
9782 </h4>
9783 <script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 164/298
1/31/24, 9:21 AM [Link]
9784 function findLongestWord(str) {
9785 // Split the string into an array of words
9786 let words = [Link](" ");
9787
9788 // Initialize variables to store the longest word and its length
9789 let longestWord = "";
9790 let maxLength = 0;
9791
9792 // Iterate over each word in the array
9793 for (let i = 0; i < [Link]; i++) {
9794 // Check if the current word's length is greater than the maxLength
9795 if (words[i].length > maxLength) {
9796 // If so, update the maxLength and longestWord variables
9797 maxLength = words[i].length;
9798 longestWord = words[i];
9799 }
9800 }
9801
9802 // Return the longest word
9803 return longestWord;
9804 }
9805
9806 // Test the function
9807 const inputString = "Web Development Tutorial";
9808 [Link]("Longest word:", findLongestWord(inputString));
9809 </script>
9810 <hr />
9811
9812 <h4>
9813 [Link] a JavaScript function that accepts a string as a parameter and
9814 counts the number of vowels within the string. Note : As the letter 'y'
9815 can be regarded as both a vowel and a consonant, we do not count 'y' as
9816 vowel here. Example string : 'The quick brown fox' Expected Output : 5
9817 </h4>
9818 <script>
9819 function countVowels(str) {
9820 // Convert the string to lowercase to make the comparison case-insensitive
9821 str = [Link]();
9822
9823 // Define a string containing all vowels
9824 const vowels = "aeiou";
9825
9826 // Initialize a counter for vowels
9827 let vowelCount = 0;
9828
9829 // Loop through each character of the string
9830 for (let i = 0; i < [Link]; i++) {
9831 // Check if the current character is a vowel
9832 if ([Link](str[i])) {
9833 // If it's a vowel, increment the vowel count
9834 vowelCount++;
9835 }
9836 }
9837
9838 // Return the total count of vowels
9839 return vowelCount;
9840 }
9841
9842 // Test the function
9843 const inputString = "The quick brown fox";
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 165/298
1/31/24, 9:21 AM [Link]
9844 [Link]("Number of vowels:", countVowels(inputString));
9845 </script>
9846 <hr />
9847
9848 <h4>
9849 [Link] a JavaScript function that accepts a number as a parameter and
9850 check the number is prime or not. Note : A prime number (or a prime) is a
9851 natural number greater than 1 that has no positive divisors other than 1
9852 and itself.
9853 </h4>
9854 <script>
9855 function isPrime(num) {
9856 // Check if the number is less than 2
9857 if (num < 2) {
9858 return false; // Numbers less than 2 are not prime
9859 }
9860
9861 // Loop from 2 to the square root of the number
9862 for (let i = 2; i <= [Link](num); i++) {
9863 // Check if the number is divisible by any integer between 2 and its square
root
9864 if (num % i === 0) {
9865 return false; // If it's divisible, it's not prime
9866 }
9867 }
9868
9869 // If the number is not divisible by any integer between 2 and its square root,
it's prime
9870 return true;
9871 }
9872
9873 // Test the function
9874 const num = 17;
9875 [Link](num + " is prime?", isPrime(num)); // Output: true
9876 </script>
9877 <hr />
9878
9879 <h4>
9880 [Link] a JavaScript function which accepts an argument and returns the
9881 type. Note : There are six possible values that typeof returns: object,
9882 boolean, function, number, string, and undefined.
9883 </h4>
9884 <script>
9885 function getType(value) {
9886 return typeof value;
9887 }
9888
9889 // Test the function
9890 [Link](getType({})); // Output: object
9891 [Link](getType(true)); // Output: boolean
9892 [Link](getType(function () {})); // Output: function
9893 [Link](getType(123)); // Output: number
9894 [Link](getType("Hello")); // Output: string
9895 [Link](getType(undefined)); // Output: undefined
9896 </script>
9897 <hr />
9898
9899 <h4>
9900 [Link] a JavaScript function which returns the n rows by n columns
9901 identity matrix.
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 166/298
1/31/24, 9:21 AM [Link]
9902 </h4>
9903 <script>
9904 function identityMatrix(n) {
9905 let matrix = [];
9906 for (let i = 0; i < n; i++) {
9907 let row = [];
9908 for (let j = 0; j < n; j++) {
9909 if (i === j) {
9910 [Link](1);
9911 } else {
9912 [Link](0);
9913 }
9914 }
9915 [Link](row);
9916 }
9917 return matrix;
9918 }
9919
9920 // Test the function
9921 [Link](identityMatrix(3));
9922 </script>
9923 <hr />
9924
9925 <h4>
9926 [Link] a JavaScript function which will take an array of numbers stored
9927 and find the second lowest and second greatest numbers, respectively.
9928 Sample array : [1,2,3,4,5] Expected Output : 2,4
9929 </h4>
9930 <script>
9931 function findSecondLowestAndGreatest(arr) {
9932 if ([Link] < 2) {
9933 return "Array length should be at least 2";
9934 }
9935
9936 // Sort the array in ascending order
9937 [Link](function (a, b) {
9938 return a - b;
9939 });
9940
9941 let secondLowest = arr[1];
9942 let secondGreatest = arr[[Link] - 2];
9943
9944 return [secondLowest, secondGreatest];
9945 }
9946
9947 // Test the function
9948 let sampleArray = [1, 2, 3, 4, 5];
9949 [Link](findSecondLowestAndGreatest(sampleArray)); // Output: [2, 4]
9950 </script>
9951 <hr />
9952
9953 <h4>
9954 [Link] a JavaScript function which says whether a number is perfect.
9955 According to Wikipedia : In number theory, a perfect number is a positive
9956 integer that is equal to the sum of its proper positive divisors, that is,
9957 the sum of its positive divisors excluding the number itself (also known
9958 as its aliquot sum). Equivalently, a perfect number is a number that is
9959 half the sum of all of its positive divisors (including itself). Example :
9960 The first perfect number is 6, because 1, 2, and 3 are its proper positive
9961 divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 167/298
1/31/24, 9:21 AM [Link]
9962 the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. The next
9963 perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect
9964 numbers 496 and 8128
9965 </h4>
9966 <script>
9967 function isPerfectNumber(num) {
9968 if (num <= 1) {
9969 return false;
9970 }
9971
9972 let sum = 1; // Initialize sum of divisors as 1 (since 1 is always a divisor)
9973
9974 // Find all proper divisors and add them to the sum
9975 for (let i = 2; i * i <= num; i++) {
9976 if (num % i === 0) {
9977 sum += i;
9978 if (i !== num / i) {
9979 sum += num / i;
9980 }
9981 }
9982 }
9983
9984 // If the sum of divisors is equal to the number itself, it's a perfect number
9985 return sum === num;
9986 }
9987
9988 // Test the function
9989 [Link](isPerfectNumber(6)); // Output: true
9990 [Link](isPerfectNumber(28)); // Output: true
9991 [Link](isPerfectNumber(496)); // Output: true
9992 [Link](isPerfectNumber(8128)); // Output: true
9993 [Link](isPerfectNumber(10)); // Output: false
9994 </script>
9995 <hr />
9996
9997 <h4>
9998 [Link] a JavaScript function to compute the factors of a positive
9999 integer
10000 </h4>
10001 <script>
10002 function findFactors(num) {
10003 if (num <= 0) {
10004 return "Number must be positive";
10005 }
10006
10007 const factors = [];
10008 for (let i = 1; i <= [Link]([Link](num)); i++) {
10009 if (num % i === 0) {
10010 [Link](i);
10011 if (num / i !== i) {
10012 [Link](num / i);
10013 }
10014 }
10015 }
10016
10017 // Sort the factors in ascending order
10018 [Link]((a, b) => a - b);
10019
10020 return factors;
10021 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 168/298
1/31/24, 9:21 AM [Link]
10022
10023 // Test the function
10024 [Link](findFactors(12)); // Output: [1, 2, 3, 4, 6, 12]
10025 [Link](findFactors(15)); // Output: [1, 3, 5, 15]
10026 [Link](findFactors(28)); // Output: [1, 2, 4, 7, 14, 28]
10027 </script>
10028 <hr />
10029
10030 <h4>
10031 [Link] a JavaScript function to convert an amount to coins. Sample
10032 function : amountTocoins(46, [25, 10, 5, 2, 1]) Here 46 is the amount. and
10033 25, 10, 5, 2, 1 are coins. Output : 25, 10, 10, 1
10034 </h4>
10035 <script>
10036 function amountToCoins(amount, coins) {
10037 if (amount <= 0 || [Link] === 0) {
10038 return "Invalid input";
10039 }
10040
10041 [Link]((a, b) => b - a); // Sort coins in descending order
10042
10043 const result = [];
10044 let remainingAmount = amount;
10045
10046 for (let i = 0; i < [Link]; i++) {
10047 const currentCoin = coins[i];
10048 while (remainingAmount >= currentCoin) {
10049 [Link](currentCoin);
10050 remainingAmount -= currentCoin;
10051 }
10052 }
10053
10054 return result;
10055 }
10056
10057 // Test the function
10058 [Link](amountToCoins(46, [25, 10, 5, 2, 1])); // Output: [25, 10, 10, 1]
10059 </script>
10060 <hr />
10061
10062 <h4>
10063 [Link] a JavaScript function to compute the value of b n where n is the
10064 exponent and b is the bases. Accept b and n from the user and display the
10065 result
10066 </h4>
10067 <script>
10068 function computePower(base, exponent) {
10069 return [Link](base, exponent);
10070 }
10071
10072 // Example usage:
10073 const base = parseFloat(prompt("Enter the base:"));
10074 const exponent = parseInt(prompt("Enter the exponent:"));
10075
10076 if (!isNaN(base) && !isNaN(exponent)) {
10077 const result = computePower(base, exponent);
10078 [Link](`${base}^${exponent} = ${result}`);
10079 } else {
10080 [Link]("Invalid input. Please enter valid numbers.");
10081 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 169/298
1/31/24, 9:21 AM [Link]
10082 </script>
10083 <hr />
10084
10085 <h4>
10086 [Link] a JavaScript function to extract unique characters from a
10087 string. Example string : "thequickbrownfoxjumpsoverthelazydog" Expected
10088 Output : "thequickbrownfxjmpsvlazydg"
10089 </h4>
10090 <script>
10091 function extractUniqueCharacters(str) {
10092 const uniqueChars = new Set(str);
10093 return [...uniqueChars].join("");
10094 }
10095
10096 // Example usage:
10097 const inputString = "thequickbrownfoxjumpsoverthelazydog";
10098 const result = extractUniqueCharacters(inputString);
10099 [Link](result); // Output: "thequickbrownfxjmpsvlazydg"
10100 </script>
10101 <hr />
10102
10103 <h4>
10104 [Link] a JavaScript function to get the number of occurrences of each
10105 letter in specified string
10106 </h4>
10107 <script>
10108 function countLetterOccurrences(str) {
10109 const occurrences = {};
10110
10111 for (let char of str) {
10112 if (occurrences[char]) {
10113 occurrences[char]++;
10114 } else {
10115 occurrences[char] = 1;
10116 }
10117 }
10118
10119 return occurrences;
10120 }
10121
10122 // Example usage:
10123 const inputString = "hello world";
10124 const result = countLetterOccurrences(inputString);
10125 [Link](result);
10126 </script>
10127 <hr />
10128
10129 <h4>
10130 [Link] a function for searching JavaScript arrays with a binary search.
10131 Note : A binary search searches by splitting an array into smaller and
10132 smaller chunks until it finds the desired value.
10133 </h4>
10134 <script>
10135 function binarySearch(arr, target) {
10136 let left = 0;
10137 let right = [Link] - 1;
10138
10139 while (left <= right) {
10140 const mid = [Link]((left + right) / 2);
10141
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 170/298
1/31/24, 9:21 AM [Link]
10142 if (arr[mid] === target) {
10143 return mid; // Element found, return its index
10144 } else if (arr[mid] < target) {
10145 left = mid + 1; // Continue searching in the right half
10146 } else {
10147 right = mid - 1; // Continue searching in the left half
10148 }
10149 }
10150
10151 return -1; // Element not found
10152 }
10153
10154 // Example usage:
10155 const arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
10156 const target = 11;
10157 const index = binarySearch(arr, target);
10158 [Link](index); // Output: 5 (index of target element in the array)
10159 </script>
10160 <hr />
10161
10162 <h4>
10163 [Link] a JavaScript function that returns array elements larger than a
10164 number.
10165 </h4>
10166
10167 <script>
10168 function elementsLargerThan(arr, number) {
10169 return [Link]((item) => item > number);
10170 }
10171
10172 // Example usage:
10173 const array = [1, 5, 10, 15, 20];
10174 const number = 10;
10175 const result = elementsLargerThan(array, number);
10176 [Link](result); // Output: [15, 20]
10177 </script>
10178 <hr />
10179
10180 <h4>
10181 [Link] a JavaScript function that generates a string id (specified
10182 length) of random characters. Sample character list :
10183 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
10184 </h4>
10185 <script>
10186 function generateRandomId(length) {
10187 const characters =
10188 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
10189 let result = "";
10190 const charactersLength = [Link];
10191 for (let i = 0; i < length; i++) {
10192 result += [Link](
10193 [Link]([Link]() * charactersLength)
10194 );
10195 }
10196 return result;
10197 }
10198
10199 // Example usage:
10200 const idLength = 8;
10201 const randomId = generateRandomId(idLength);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 171/298
1/31/24, 9:21 AM [Link]
10202 [Link](randomId); // Output: something like "j4rD9e2S"
10203 </script>
10204 <hr />
10205
10206 <h4>
10207 [Link] a JavaScript function to get all possible subset with a fixed
10208 length (for example 2) combinations in an array. Sample array : [1, 2, 3]
10209 and subset length is 2 Expected output : [[2, 1], [3, 1], [3, 2], [3, 2,
10210 1]]
10211 </h4>
10212 <script>
10213 function getSubsets(arr, subsetLength) {
10214 const subsets = [];
10215
10216 function generate(subset, index) {
10217 if ([Link] === subsetLength) {
10218 [Link](subset);
10219 return;
10220 }
10221 for (let i = index; i < [Link]; i++) {
10222 generate([Link](arr[i]), i + 1);
10223 }
10224 }
10225
10226 generate([], 0);
10227 return subsets;
10228 }
10229
10230 // Example usage:
10231 const array = [1, 2, 3];
10232 const subsetLength = 2;
10233 const result = getSubsets(array, subsetLength);
10234 [Link](result); // Output: [[1, 2], [1, 3], [2, 3]]
10235 </script>
10236 <hr />
10237
10238 <h4>
10239 [Link] a JavaScript function that accepts two arguments, a string and a
10240 letter and the function will count the number of occurrences of the
10241 specified letter within the string. Sample arguments : '[Link]',
10242 'o' Expected output : 2
10243 </h4>
10244 <script>
10245 function countOccurrences(str, letter) {
10246 // Initialize count to 0
10247 let count = 0;
10248 // Loop through each character in the string
10249 for (let i = 0; i < [Link]; i++) {
10250 // Check if the current character matches the specified letter
10251 if (str[i] === letter) {
10252 // If it matches, increment the count
10253 count++;
10254 }
10255 }
10256 // Return the count of occurrences
10257 return count;
10258 }
10259
10260 // Example usage:
10261 const string = "[Link]";
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 172/298
1/31/24, 9:21 AM [Link]
10262 const letter = "o";
10263 const occurrences = countOccurrences(string, letter);
10264 [Link](occurrences); // Output: 2
10265 </script>
10266 <hr />
10267
10268 <h4>
10269 [Link] a JavaScript function to find the first not repeated character.
10270 Sample arguments : 'abacddbec' Expected output : 'e'
10271 </h4>
10272 <script>
10273 function firstNonRepeatedCharacter(str) {
10274 // Create an object to store the frequency of each character
10275 const frequency = {};
10276
10277 // Loop through each character in the string and update its frequency
10278 for (let char of str) {
10279 frequency[char] = (frequency[char] || 0) + 1;
10280 }
10281
10282 // Loop through the string again to find the first character with frequency 1
10283 for (let char of str) {
10284 if (frequency[char] === 1) {
10285 return char; // Return the first non-repeated character
10286 }
10287 }
10288
10289 // If no non-repeated character is found, return null
10290 return null;
10291 }
10292
10293 // Example usage:
10294 const inputString = "abacddbec";
10295 const result = firstNonRepeatedCharacter(inputString);
10296 [Link](result); // Output: 'e'
10297 </script>
10298 <hr />
10299
10300 <h4>
10301 [Link] a JavaScript function to apply Bubble Sort algorithm. Note :
10302 According to wikipedia "Bubble sort, sometimes referred to as sinking
10303 sort, is a simple sorting algorithm that works by repeatedly stepping
10304 through the list to be sorted, comparing each pair of adjacent items and
10305 swapping them if they are in the wrong order". Sample array : [12, 345, 4,
10306 546, 122, 84, 98, 64, 9, 1, 3223, 455, 23, 234, 213] Expected output :
10307 [3223, 546, 455, 345, 234, 213, 122, 98, 84, 64, 23, 12, 9, 4, 1]
10308 </h4>
10309 <script>
10310 function bubbleSort(arr) {
10311 const len = [Link];
10312 let swapped;
10313
10314 do {
10315 swapped = false;
10316 for (let i = 0; i < len - 1; i++) {
10317 if (arr[i] > arr[i + 1]) {
10318 // Swap elements
10319 const temp = arr[i];
10320 arr[i] = arr[i + 1];
10321 arr[i + 1] = temp;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 173/298
1/31/24, 9:21 AM [Link]
10322 swapped = true;
10323 }
10324 }
10325 } while (swapped);
10326
10327 return arr;
10328 }
10329
10330 // Example usage:
10331 const array = [
10332 12, 345, 4, 546, 122, 84, 98, 64, 9, 1, 3223, 455, 23, 234, 213,
10333 ];
10334 const sortedArray = bubbleSort(array);
10335 [Link](sortedArray); // Output: [1, 4, 9, 12, 23, 64, 84, 98, 122, 213, 234,
345, 455, 546, 3223]
10336 </script>
10337 <hr />
10338
10339 <h4>
10340 [Link] a JavaScript function that accept a list of country names as
10341 input and returns the longest country name as output. Sample function :
10342 Longest_Country_Name(["Australia", "Germany", "United States of America"])
10343 Expected output : "United States of America"
10344 </h4>
10345 <script>
10346 function longestCountryName(countryNames) {
10347 let longestName = "";
10348
10349 for (let i = 0; i < [Link]; i++) {
10350 if (countryNames[i].length > [Link]) {
10351 longestName = countryNames[i];
10352 }
10353 }
10354
10355 return longestName;
10356 }
10357
10358 // Example usage:
10359 const countries = ["Australia", "Germany", "United States of America"];
10360 const longest = longestCountryName(countries);
10361 [Link](longest); // Output: "United States of America"
10362 </script>
10363 <hr />
10364
10365 <h4>
10366 [Link] a JavaScript function to find longest substring in a given a
10367 string without repeating characters
10368 </h4>
10369 <script>
10370 function longestSubstringWithoutRepeating(str) {
10371 let maxLength = 0;
10372 let longestSubstring = "";
10373 let currentSubstring = "";
10374
10375 for (let i = 0; i < [Link]; i++) {
10376 const char = str[i];
10377 const charIndex = [Link](char);
10378
10379 if (charIndex !== -1) {
10380 maxLength = [Link](maxLength, [Link]);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 174/298
1/31/24, 9:21 AM [Link]
10381 currentSubstring = [Link](charIndex + 1);
10382 }
10383
10384 currentSubstring += char;
10385 }
10386
10387 // Check for the last substring
10388 maxLength = [Link](maxLength, [Link]);
10389
10390 // Get the longest substring
10391 longestSubstring = [Link]([Link] - maxLength);
10392
10393 return longestSubstring;
10394 }
10395
10396 // Example usage:
10397 const str = "abcabcbb";
10398 [Link](longestSubstringWithoutRepeating(str)); // Output: "abc"
10399 </script>
10400 <hr />
10401
10402 <h4>
10403 [Link] a JavaScript function that returns the longest palindrome in a
10404 given string. Note: According to Wikipedia "In computer science, the
10405 longest palindromic substring or longest symmetric factor problem is the
10406 problem of finding a maximum-length contiguous substring of a given string
10407 that is also a palindrome. For example, the longest palindromic substring
10408 of "bananas" is "anana". The longest palindromic substring is not
10409 guaranteed to be unique; for example, in the string "abracadabra", there
10410 is no palindromic substring with length greater than three, but there are
10411 two palindromic substrings with length three, namely, "aca" and "ada". In
10412 some applications it may be necessary to return all maximal palindromic
10413 substrings (that is, all substrings that are themselves palindromes and
10414 cannot be extended to larger palindromic substrings) rather than returning
10415 only one substring or returning the maximum length of a palindromic
10416 substring.
10417 </h4>
10418 <script>
10419 function longestPalindrome(str) {
10420 if ([Link] <= 1) return str;
10421
10422 let maxLength = 1;
10423 let start = 0;
10424
10425 // Create a 2D array to store whether substrings are palindromes
10426 const dp = [Link]({ length: [Link] }, () =>
10427 Array([Link]).fill(false)
10428 );
10429
10430 // All substrings of length 1 are palindromes
10431 for (let i = 0; i < [Link]; i++) {
10432 dp[i][i] = true;
10433 }
10434
10435 // Check for substrings of length 2
10436 for (let i = 0; i < [Link] - 1; i++) {
10437 if (str[i] === str[i + 1]) {
10438 dp[i][i + 1] = true;
10439 start = i;
10440 maxLength = 2;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 175/298
1/31/24, 9:21 AM [Link]
10441 }
10442 }
10443
10444 // Check for substrings of length > 2
10445 for (let len = 3; len <= [Link]; len++) {
10446 for (let i = 0; i < [Link] - len + 1; i++) {
10447 const j = i + len - 1;
10448
10449 if (str[i] === str[j] && dp[i + 1][j - 1]) {
10450 dp[i][j] = true;
10451 start = i;
10452 maxLength = len;
10453 }
10454 }
10455 }
10456
10457 return [Link](start, maxLength);
10458 }
10459
10460 // Example usage:
10461 const str = "bananas";
10462 [Link](longestPalindrome(str)); // Output: "anana"
10463 </script>
10464 <hr />
10465
10466 <h4>
10467 [Link] a JavaScript program to pass a 'JavaScript function' as
10468 parameter
10469 </h4>
10470 <script>
10471 // Define a function that takes another function as a parameter
10472 function higherOrderFunction(callback) {
10473 // Call the function passed as parameter
10474 callback();
10475 }
10476
10477 // Define a function to be passed as a parameter
10478 function myFunction() {
10479 [Link]("Hello from myFunction!");
10480 }
10481
10482 // Call the higher-order function and pass myFunction as a parameter
10483 higherOrderFunction(myFunction);
10484 </script>
10485 <hr />
10486
10487 <h4>[Link] a JavaScript function to get the function name.</h4>
10488 <script>
10489 function getFunctionName(func) {
10490 // If the function has a name property, return it
10491 if ([Link]) {
10492 return [Link];
10493 }
10494 // If the function was created using a function declaration, return the name of
the variable it was assigned to
10495 if ([Link]().startsWith("function")) {
10496 return [Link]().split(" ")[1];
10497 }
10498 // If the function was created using a function expression, return the name of
the variable it was assigned to
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 176/298
1/31/24, 9:21 AM [Link]
10499 if ([Link]().startsWith("()")) {
10500 return [Link]().split(" ")[1];
10501 }
10502 // If the function is an arrow function, it has no name
10503 return "Anonymous Function";
10504 }
10505
10506 // Example usage:
10507 function myFunction() {
10508 // Function body
10509 }
10510
10511 const anotherFunction = function () {
10512 // Function body
10513 };
10514
10515 const arrowFunction = () => {
10516 // Function body
10517 };
10518
10519 [Link](getFunctionName(myFunction)); // Output: myFunction
10520 [Link](getFunctionName(anotherFunction)); // Output: anotherFunction
10521 [Link](getFunctionName(arrowFunction)); // Output: Anonymous Function
10522 </script>
10523 <hr />
10524
10525 <h4>
10526 [Link] a JavaScript program to calculate the factorial of a number. In
10527 mathematics, the factorial of a non-negative integer n, denoted by n!, is
10528 the product of all positive integers less than or equal to n. For example,
10529 5! = 5 x 4 x 3 x 2 x 1 = 120
10530 </h4>
10531 <script>
10532 function factorial(n) {
10533 if (n === 0) {
10534 return 1;
10535 } else {
10536 return n * factorial(n - 1);
10537 }
10538 }
10539
10540 // Example usage:
10541 const number = 5;
10542 [Link](`The factorial of ${number} is: ${factorial(number)}`);
10543 </script>
10544 <hr />
10545
10546 <h4>
10547 [Link] a JavaScript program to find the greatest common divisor (gcd)
10548 of two positive numbers.
10549 </h4>
10550 <script>
10551 function gcd(a, b) {
10552 // Ensure a is greater than or equal to b
10553 if (b === 0) {
10554 return a;
10555 } else {
10556 return gcd(b, a % b);
10557 }
10558 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 177/298
1/31/24, 9:21 AM [Link]
10559
10560 // Example usage:
10561 const num1 = 24;
10562 const num2 = 36;
10563 [Link](
10564 `The greatest common divisor of ${num1} and ${num2} is: ${gcd(
10565 num1,
10566 num2
10567 )}`
10568 );
10569 </script>
10570 <hr />
10571
10572 <h4>
10573 [Link] a JavaScript program to get the integers in range (x, y).
10574 Example : range(2, 9) Expected Output : [3, 4, 5, 6, 7, 8]
10575 </h4>
10576 <script>
10577 function range(x, y) {
10578 // Ensure x is less than y
10579 if (x >= y) {
10580 return [];
10581 }
10582
10583 const result = [];
10584 for (let i = x + 1; i < y; i++) {
10585 [Link](i);
10586 }
10587 return result;
10588 }
10589
10590 // Example usage:
10591 const x = 2;
10592 const y = 9;
10593 [Link](`Range between ${x} and ${y}:`, range(x, y));
10594 </script>
10595 <hr />
10596
10597 <h4>
10598 [Link] a JavaScript program to compute the sum of an array of integers.
10599 Example : var array = [1, 2, 3, 4, 5, 6] Expected Output : 21
10600 </h4>
10601 <script>
10602 function sumArray(array) {
10603 return [Link]((sum, current) => sum + current, 0);
10604 }
10605
10606 // Example usage:
10607 const array = [1, 2, 3, 4, 5, 6];
10608 [Link]("Sum of the array:", sumArray(array));
10609 </script>
10610
10611 <h4>
10612 [Link] a JavaScript program to compute the exponent of a number. Note :
10613 The exponent of a number says how many times the base number is used as a
10614 factor. 8 2 = 8 x 8 = 64. Here 8 is the base and 2 is the exponent.
10615 </h4>
10616 <script>
10617 function computeExponent(base, exponent) {
10618 return [Link](base, exponent);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 178/298
1/31/24, 9:21 AM [Link]
10619 }
10620
10621 // Example usage:
10622 const base = 8;
10623 const exponent = 2;
10624 [Link]("Result:", computeExponent(base, exponent));
10625 </script>
10626 <hr />
10627
10628 <h4>
10629 [Link] a JavaScript program to get the first n Fibonacci numbers. Note
10630 : The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8,
10631 13, 21, 34, . . . Each subsequent number is the sum of the previous two
10632 </h4>
10633 <script>
10634 function getFibonacciNumbers(n) {
10635 let fibonacci = [0, 1];
10636 for (let i = 2; i < n; i++) {
10637 [Link](fibonacci[i - 1] + fibonacci[i - 2]);
10638 }
10639 return [Link](0, n);
10640 }
10641
10642 // Example usage:
10643 const n = 10;
10644 [Link]("First", n, "Fibonacci numbers:", getFibonacciNumbers(n));
10645 </script>
10646 <hr />
10647
10648 <h4>
10649 [Link] a JavaScript program to check whether a number is even or not
10650 </h4>
10651 <script>
10652 function isEven(number) {
10653 return number % 2 === 0;
10654 }
10655
10656 // Example usage:
10657 const number = 7;
10658 if (isEven(number)) {
10659 [Link](number, "is even.");
10660 } else {
10661 [Link](number, "is not even.");
10662 }
10663 </script>
10664 <hr />
10665
10666 <h4>
10667 [Link] a JavaScript program for binary search. Sample array :
10668 [0,1,2,3,4,5,6] [Link](l.br_search(5)) will return '5'
10669 </h4>
10670 <script>
10671 [Link] = function (target) {
10672 let low = 0;
10673 let high = [Link] - 1;
10674
10675 while (low <= high) {
10676 const mid = [Link]((low + high) / 2);
10677 const midValue = this[mid];
10678
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 179/298
1/31/24, 9:21 AM [Link]
10679 if (midValue === target) {
10680 return mid;
10681 } else if (midValue < target) {
10682 low = mid + 1;
10683 } else {
10684 high = mid - 1;
10685 }
10686 }
10687
10688 return -1; // Not found
10689 };
10690
10691 // Example usage:
10692 const arr = [0, 1, 2, 3, 4, 5, 6];
10693 [Link]([Link](5)); // Output: 5
10694 </script>
10695 <hr />
10696
10697 <h4>
10698 [Link] a merge sort program in JavaScript. Sample array :
10699 [34,7,23,32,5,62] Sample output : [5, 7, 23, 32, 34, 62]
10700 </h4>
10701 <script>
10702 function mergeSort(arr) {
10703 if ([Link] <= 1) {
10704 return arr;
10705 }
10706
10707 const mid = [Link]([Link] / 2);
10708 const left = [Link](0, mid);
10709 const right = [Link](mid);
10710
10711 return merge(mergeSort(left), mergeSort(right));
10712 }
10713
10714 function merge(left, right) {
10715 let result = [];
10716 let leftIndex = 0;
10717 let rightIndex = 0;
10718
10719 while (leftIndex < [Link] && rightIndex < [Link]) {
10720 if (left[leftIndex] < right[rightIndex]) {
10721 [Link](left[leftIndex]);
10722 leftIndex++;
10723 } else {
10724 [Link](right[rightIndex]);
10725 rightIndex++;
10726 }
10727 }
10728
10729 return result
10730 .concat([Link](leftIndex))
10731 .concat([Link](rightIndex));
10732 }
10733
10734 // Example usage:
10735 const arr = [34, 7, 23, 32, 5, 62];
10736 const sortedArr = mergeSort(arr);
10737 [Link](sortedArr); // Output: [5, 7, 23, 32, 34, 62]
10738 </script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 180/298
1/31/24, 9:21 AM [Link]
10739 <hr />
10740
10741 <h4>
10742 [Link] a JavaScript program that accept two integers and display the
10743 larger.
10744 </h4>
10745 <script>
10746 function displayLarger(num1, num2) {
10747 if (num1 > num2) {
10748 return num1;
10749 } else {
10750 return num2;
10751 }
10752 }
10753
10754 // Example usage:
10755 const num1 = 10;
10756 const num2 = 20;
10757 const largerNumber = displayLarger(num1, num2);
10758 [Link]("The larger number is:", largerNumber);
10759 </script>
10760 <hr />
10761
10762 <h4>
10763 [Link] a JavaScript conditional statement to find the sign of product
10764 of three numbers. Display an alert box with the specified sign. Sample
10765 numbers : 3, -7, 2 Output : The sign is –
10766 </h4>
10767 <script>
10768 function findProductSign(num1, num2, num3) {
10769 // Calculate the product of the three numbers
10770 const product = num1 * num2 * num3;
10771
10772 // Check the sign of the product
10773 let sign;
10774 if (product > 0) {
10775 sign = "positive";
10776 } else if (product < 0) {
10777 sign = "negative";
10778 } else {
10779 sign = "zero";
10780 }
10781
10782 // Display an alert box with the sign
10783 alert("The sign is " + sign);
10784 }
10785
10786 // Example usage:
10787 const num1 = 3;
10788 const num2 = -7;
10789 const num3 = 2;
10790 findProductSign(num1, num2, num3);
10791 </script>
10792 <hr />
10793
10794 <h4>
10795 [Link] a JavaScript conditional statement to sort three numbers.
10796 Display an alert box to show the result. Sample numbers : 0, -1, 4 Output
10797 : 4, 0, -1
10798 </h4>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 181/298
1/31/24, 9:21 AM [Link]
10799 <script>
10800 function sortNumbers(num1, num2, num3) {
10801 let sortedNumbers;
10802
10803 // Check the relationships between the numbers and sort them accordingly
10804 if (num1 >= num2 && num1 >= num3) {
10805 if (num2 >= num3) {
10806 sortedNumbers = [num1, num2, num3];
10807 } else {
10808 sortedNumbers = [num1, num3, num2];
10809 }
10810 } else if (num2 >= num1 && num2 >= num3) {
10811 if (num1 >= num3) {
10812 sortedNumbers = [num2, num1, num3];
10813 } else {
10814 sortedNumbers = [num2, num3, num1];
10815 }
10816 } else {
10817 if (num1 >= num2) {
10818 sortedNumbers = [num3, num1, num2];
10819 } else {
10820 sortedNumbers = [num3, num2, num1];
10821 }
10822 }
10823
10824 // Display the sorted numbers in an alert box
10825 alert("Sorted numbers: " + [Link](", "));
10826 }
10827
10828 // Example usage:
10829 const num1 = 0;
10830 const num2 = -1;
10831 const num3 = 4;
10832 sortNumbers(num1, num2, num3);
10833 </script>
10834 <hr />
10835
10836 <h4>
10837 [Link] a JavaScript conditional statement to find the largest of five
10838 numbers. Display an alert box to show the result. Sample numbers : -5, -2,
10839 -6, 0, -1 Output : 0
10840 </h4>
10841 <script>
10842 function findLargest(num1, num2, num3, num4, num5) {
10843 let largest = num1;
10844
10845 // Compare the remaining numbers with the current largest
10846 if (num2 > largest) {
10847 largest = num2;
10848 }
10849 if (num3 > largest) {
10850 largest = num3;
10851 }
10852 if (num4 > largest) {
10853 largest = num4;
10854 }
10855 if (num5 > largest) {
10856 largest = num5;
10857 }
10858
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 182/298
1/31/24, 9:21 AM [Link]
10859 // Display the largest number in an alert box
10860 alert("The largest number is: " + largest);
10861 }
10862
10863 // Example usage:
10864 const num1 = -5,
10865 num2 = -2,
10866 num3 = -6,
10867 num4 = 0,
10868 num5 = -1;
10869 findLargest(num1, num2, num3, num4, num5);
10870 </script>
10871 <hr />
10872
10873 <h4>
10874 [Link] a JavaScript for loop that will iterate from 0 to 15. For each
10875 iteration, it will check if the current number is odd or even, and display
10876 a message to the screen. Sample Output : "0 is even" "1 is odd" "2 is
10877 even" …….
10878 </h4>
10879 <script>
10880 // Loop from 0 to 15
10881 for (let i = 0; i <= 15; i++) {
10882 // Check if the current number is even or odd
10883 if (i % 2 === 0) {
10884 [Link](i + " is even");
10885 } else {
10886 [Link](i + " is odd");
10887 }
10888 }
10889 </script>
10890 <hr />
10891
10892 <h4>
10893 <pre>
10894 [Link] a JavaScript program which compute, the average marks of the following
students Then, this average is used
10895 to determine the corresponding grade.
10896 Student Name Marks
10897 David 80
10898 Vinoth 77
10899 Divya 88
10900 Ishitha 95
10901 Thomas 6</pre
10902 >
10903 </h4>
10904 <script>
10905 // Function to compute the average marks
10906 function computeAverage(marks) {
10907 let totalMarks = 0;
10908 for (let i = 0; i < [Link]; i++) {
10909 totalMarks += marks[i];
10910 }
10911 return totalMarks / [Link];
10912 }
10913
10914 // Function to determine the grade based on average marks
10915 function determineGrade(average) {
10916 if (average >= 90) {
10917 return "A";
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 183/298
1/31/24, 9:21 AM [Link]
10918 } else if (average >= 80) {
10919 return "B";
10920 } else if (average >= 70) {
10921 return "C";
10922 } else if (average >= 60) {
10923 return "D";
10924 } else {
10925 return "F";
10926 }
10927 }
10928
10929 // Object containing student names and their marks
10930 const studentMarks = {
10931 David: 80,
10932 Vinoth: 77,
10933 Divya: 88,
10934 Ishitha: 95,
10935 Thomas: 68,
10936 };
10937
10938 // Compute average marks
10939 const marksArray = [Link](studentMarks);
10940 const averageMarks = computeAverage(marksArray);
10941
10942 // Determine grade
10943 const grade = determineGrade(averageMarks);
10944
10945 // Output average marks and grade
10946 [Link]("Average marks:", averageMarks);
10947 [Link]("Grade:", grade);
10948 </script>
10949 <hr />
10950
10951 <h4>
10952 [Link] a JavaScript program which iterates the integers from 1 to 100.
10953 But for multiples of three print "Fizz" instead of the number and for the
10954 multiples of five print "Buzz". For numbers which are multiples of both
10955 three and five print "FizzBuzz".
10956 </h4>
10957 <script>
10958 for (let i = 1; i <= 100; i++) {
10959 // Check if the number is a multiple of both 3 and 5
10960 if (i % 3 === 0 && i % 5 === 0) {
10961 [Link]("FizzBuzz");
10962 }
10963 // Check if the number is a multiple of 3
10964 else if (i % 3 === 0) {
10965 [Link]("Fizz");
10966 }
10967 // Check if the number is a multiple of 5
10968 else if (i % 5 === 0) {
10969 [Link]("Buzz");
10970 }
10971 // If none of the above conditions are met, print the number itself
10972 else {
10973 [Link](i);
10974 }
10975 }
10976 </script>
10977
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 184/298
1/31/24, 9:21 AM [Link]
10978 <h4>
10979 [Link] to Wikipedia a happy number is defined by the following
10980 process : "Starting with any positive integer, replace the number by the
10981 sum of the squares of its digits, and repeat the process until the number
10982 equals 1 (where it will stay), or it loops endlessly in a cycle which does
10983 not include 1. Those numbers for which this process ends in 1 are happy
10984 numbers, while those that do not end in 1 are unhappy numbers (or sad
10985 numbers)". Write a JavaScript program to find and print the first 5 happy
10986 numbers.
10987 </h4>
10988 <script>
10989 // Function to compute the sum of the squares of the digits of a number
10990 function sumOfSquares(n) {
10991 let sum = 0;
10992 while (n > 0) {
10993 const digit = n % 10;
10994 sum += digit * digit;
10995 n = [Link](n / 10);
10996 }
10997 return sum;
10998 }
10999
11000 // Function to check if a number is a happy number
11001 function isHappyNumber(num) {
11002 // Use a set to keep track of seen numbers to detect cycles
11003 const seen = new Set();
11004 while (num !== 1 && ) {
11005 [Link](num);
11006 num = sumOfSquares(num);
11007 }
11008 return num === 1;
11009 }
11010
11011 // Function to find and print the first n happy numbers
11012 function findFirstNHappiness(n) {
11013 const happyNumbers = [];
11014 let num = 1;
11015 while ([Link] < n) {
11016 if (isHappyNumber(num)) {
11017 [Link](num);
11018 }
11019 num++;
11020 }
11021 return happyNumbers;
11022 }
11023
11024 // Print the first 5 happy numbers
11025 const first5HappyNumbers = findFirstNHappiness(5);
11026 [Link](
11027 "The first 5 happy numbers are:",
11028 [Link](", ")
11029 );
11030 </script>
11031 <hr />
11032
11033 <h4>
11034 [Link] a JavaScript program to find the armstrong numbers of 3 digits.
11035 Note : An Armstrong number of three digits is an integer such that the sum
11036 of the cubes of its digits is equal to the number itself. For example, 371
11037 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371.
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 185/298
1/31/24, 9:21 AM [Link]
11038 </h4>
11039 <script>
11040 // Function to check if a number is an Armstrong number of 3 digits
11041 function isArmstrongNumber(num) {
11042 const digits = [Link]().split("");
11043 const numDigits = [Link];
11044 let sum = 0;
11045
11046 // Calculate the sum of cubes of digits
11047 for (let digit of digits) {
11048 sum += [Link](parseInt(digit), numDigits);
11049 }
11050
11051 // Check if the sum equals the number itself
11052 return sum === num;
11053 }
11054
11055 // Function to find and return Armstrong numbers of 3 digits
11056 function findArmstrongNumbers() {
11057 const armstrongNumbers = [];
11058 for (let i = 100; i < 1000; i++) {
11059 if (isArmstrongNumber(i)) {
11060 [Link](i);
11061 }
11062 }
11063 return armstrongNumbers;
11064 }
11065
11066 // Find and print Armstrong numbers of 3 digits
11067 const armstrongNumbers = findArmstrongNumbers();
11068 [Link](
11069 "Armstrong numbers of 3 digits:",
11070 [Link](", ")
11071 );
11072 </script>
11073 <hr />
11074
11075 <h4>
11076 [Link] a JavaScript program to construct the following pattern, using a
11077 nested for loop. * * * * * * * * * * * * * * *
11078 </h4>
11079 <script>
11080 // Function to construct the pattern
11081 function constructPattern(rows) {
11082 // Iterate through each row
11083 for (let i = 1; i <= rows; i++) {
11084 let pattern = "";
11085 // Print '*' based on the current row number
11086 for (let j = 1; j <= i; j++) {
11087 pattern += "* ";
11088 }
11089 [Link](pattern);
11090 }
11091 }
11092
11093 // Number of rows for the pattern
11094 const numberOfRows = 5;
11095
11096 // Construct and print the pattern
11097 constructPattern(numberOfRows);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 186/298
1/31/24, 9:21 AM [Link]
11098 </script>
11099 <hr />
11100
11101 <h4>
11102 [Link] a JavaScript program to compute the lowest common divisor (LCD)
11103 of two positive integers
11104 </h4>
11105 <script>
11106 // Function to compute the greatest common divisor (GCD) using Euclidean algorithm
11107 function gcd(a, b) {
11108 // Base case: if b is 0, then GCD is a
11109 if (b === 0) {
11110 return a;
11111 } else {
11112 // Recursive call: GCD(a, b) = GCD(b, a % b)
11113 return gcd(b, a % b);
11114 }
11115 }
11116
11117 // Function to compute the lowest common divisor (LCD) using GCD
11118 function lcd(a, b) {
11119 // LCD = (a * b) / GCD(a, b)
11120 return (a * b) / gcd(a, b);
11121 }
11122
11123 // Example usage
11124 const num1 = 12;
11125 const num2 = 18;
11126 [Link](
11127 `The lowest common divisor of ${num1} and ${num2} is: ${lcd(
11128 num1,
11129 num2
11130 )}`
11131 );
11132 </script>
11133 <hr />
11134
11135 <h4>
11136 [Link] a JavaScript program to sum the multiples of 3 and 5 under 1000.
11137 </h4>
11138 <script>
11139 function sumMultiples() {
11140 let sum = 0;
11141 for (let i = 1; i < 1000; i++) {
11142 // Check if the number is a multiple of 3 or 5
11143 if (i % 3 === 0 || i % 5 === 0) {
11144 sum += i;
11145 }
11146 }
11147 return sum;
11148 }
11149
11150 // Calculate and display the sum of multiples of 3 and 5 under 1000
11151 [Link]("Sum of multiples of 3 and 5 under 1000:", sumMultiples());
11152 </script>
11153 <hr />
11154
11155 <h4>
11156 467.. Write a JavaScript function to convert a number from one base to
11157 another. Note : Both bases must be between 2 and 36. Test Data :
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 187/298
1/31/24, 9:21 AM [Link]
11158 [Link](base_convert('E164',16,8));
11159 [Link](base_convert(1000,2,8)); "160544" "10"
11160 </h4>
11161 <script>
11162 function base_convert(number, from_base, to_base) {
11163 if (typeof number !== "string") {
11164 // Convert the number to a string in its original base
11165 number = parseInt(number).toString(from_base);
11166 }
11167
11168 // Convert the number from its original base to base 10
11169 let base_10_number = parseInt(number, from_base);
11170
11171 // Convert the number from base 10 to the target base
11172 let result = base_10_number.toString(to_base);
11173
11174 return result;
11175 }
11176
11177 // Test cases
11178 [Link](base_convert("E164", 16, 8)); // Output: "160544"
11179 [Link](base_convert(1000, 2, 8)); // Output: "10"
11180 </script>
11181 <hr />
11182
11183 <h4>
11184 [Link] a JavaScript function to convert a binary number to a decimal
11185 number. Test Data : [Link](bin_to_dec('110011'));
11186 [Link](bin_to_dec('100')); 51 4
11187 </h4>
11188 <script>
11189 function bin_to_dec(binary) {
11190 // Convert binary string to decimal number using parseInt
11191 let decimal = parseInt(binary, 2);
11192 return decimal;
11193 }
11194
11195 // Test cases
11196 [Link](bin_to_dec("110011")); // Output: 51
11197 [Link](bin_to_dec("100")); // Output: 4
11198 </script>
11199 <hr />
11200
11201 <h4>
11202 [Link] a JavaScript function to convert a decimal number to binary,
11203 hexadecimal or octal number. Test Data : [Link](dec_to_bho(120,'B'));
11204 [Link](dec_to_bho(120,'H')); [Link](dec_to_bho(120,'O'));
11205 "1111000" "78" "170"
11206 </h4>
11207 <script>
11208 function dec_to_bho(decimal, type) {
11209 if (type === "B") {
11210 // Convert decimal to binary using toString
11211 return [Link](2);
11212 } else if (type === "H") {
11213 // Convert decimal to hexadecimal using toString
11214 return [Link](16);
11215 } else if (type === "O") {
11216 // Convert decimal to octal using toString
11217 return [Link](8);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 188/298
1/31/24, 9:21 AM [Link]
11218 } else {
11219 return "Invalid type";
11220 }
11221 }
11222
11223 // Test cases
11224 [Link](dec_to_bho(120, "B")); // Output: "1111000"
11225 [Link](dec_to_bho(120, "H")); // Output: "78"
11226 [Link](dec_to_bho(120, "O")); // Output: "170"
11227 </script>
11228 <hr />
11229
11230 <h4>
11231 [Link] a JavaScript function to generate a random integer. Test Data :
11232 [Link](rand(20,1)); [Link](rand(1,10)); [Link](rand(6));
11233 [Link](rand()); 15 5 1 0
11234 </h4>
11235 <script>
11236 function rand(min = 0, max = 10) {
11237 // If only one argument is provided, set it as the maximum value
11238 if ([Link] === 1) {
11239 max = min;
11240 min = 0;
11241 }
11242 // Generate a random integer within the specified range
11243 return [Link]([Link]() * (max - min + 1)) + min;
11244 }
11245
11246 // Test cases
11247 [Link](rand(20, 1)); // Output: Random integer between 20 and 1 (inclusive)
11248 [Link](rand(1, 10)); // Output: Random integer between 1 and 10 (inclusive)
11249 [Link](rand(6)); // Output: Random integer between 0 and 6 (inclusive)
11250 [Link](rand()); // Output: Random integer between 0 and 10 (inclusive)
because no range is provided
11251 </script>
11252 <hr />
11253
11254 <h4>
11255 [Link] a JavaScript function to format a number up to specified decimal
11256 places. Test Data : [Link](decimals(2.100212, 2));
11257 [Link](decimals(2.100212, 3)); [Link](decimals(2100, 2)); "2.10"
11258 "2.100" "2100.00"
11259 </h4>
11260 <script>
11261 function decimals(number, decimalPlaces) {
11262 // If the number is an integer, convert it to a float to format decimals
11263 if ([Link](number)) {
11264 number = parseFloat([Link](decimalPlaces));
11265 } else {
11266 number = parseFloat([Link](decimalPlaces));
11267 }
11268 return [Link](decimalPlaces);
11269 }
11270
11271 // Test cases
11272 [Link](decimals(2.100212, 2)); // Output: 2.10
11273 [Link](decimals(2.100212, 3)); // Output: 2.100
11274 [Link](decimals(2100, 2)); // Output: 2100.00
11275 </script>
11276 <hr />
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 189/298
1/31/24, 9:21 AM [Link]
11277
11278 <h4>
11279 [Link] a JavaScript function to find the highest value in an array.
11280 Test Data : [Link](max([12,34,56,1]));
11281 [Link](max([-12,-34,0,-56,-1])); 56 0
11282 </h4>
11283 <script>
11284 function max(array) {
11285 return [Link](...array);
11286 }
11287
11288 // Test cases
11289 [Link](max([12, 34, 56, 1])); // Output: 56
11290 [Link](max([-12, -34, 0, -56, -1])); // Output: 0
11291 </script>
11292 <hr />
11293
11294 <h4>
11295 [Link] a JavaScript function to find the lowest value in an array. Test
11296 Data : [Link](min([12,34,56,1]));
11297 [Link](min([-12,-34,0,-56,-1])); 1 -56
11298 </h4>
11299 <script>
11300 function min(array) {
11301 return [Link](...array);
11302 }
11303
11304 // Test cases
11305 [Link](min([12, 34, 56, 1])); // Output: 1
11306 [Link](min([-12, -34, 0, -56, -1])); // Output: -56
11307 </script>
11308 <hr />
11309
11310 <h4>
11311 [Link] a JavaScript function to get the greatest common divisor (gcd)
11312 of two integers. Note : According to Wikipedia - In mathematics, the
11313 greatest common divisor (gcd) of two or more integers, when at least one
11314 of them is not zero, is the largest positive integer that divides the
11315 numbers without a remainder. For example, the GCD of 8 and 12 is 4. Test
11316 Data : [Link](gcd_two_numbers(12, 13));
11317 [Link](gcd_two_numbers(9, 3)); Output : 1 3
11318 </h4>
11319 <script>
11320 function gcd_two_numbers(x, y) {
11321 if (y === 0) {
11322 return x;
11323 } else {
11324 return gcd_two_numbers(y, x % y);
11325 }
11326 }
11327
11328 // Test cases
11329 [Link](gcd_two_numbers(12, 13)); // Output: 1
11330 [Link](gcd_two_numbers(9, 3)); // Output: 3
11331 </script>
11332 <hr />
11333
11334 <h4>
11335 [Link] a JavaScript function to find the GCD (greatest common divisor)
11336 of more than 2 integers. Test Data :
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 190/298
1/31/24, 9:21 AM [Link]
11337 [Link](gcd_more_than_two_numbers([3,15,27]));
11338 [Link](gcd_more_than_two_numbers([5,10,15,25])); Output : 3 5
11339 </h4>
11340 <script>
11341 function gcd_more_than_two_numbers(arr) {
11342 const gcdOfTwo = (x, y) => {
11343 if (y === 0) {
11344 return x;
11345 } else {
11346 return gcdOfTwo(y, x % y);
11347 }
11348 };
11349
11350 if ([Link] < 2) {
11351 throw new Error("Array must contain at least two integers");
11352 }
11353
11354 let result = arr[0];
11355 for (let i = 1; i < [Link]; i++) {
11356 result = gcdOfTwo(result, arr[i]);
11357 }
11358
11359 return result;
11360 }
11361
11362 // Test cases
11363 [Link](gcd_more_than_two_numbers([3, 15, 27])); // Output: 3
11364 [Link](gcd_more_than_two_numbers([5, 10, 15, 25])); // Output: 5
11365 </script>
11366 <hr />
11367
11368 <h4>
11369 [Link] a JavaScript function to get the least common multiple (LCM) of
11370 two numbers. Note : According to Wikipedia - A common multiple is a number
11371 that is a multiple of two or more integers. The common multiples of 3 and
11372 4 are 0, 12, 24, .... The least common multiple (LCM) of two numbers is
11373 the smallest number (not zero) that is a multiple of both. Test Data :
11374 [Link](lcm_two_numbers(3,15)); [Link](lcm_two_numbers(10,15));
11375 Output : 15 30
11376 </h4>
11377 <script>
11378 function lcm_two_numbers(a, b) {
11379 const gcd = (x, y) => {
11380 while (y !== 0) {
11381 let temp = y;
11382 y = x % y;
11383 x = temp;
11384 }
11385 return x;
11386 };
11387
11388 // Calculate LCM using the formula
11389 return [Link](a * b) / gcd(a, b);
11390 }
11391
11392 // Test cases
11393 [Link](lcm_two_numbers(3, 15)); // Output: 15
11394 [Link](lcm_two_numbers(10, 15)); // Output: 30
11395 </script>
11396 <hr />
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 191/298
1/31/24, 9:21 AM [Link]
11397
11398 <h4>
11399 [Link] a JavaScript function to get the least common multiple (LCM) of
11400 more than 2 integers. Test Data :
11401 [Link](lcm_more_than_two_numbers([100,90,80,7]));
11402 [Link](lcm_more_than_two_numbers([5,10,15,25])); Output : 25200 150
11403 </h4>
11404 <script>
11405 // Function to calculate the least common multiple (LCM) of more than two numbers
11406 function lcm_more_than_two_numbers(arr) {
11407 // Function to calculate the LCM of two numbers
11408 const lcm_two_numbers = (a, b) => {
11409 const gcd = (x, y) => {
11410 while (y !== 0) {
11411 let temp = y;
11412 y = x % y;
11413 x = temp;
11414 }
11415 return x;
11416 };
11417 return [Link](a * b) / gcd(a, b);
11418 };
11419
11420 // Iterate through the array to calculate the LCM of all numbers
11421 let result = arr[0];
11422 for (let i = 1; i < [Link]; i++) {
11423 result = lcm_two_numbers(result, arr[i]);
11424 }
11425
11426 return result;
11427 }
11428
11429 // Test cases
11430 [Link](lcm_more_than_two_numbers([100, 90, 80, 7])); // Output: 25200
11431 [Link](lcm_more_than_two_numbers([5, 10, 15, 25])); // Output: 150
11432 </script>
11433 <hr />
11434
11435 <h4>
11436 [Link] a JavaScript function to find out if a number is a natural
11437 number or not. Note : Natural numbers are whole numbers from 1 upwards :
11438 1, 2, 3, and so on ... or from 0 upwards in some area of mathematics: 0,
11439 1, 2, 3 and so on ... No negative numbers and no fractions. Test Data :
11440 [Link](is_Natural(-15)); [Link](is_Natural(1));
11441 [Link](is_Natural(10.22)); [Link](is_Natural(10/0)); Output :
11442 false true false false
11443 </h4>
11444 <script>
11445 function is_Natural(num) {
11446 return [Link](num) && num >= 0;
11447 }
11448
11449 // Test Data
11450 [Link](is_Natural(-15)); // Output: false
11451 [Link](is_Natural(1)); // Output: true
11452 [Link](is_Natural(10.22)); // Output: false
11453 [Link](is_Natural(10 / 0)); // Output: false
11454 </script>
11455 <hr />
11456
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 192/298
1/31/24, 9:21 AM [Link]
11457 <h4>
11458 [Link] a JavaScript function to test if a number is a power of 2. Test
11459 Data : [Link](power_of_2(16)); [Link](power_of_2(18));
11460 [Link](power_of_2(256)); Output : true false true
11461 </h4>
11462 <script>
11463 //479 Function to test if a number is a power of 2
11464 function power_of_2(n) {
11465 return n && (n & (n - 1)) === 0;
11466 }
11467
11468 // Test Data
11469 [Link](power_of_2(16)); // Output: true
11470 [Link](power_of_2(18)); // Output: false
11471 [Link](power_of_2(256)); // Output: true
11472 </script>
11473 <hr />
11474
11475 <h4>
11476 [Link] a JavaScript function to round a number to a given decimal
11477 places. Test Data : [Link](precise_round(12.375,2));
11478 [Link](precise_round(-10.3079499, 3));
11479 [Link](precise_round(10.49999,0));
11480 [Link](precise_round(10.49999,2)); Output : 12.38 -10.308 10 10.50
11481 </h4>
11482 <script>
11483 //480 Function to round a number to a given decimal places
11484 function precise_round(number, decimals) {
11485 return Number([Link](decimals));
11486 }
11487
11488 // Test Data
11489 [Link](precise_round(12.375, 2)); // Output: 12.38
11490 [Link](precise_round(-10.3079499, 3)); // Output: -10.308
11491 [Link](precise_round(10.49999, 0)); // Output: 10
11492 [Link](precise_round(10.49999, 2)); // Output: 10.50
11493 </script>
11494 <hr />
11495
11496 <h4>
11497 [Link] a JavaScript function to check whether a value is an integer or
11498 not. Note : Integer - A number which is not a fraction; a whole number.
11499 Test Data : [Link](is_Int(23)); [Link](is_Int(4e2));
11500 [Link](is_Int(NaN)); [Link](is_Int(23.75));
11501 [Link](is_Int(-23)); Output : true true false false true
11502 </h4>
11503 <script>
11504 //481 Function to check whether a value is an integer or not
11505 function is_Int(n) {
11506 return [Link](n);
11507 }
11508
11509 // Test Data
11510 [Link](is_Int(23)); // Output: true
11511 [Link](is_Int(4e2)); // Output: true
11512 [Link](is_Int(NaN)); // Output: false
11513 [Link](is_Int(23.75)); // Output: false
11514 [Link](is_Int(-23)); // Output: true
11515 </script>
11516 <hr />
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 193/298
1/31/24, 9:21 AM [Link]
11517
11518 <h4>
11519 482. Write a JavaScript function to check to check whether a variable is
11520 numeric or not. Test Data : [Link](is_Numeric(12));
11521 [Link](is_Numeric('abcd')); [Link](is_Numeric('12'));
11522 [Link](is_Numeric(' ')); [Link](is_Numeric(1.20));
11523 [Link](is_Numeric(-200)); Output : true false true false true true
11524 </h4>
11525 <script>
11526 //482 Function to check whether a variable is numeric or not
11527 function is_Numeric(n) {
11528 return !isNaN(parseFloat(n)) && isFinite(n);
11529 }
11530
11531 // Test Data
11532 [Link](is_Numeric(12)); // Output: true
11533 [Link](is_Numeric("abcd")); // Output: false
11534 [Link](is_Numeric("12")); // Output: true
11535 [Link](is_Numeric(" ")); // Output: false
11536 [Link](is_Numeric(1.2)); // Output: true
11537 [Link](is_Numeric(-200)); // Output: true
11538 </script>
11539 <h4>
11540 483. Write a JavaScript function to calculate the sum of values in an
11541 array. Test Data : [Link](sum([1,2,3]));
11542 [Link](sum([100,-200,3])); [Link](sum([1,2,'a',3])); Output : 6
11543 -97 6
11544 </h4>
11545 <script>
11546 //483 Function to calculate the sum of values in an array
11547 function sum(arr) {
11548 return [Link]((total, current) => {
11549 return total + (isNaN(current) ? 0 : Number(current));
11550 }, 0);
11551 }
11552
11553 // Test Data
11554 [Link](sum([1, 2, 3])); // Output: 6
11555 [Link](sum([100, -200, 3])); // Output: -97
11556 [Link](sum([1, 2, "a", 3])); // Output: 6
11557 </script>
11558 <hr />
11559
11560 <h4>
11561 484. Write a JavaScript function to calculate the product of values in an
11562 array. Test Data : [Link](product([1,2,3]));
11563 [Link](product([100,-200,3])); [Link](product([1,2,'a',3]));
11564 Output : 6 -60000 6
11565 </h4>
11566 <script>
11567 function product(arr) {
11568 return [Link]((acc, curr) => {
11569 return acc * (isNaN(curr) ? 1 : curr);
11570 }, 1);
11571 }
11572
11573 // Test Data
11574 [Link](product([1, 2, 3])); // Output: 6
11575 [Link](product([100, -200, 3])); // Output: -60000
11576 [Link](product([1, 2, "a", 3])); // Output: 6
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 194/298
1/31/24, 9:21 AM [Link]
11577 </script>
11578 <hr />
11579
11580 <h4>
11581 485. Create a Pythagorean function in JavaScript. Note : The Pythagorean
11582 Theorem tells us that the relationship in every right triangle is : c 2 =
11583 a2 + b2 , where c is the hypotenuse and a, b are two legs of the triangle.
11584 Test Data : [Link](pythagorean_theorem(2, 4));
11585 [Link](pythagorean_theorem(3, 4)); Output : 4.47213595499958 5
11586 </h4>
11587 <script>
11588 function pythagorean_theorem(a, b) {
11589 return [Link](a * a + b * b);
11590 }
11591
11592 // Test Data
11593 [Link](pythagorean_theorem(2, 4)); // Output: 4.47213595499958
11594 [Link](pythagorean_theorem(3, 4)); // Output: 5
11595 </script>
11596 <hr />
11597
11598 <h4>
11599 486. Write a JavaScript program to evaluate binomial coefficients. Note :
11600 Binomial coefficient : According to Wikipedia - In mathematics, binomial
11601 coefficients are a family of positive integers that occur as coefficients
11602 in the binomial theorem. They are indexed by two nonnegative integers; the
11603 binomial coefficient indexed by n and k. Under suitable circumstances the
11604 value of the coefficient is given by the expression : Arranging binomial
11605 coefficients into rows for successive values of n, and in which k ranges
11606 from 0 to n, gives a triangular array called Pascal's triangle. Test Data
11607 : [Link](binomial(8,3)); [Link](binomial(10,2)); Output : 56 45
11608 </h4>
11609 <script>
11610 function binomial(n, k) {
11611 if (k < 0 || k > n) return 0;
11612 if (k === 0 || k === n) return 1;
11613 let numerator = 1;
11614 for (let i = n; i > [Link](k, n - k); i--) {
11615 numerator *= i;
11616 }
11617 let denominator = 1;
11618 for (let i = 1; i <= [Link](k, n - k); i++) {
11619 denominator *= i;
11620 }
11621 return numerator / denominator;
11622 }
11623
11624 // Test Data
11625 [Link](binomial(8, 3)); // Output: 56
11626 [Link](binomial(10, 2)); // Output: 45
11627 </script>
11628 <hr />
11629
11630 <h4>
11631 487. Write a JavaScript function that Convert an integer into a Roman
11632 Numeral in javaScript
11633 </h4>
11634 <script>
11635 function integerToRoman(num) {
11636 const romanNumerals = {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 195/298
1/31/24, 9:21 AM [Link]
11637 M: 1000,
11638 CM: 900,
11639 D: 500,
11640 CD: 400,
11641 C: 100,
11642 XC: 90,
11643 L: 50,
11644 XL: 40,
11645 X: 10,
11646 IX: 9,
11647 V: 5,
11648 IV: 4,
11649 I: 1,
11650 };
11651
11652 let roman = "";
11653
11654 for (let key in romanNumerals) {
11655 while (num >= romanNumerals[key]) {
11656 roman += key;
11657 num -= romanNumerals[key];
11658 }
11659 }
11660
11661 return roman;
11662 }
11663
11664 // Test Data
11665 [Link](integerToRoman(23)); // Output: XXIII
11666 </script>
11667 <hr />
11668
11669 <h4>
11670 488. Write a JavaScript function that Convert Roman Numeral to Integer
11671 </h4>
11672 <script>
11673 function romanToInteger(roman) {
11674 const romanNumerals = {
11675 M: 1000,
11676 CM: 900,
11677 D: 500,
11678 CD: 400,
11679 C: 100,
11680 XC: 90,
11681 L: 50,
11682 XL: 40,
11683 X: 10,
11684 IX: 9,
11685 V: 5,
11686 IV: 4,
11687 I: 1,
11688 };
11689
11690 let result = 0;
11691
11692 for (let i = 0; i < [Link]; i++) {
11693 if (
11694 i < [Link] - 1 &&
11695 romanNumerals[roman[i]] < romanNumerals[roman[i + 1]]
11696 ) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 196/298
1/31/24, 9:21 AM [Link]
11697 result -= romanNumerals[roman[i]];
11698 } else {
11699 result += romanNumerals[roman[i]];
11700 }
11701 }
11702
11703 return result;
11704 }
11705
11706 // Test Data
11707 [Link](romanToInteger("XXIII")); // Output: 23
11708 </script>
11709 <hr />
11710
11711 <h4>
11712 489. Write a JavaScript function to create a UUID identifier. Note :
11713 According to Wikipedia - A universally unique identifier (UUID) is an
11714 identifier standard used in software construction. A UUID is simply a
11715 128-bit value. The meaning of each bit is defined by any of several
11716 variants. For human-readable display, many systems use a canonical format
11717 using hexadecimal text with inserted hyphen characters. For example :
11718 de305d54-75b4-431b-adb2-eb6b9e546014
11719 </h4>
11720 <script>
11721 function generateUUID() {
11722 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
11723 /[xy]/g,
11724 function (c) {
11725 var r = ([Link]() * 16) | 0,
11726 v = c === "x" ? r : (r & 0x3) | 0x8;
11727 return [Link](16);
11728 }
11729 );
11730 }
11731
11732 // Test Data
11733 [Link](generateUUID()); // Output: a UUID identifier
11734 </script>
11735 <hr />
11736
11737 <h4>
11738 490. Write a JavaScript function to round a number to a specified number
11739 of digits and strip extra zeros (if any). Test Data : var a = -4.55555;
11740 [Link](result); -4.5556 var a = 5.0001000; [Link](result);
11741 5.0001
11742 </h4>
11743 <script>
11744 function roundAndStrip(num, digits) {
11745 return parseFloat([Link](digits)).toString();
11746 }
11747
11748 // Test Data
11749 [Link](roundAndStrip(-4.55555, 4)); // Output: -4.5556
11750 [Link](roundAndStrip(5.0001, 4)); // Output: 5.0001
11751 </script>
11752 <hr />
11753
11754 <h4>
11755 491. Write a JavaScript function to make currency math (add, subtract,
11756 multiply, division etc.). Test Data : n1 = '$40.24', n2 = '$21.57';
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 197/298
1/31/24, 9:21 AM [Link]
11757 </h4>
11758 <script>
11759 function currencyMath(n1, n2) {
11760 const num1 = parseFloat([Link]("$", ""));
11761 const num2 = parseFloat([Link]("$", ""));
11762 return {
11763 add: (num1 + num2).toFixed(2),
11764 subtract: (num1 - num2).toFixed(2),
11765 multiply: (num1 * num2).toFixed(2),
11766 divide: (num1 / num2).toFixed(2),
11767 };
11768 }
11769
11770 // Test Data
11771 const { add, subtract, multiply, divide } = currencyMath(
11772 "$40.24",
11773 "$21.57"
11774 );
11775 [Link](`Addition: $${add}`);
11776 [Link](`Subtraction: $${subtract}`);
11777 [Link](`Multiplication: $${multiply}`);
11778 [Link](`Division: $${divide}`);
11779 </script>
11780 <hr />
11781
11782 <h4>
11783 492. Write a JavaScript function to calculate the nth root of a number.
11784 Test Data : [Link](nthroot(64, 2)); 8 [Link](nthroot(64, -2));
11785 0.125
11786 </h4>
11787 <script>
11788 function nthRoot(number, n) {
11789 return [Link](number, 1 / n);
11790 }
11791
11792 // Test Data
11793 [Link](nthRoot(64, 2)); // Output: 8
11794 [Link](nthRoot(64, -2)); // Output: 0.125
11795 </script>
11796 <hr />
11797
11798 <h4>
11799 493. Write a JavaScript function to calculate degrees between 2 points
11800 with inverse Y axis. Test Data : [Link](pointDirection(1, 0, 12, 0));
11801 0 [Link](pointDirection(1, 0, 1, 10)); 90
11802 </h4>
11803 <script>
11804 function pointDirection(x1, y1, x2, y2) {
11805 // Calculate the angle from (x1, y1) to (x2, y2) in radians
11806 let angleRad = Math.atan2(y2 - y1, x2 - x1);
11807
11808 // Convert radians to degrees
11809 let angleDeg = angleRad * (180 / [Link]);
11810
11811 // Adjust angle for inverse Y-axis
11812 angleDeg = angleDeg < 0 ? angleDeg + 360 : angleDeg;
11813
11814 return angleDeg;
11815 }
11816
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 198/298
1/31/24, 9:21 AM [Link]
11817 // Test Data
11818 [Link](pointDirection(1, 0, 12, 0)); // Output: 0
11819 [Link](pointDirection(1, 0, 1, 10)); // Output: 90
11820 </script>
11821 <hr />
11822
11823 <script>
11824 // 494. JavaScript function to round up an integer value to the next multiple of 5
11825 function int_round5(num) {
11826 return [Link](num / 5) * 5;
11827 }
11828
11829 // Test Data
11830 [Link](int_round5(32)); // Output: 35
11831 [Link](int_round5(137)); // Output: 140
11832 </script>
11833
11834 <script>
11835 // 495. JavaScript function to convert a positive number to negative number
11836 function pos_to_neg(num) {
11837 return -[Link](num);
11838 }
11839
11840 // Test Data
11841 [Link](pos_to_neg(15)); // Output: -15
11842 </script>
11843
11844 <script>
11845 // 496. JavaScript function to cast a square root of a number to an integer
11846 function sqrt_to_int(num) {
11847 return [Link]([Link](num));
11848 }
11849
11850 // Test Data
11851 [Link](sqrt_to_int(17)); // Output: 4
11852 </script>
11853
11854 <script>
11855 // 497. JavaScript function to get the highest number from three different numbers
11856 function highest_of_three(num1, num2, num3) {
11857 return [Link](num1, num2, num3);
11858 }
11859
11860 // Test Data
11861 [Link](highest_of_three(-5, 4, 2)); // Output: 4
11862 </script>
11863
11864 <script>
11865 // 498. JavaScript function to calculate the percentage (%) of a number
11866 function percentage(num, percent) {
11867 return (num * percent) / 100;
11868 }
11869
11870 // Test Data
11871 [Link](percentage(1000, 47.12)); // Output: 471.2
11872 </script>
11873
11874 <script>
11875 // 499. JavaScript function to convert an angle from degrees to radians
11876 function degrees_to_radians(degrees) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 199/298
1/31/24, 9:21 AM [Link]
11877 return degrees * ([Link] / 180);
11878 }
11879
11880 // Test Data
11881 [Link](degrees_to_radians(45)); // Output: 0.7853981633974483
11882 </script>
11883
11884 <script>
11885 // 500. JavaScript function to convert radians to degrees
11886 function radians_to_degrees(radians) {
11887 return radians * (180 / [Link]);
11888 }
11889
11890 // Test Data
11891 [Link](radians_to_degrees(0.7853981633974483)); // Output: 45
11892 </script>
11893 <hr />
11894
11895 <!-- ---------------------------------------- 601 - 756 ---------------------------
-->
11896 <!-- Question 601 -->
11897 <h3>Question 601:</h3>
11898 <p>Write a JavaScript function to get the difference to Greenwich time (GMT) in hours.<
/p>
11899
11900 <!-- Answer 601 -->
11901 <script>
11902 function diff_to_GMT(dt) {
11903 const offsetInMinutes = [Link]();
11904 const offsetInHours = offsetInMinutes / 60;
11905 const sign = offsetInHours > 0 ? '+' : '-';
11906 const hours = [Link]([Link](offsetInHours));
11907 const minutes = [Link](offsetInMinutes % 60);
11908
11909 return `${sign}${hours}.${minutes}`;
11910 }
11911 </script>
11912
11913 <!-- Question 602 -->
11914 <h3>Question 602:</h3>
11915 <p>Write a JavaScript function to get the timezone offset in seconds.</p>
11916
11917 <!-- Answer 602 -->
11918 <script>
11919 function timezone_offset_in_seconds(dt) {
11920 return [Link]() * 60;
11921 }
11922 </script>
11923
11924 <!-- Question 603 -->
11925 <h3>Question 603:</h3>
11926 <p>Write a JavaScript function to add specified years to a date.</p>
11927
11928 <!-- Answer 603 -->
11929 <script>
11930 function add_years(dt, years) {
11931 return new Date([Link]() + years, [Link](), [Link](),
[Link](), [Link](), [Link]());
11932 }
11933 </script>
11934
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 200/298
1/31/24, 9:21 AM [Link]
11935 <!-- Question 604 -->
11936 <h3>Question 604:</h3>
11937 <p>Write a JavaScript function to add specified weeks to a date.</p>
11938
11939 <!-- Answer 604 -->
11940 <script>
11941 function add_weeks(dt, weeks) {
11942 return new Date([Link]() + weeks * 7 * 24 * 60 * 60 * 1000);
11943 }
11944 </script>
11945
11946 <!-- Question 605 -->
11947 <h3>Question 605:</h3>
11948 <p>Write a JavaScript function to add specified months to a date.</p>
11949
11950 <!-- Answer 605 -->
11951 <script>
11952 function add_months(dt, months) {
11953 return new Date([Link](), [Link]() + months, [Link](),
[Link](), [Link](), [Link]());
11954 }
11955 </script>
11956
11957 <!-- Question 606 -->
11958 <h3>Question 606:</h3>
11959 <p>Write a JavaScript function to get time differences in minutes between two dates.</p>
11960
11961 <!-- Answer 606 -->
11962 <script>
11963 function get_time_difference_in_minutes(dt1, dt2) {
11964 const diffInMilliseconds = [Link](dt2 - dt1);
11965 return [Link](diffInMilliseconds / (60 * 1000));
11966 }
11967 </script>
11968 <!-- Question 607 -->
11969 <h3>Question 607:</h3>
11970 <p>Write a JavaScript function to get time differences in hours between two dates.</p>
11971
11972 <!-- Answer 607 -->
11973 <script>
11974 function diff_hours(dt1, dt2) {
11975 const diffInMilliseconds = [Link](dt2 - dt1);
11976 return [Link](diffInMilliseconds / (60 * 60 * 1000));
11977 }
11978 </script>
11979
11980 <!-- Question 608 -->
11981 <h3>Question 608:</h3>
11982 <p>Write a JavaScript function to get time differences in days between two dates.</p>
11983
11984 <!-- Answer 608 -->
11985 <script>
11986 function diff_days(dt1, dt2) {
11987 const diffInMilliseconds = [Link](dt2 - dt1);
11988 return [Link](diffInMilliseconds / (24 * 60 * 60 * 1000));
11989 }
11990 </script>
11991
11992 <!-- Question 609 -->
11993 <h3>Question 609:</h3>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 201/298
1/31/24, 9:21 AM [Link]
11994 <p>Write a JavaScript function to get time differences in weeks between two dates.</p>
11995
11996 <!-- Answer 609 -->
11997 <script>
11998 function diff_weeks(dt1, dt2) {
11999 const diffInMilliseconds = [Link](dt2 - dt1);
12000 return [Link](diffInMilliseconds / (7 * 24 * 60 * 60 * 1000));
12001 }
12002 </script>
12003
12004 <!-- Question 610 -->
12005 <h3>Question 610:</h3>
12006 <p>Write a JavaScript function to get time differences in months between two dates.</p>
12007
12008 <!-- Answer 610 -->
12009 <script>
12010 function diff_months(dt1, dt2) {
12011 const diffInMonths = ([Link]() - [Link]()) * 12 +
([Link]() - [Link]());
12012 return [Link](diffInMonths);
12013 }
12014 </script>
12015
12016 <!-- Question 611 -->
12017 <h3>Question 611:</h3>
12018 <p>Write a JavaScript function to get time differences in years between two dates.</p>
12019
12020 <!-- Answer 611 -->
12021 <script>
12022 function diff_years(dt1, dt2) {
12023 const diffInYears = [Link]() - [Link]();
12024 return [Link](diffInYears);
12025 }
12026 </script>
12027
12028 <!-- Question 612 -->
12029 <h3>Question 612:</h3>
12030 <p>Write a JavaScript function to get the week start date.</p>
12031
12032 <!-- Answer 612 -->
12033 <script>
12034 function get_week_start_date(dt) {
12035 const dayOfWeek = [Link]();
12036 const startOfWeek = new Date(dt);
12037 [Link]([Link]() - dayOfWeek);
12038 return startOfWeek;
12039 }
12040 </script>
12041
12042 <!-- Question 613 -->
12043 <h3>Question 613:</h3>
12044 <p>Write a JavaScript function to get the week end date.</p>
12045
12046 <!-- Answer 613 -->
12047 <script>
12048 function get_week_end_date(dt) {
12049 const dayOfWeek = [Link]();
12050 const endOfWeek = new Date(dt);
12051 [Link]([Link]() + (6 - dayOfWeek));
12052 return endOfWeek;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 202/298
1/31/24, 9:21 AM [Link]
12053 }
12054 </script>
12055
12056 <!-- Question 614 -->
12057 <h3>Question 614:</h3>
12058 <p>Write a JavaScript function to get the month start date.</p>
12059
12060 <!-- Answer 614 -->
12061 <script>
12062 function get_month_start_date(dt) {
12063 return new Date([Link](), [Link](), 1);
12064 }
12065 </script>
12066
12067 <!-- Question 615 -->
12068 <h3>Question 615:</h3>
12069 <p>Write a JavaScript function to get the month end date.</p>
12070
12071 <!-- Answer 615 -->
12072 <script>
12073 function get_month_end_date(dt) {
12074 return new Date([Link](), [Link]() + 1, 0);
12075 }
12076 </script>
12077
12078 <!-- Question 616 -->
12079 <h3>Question 616:</h3>
12080 <p>Write a JavaScript function to check whether an `input` is a string or not.</p>
12081
12082 <!-- Answer 616 -->
12083 <script>
12084 function is_string(input) {
12085 return typeof input === 'string';
12086 }
12087 </script>
12088 <!-- Question 617 -->
12089 <h3>Question 617:</h3>
12090 <p>Write a JavaScript function to check whether a string is blank or not.</p>
12091
12092 <!-- Answer 617 -->
12093 <script>
12094 function is_Blank(str) {
12095 return [Link]() === '';
12096 }
12097 </script>
12098
12099 <!-- Question 618 -->
12100 <h3>Question 618:</h3>
12101 <p>Write a JavaScript function to split a string and convert it into an array of words.<
/p>
12102
12103 <!-- Answer 618 -->
12104 <script>
12105 function string_to_array(str) {
12106 return [Link](' ');
12107 }
12108 </script>
12109
12110 <!-- Question 619 -->
12111 <h3>Question 619:</h3>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 203/298
1/31/24, 9:21 AM [Link]
12112 <p>Write a JavaScript function to extract a specified number of characters from a
string.</p>
12113
12114 <!-- Answer 619 -->
12115 <script>
12116 function truncate_string(str, num) {
12117 return [Link](0, num);
12118 }
12119 </script>
12120
12121 <!-- Question 620 -->
12122 <h3>Question 620:</h3>
12123 <p>Write a JavaScript function to convert a string in abbreviated form.</p>
12124
12125 <!-- Answer 620 -->
12126 <script>
12127 function abbrev_name(str) {
12128 const words = [Link](' ');
12129 const firstName = words[0];
12130 const lastName = [Link] > 1 ? words[1][0] + '.' : '';
12131 return `${firstName} ${lastName}`;
12132 }
12133 </script>
12134
12135 <!-- Question 621 -->
12136 <h3>Question 621:</h3>
12137 <p>Write a JavaScript function to hide email addresses to protect from unauthorized
users.</p>
12138
12139 <!-- Answer 621 -->
12140 <script>
12141 function protect_email(email) {
12142 const atIndex = [Link]('@');
12143 const username = [Link](0, atIndex);
12144 const protectedEmail = [Link] > 2 ? [Link](0, 2) + '...' +
[Link](atIndex) : email;
12145 return protectedEmail;
12146 }
12147 </script>
12148
12149 <!-- Question 622 -->
12150 <h3>Question 622:</h3>
12151 <p>Write a JavaScript function to parameterize a string.</p>
12152
12153 <!-- Answer 622 -->
12154 <script>
12155 function string_parameterize(str) {
12156 return [Link]().replace(/[^a-zA-Z0-9]/g, '-');
12157 }
12158 </script>
12159
12160 <!-- Question 623 -->
12161 <h3>Question 623:</h3>
12162 <p>Write a JavaScript function to capitalize the first letter of a string.</p>
12163
12164 <!-- Answer 623 -->
12165 <script>
12166 function capitalize(str) {
12167 return [Link](0).toUpperCase() + [Link](1);
12168 }
12169 </script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 204/298
1/31/24, 9:21 AM [Link]
12170
12171 <!-- Question 624 -->
12172 <h3>Question 624:</h3>
12173 <p>Write a JavaScript function to capitalize the first letter of each word in a string.<
/p>
12174
12175 <!-- Answer 624 -->
12176 <script>
12177 function capitalize_Words(str) {
12178 return [Link](/\b\w/g, (char) => [Link]());
12179 }
12180 </script>
12181
12182 <!-- Question 625 -->
12183 <h3>Question 625:</h3>
12184 <p>Write a JavaScript function that takes a string with lower and upper case letters and
converts upper case letters to lower case, and lower case letters to upper case.</p>
12185
12186 <!-- Answer 625 -->
12187 <script>
12188 function swapcase(str) {
12189 return [Link](/[a-zA-Z]/g, (char) => {
12190 return char === [Link]() ? [Link]() : [Link]()
;
12191 });
12192 }
12193 </script>
12194
12195 <!-- Question 626 -->
12196 <h3>Question 626:</h3>
12197 <p>Write a JavaScript function to convert a string into camel case.
12198 Test Data :
12199 [Link](camelize("JavaScript Exercises"));
12200 make question and answer in html format and give implementation answer also
[Link](camelize("JavaScript exercises"));
12201 [Link](camelize("JavaScriptExercises"));
12202 "JavaScriptExercises"
12203 "JavaScriptExercises"
12204 "JavaScriptExercises"
12205 </p>
12206
12207 <!-- Answer 626 -->
12208 <script>
12209 <script>
12210 function camelize(str) {
12211 return [Link](/(?:^\w|[A-Z]|\b\w)/g, (match, index) => index === 0 ?
[Link]() : [Link]()).replace(/\s+/g, '');
12212 }
12213 </script>
12214 <!-- Question 627 -->
12215 <h3>Question 627:</h3>
12216 <p>Write a JavaScript function to uncamelize a string.</p>
12217
12218 <!-- Answer 627 -->
12219 <script>
12220 function uncamelize(str, separator = ' ') {
12221 return [Link](/[A-Z]/g, match => `${separator}${[Link]()}`)
.trim();
12222 }
12223 </script>
12224
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 205/298
1/31/24, 9:21 AM [Link]
12225 <!-- Question 628 -->
12226 <h3>Question 628:</h3>
12227 <p>Write a JavaScript function to concatenate a given string n times (default is 1).</p>
12228
12229 <!-- Answer 628 -->
12230 <script>
12231 function repeat(str, n = 1) {
12232 return [Link](n);
12233 }
12234 </script>
12235
12236 <!-- Question 629 -->
12237 <h3>Question 629:</h3>
12238 <p>Write a JavaScript function to insert a string within a string at a particular
position (default is 1).</p>
12239
12240 <!-- Answer 629 -->
12241 <script>
12242 function insert(original, insertStr, position = 1) {
12243 return [Link](0, position) + insertStr + [Link](position);
12244 }
12245 </script>
12246
12247 <!-- Question 630 -->
12248 <h3>Question 630:</h3>
12249 <p>Write a JavaScript function to humanize a number with the correct suffix such as 1st,
2nd, 3rd, or 4th.</p>
12250
12251 <!-- Answer 630 -->
12252 <script>
12253 function humanize_format(number) {
12254 if (typeof number !== 'number') return 'Invalid input';
12255 const suffix = (number % 100 >= 11 && number % 100 <= 13) ? 'th' : {1: 'st', 2:
'nd', 3: 'rd'}[number % 10] || 'th';
12256 return `${number}${suffix}`;
12257 }
12258 </script>
12259
12260 <!-- Question 631 -->
12261 <h3>Question 631:</h3>
12262 <p>Write a JavaScript function to truncate a string if it is longer than the specified
number of characters. Truncated strings will end with a translatable ellipsis sequence
("…") (by default) or specified characters.</p>
12263
12264 <!-- Answer 631 -->
12265 <script>
12266 function text_truncate(str, length, ending = '…') {
12267 return length === undefined || [Link] <= length ? str : [Link](0, length)
+ ending;
12268 }
12269 </script>
12270 <!-- Question 632 -->
12271 <h3>Question 632:</h3>
12272 <p>Write a JavaScript function to chop a string into chunks of a given length.</p>
12273
12274 <!-- Answer 632 -->
12275 <script>
12276 function string_chop(str, length) {
12277 if (length === undefined || length <= 0) return ['Invalid length'];
12278 return length >= [Link] ? [str] : [Link](new RegExp(`.{1,${length}}`, 'g'
)) || [];
12279 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 206/298
1/31/24, 9:21 AM [Link]
12280 </script>
12281
12282 <!-- Question 633 -->
12283 <h3>Question 633:</h3>
12284 <p>Write a JavaScript function to count the occurrence of a substring in a string.</p>
12285
12286 <!-- Answer 633 -->
12287 <script>
12288 function count(str, substr, caseSensitive = true) {
12289 const flags = caseSensitive ? 'g' : 'gi';
12290 return ([Link](new RegExp(substr, flags)) || []).length;
12291 }
12292 </script>
12293
12294 <!-- Question 634 -->
12295 <h3>Question 634:</h3>
12296 <p>Write a JavaScript function to escape an HTML string.</p>
12297
12298 <!-- Answer 634 -->
12299 <script>
12300 function escape_HTML(str) {
12301 return [Link](/[&<>"']/g, match => ({
12302 '&': '&',
12303 '<': '<',
12304 '>': '>',
12305 '"': '"',
12306 "'": '''
12307 }[match]));
12308 }
12309 </script>
12310
12311 <!-- Question 635 -->
12312 <h3>Question 635:</h3>
12313 <p>Write a JavaScript function that can pad (left, right) a string to get to a
determined length.</p>
12314
12315 <!-- Answer 635 -->
12316 <script>
12317 function formatted_string(pad, value, side) {
12318 return side === 'l' ? (pad + value).slice(-[Link]) : (value + pad)
.substring(0, [Link]);
12319 }
12320 </script>
12321
12322 <!-- Question 636 -->
12323 <h3>Question 636:</h3>
12324 <p>Write a JavaScript function to repeat a string a specified times.</p>
12325
12326 <!-- Answer 636 -->
12327 <script>
12328 function repeat_string(str, count) {
12329 return count > 0 ? [Link](count) : 'Error in string or count.';
12330 }
12331 </script>
12332
12333 <!-- Question 637 -->
12334 <h3>Question 637:</h3>
12335 <p>Write a JavaScript function to get a part of a string after a specified character.<
/p>
12336
12337 <!-- Answer 637 -->
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 207/298
1/31/24, 9:21 AM [Link]
12338 <script>
12339 function subStrAfterChars(str, char, inclusive = false) {
12340 const index = [Link](char);
12341 return index !== -1 ? [Link](index + (inclusive ? 0 : 1)) : str;
12342 }
12343 </script>
12344
12345 <!-- Question 638 -->
12346 <h3>Question 638:</h3>
12347 <p>Write a JavaScript function to strip leading and trailing spaces from a string.</p>
12348
12349 <!-- Answer 638 -->
12350 <script>
12351 function strip(str) {
12352 return [Link]();
12353 }
12354 </script>
12355 <!-- Question 639 -->
12356 <h3>Question 639:</h3>
12357 <p>Write a JavaScript function to truncate a string to a certain number of words.</p>
12358
12359 <!-- Answer 639 -->
12360 <script>
12361 function truncate(str, numWords) {
12362 const words = [Link](' ');
12363 return [Link](0, numWords).join(' ');
12364 }
12365 </script>
12366
12367 <!-- Question 640 -->
12368 <h3>Question 640:</h3>
12369 <p>Write a JavaScript function to alphabetize a given string.</p>
12370
12371 <!-- Answer 640 -->
12372 <script>
12373 function alphabetize_string(str) {
12374 return [Link]('').sort().join('');
12375 }
12376 </script>
12377
12378 <!-- Question 641 -->
12379 <h3>Question 641:</h3>
12380 <p>Write a JavaScript function to remove the first occurrence of a given 'search string'
from a string.</p>
12381
12382 <!-- Answer 641 -->
12383 <script>
12384 function remove_first_occurrence(str, search) {
12385 const index = [Link](search);
12386 return index !== -1 ? [Link](0, index) + [Link](index + [Link]) :
str;
12387 }
12388 </script>
12389
12390 <!-- Question 642 -->
12391 <h3>Question 642:</h3>
12392 <p>Write a JavaScript function to convert ASCII to Hexadecimal format.</p>
12393
12394 <!-- Answer 642 -->
12395 <script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 208/298
1/31/24, 9:21 AM [Link]
12396 function ascii_to_hexa(str) {
12397 return [Link]('').map(char => [Link](0).toString(16)).join('');
12398 }
12399 </script>
12400
12401 <!-- Question 643 -->
12402 <h3>Question 643:</h3>
12403 <p>Write a JavaScript function to convert Hexadecimal to ASCII format.</p>
12404
12405 <!-- Answer 643 -->
12406 <script>
12407 function hex_to_ascii(str) {
12408 return [Link](/.{1,2}/g).map(hex => [Link](parseInt(hex, 16)))
.join('');
12409 }
12410 </script>
12411
12412 <!-- Question 644 -->
12413 <h3>Question 644:</h3>
12414 <p>Write a JavaScript function to find a word within a string.</p>
12415
12416 <!-- Answer 644 -->
12417 <script>
12418 function search_word(str, word) {
12419 const regex = new RegExp(word, 'g');
12420 const occurrences = [Link](regex) || [];
12421 return `'${word}' was found ${[Link]} times.`;
12422 }
12423 </script>
12424
12425 <!-- Question 645 -->
12426 <h3>Question 645:</h3>
12427 <p>Write a JavaScript function to check if a string ends with specified suffix.</p>
12428
12429 <!-- Answer 645 -->
12430 <script>
12431 function string_endsWith(str, suffix) {
12432 return [Link](suffix);
12433 }
12434 </script>
12435
12436 <!-- Question 646 -->
12437 <h3>Question 646:</h3>
12438 <p>Write a JavaScript function to escape special characters (&, <, >, ', ") for use in
HTML.</p>
12439
12440 <!-- Answer 646 -->
12441 <script>
12442 function escape_html(str) {
12443 const escapeMap = {
12444 '&': '&',
12445 '<': '<',
12446 '>': '>',
12447 "'": ''',
12448 '"': '"'
12449 };
12450 return [Link](/[&<>'"]/g, match => escapeMap[match]);
12451 }
12452 </script>
12453 <!-- Question 647 -->
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 209/298
1/31/24, 9:21 AM [Link]
12454 <h3>Question 647:</h3>
12455 <p>Write a JavaScript function to remove non-printable ASCII chars.</p>
12456
12457 <!-- Answer 647 -->
12458 <script>
12459 function remove_non_ascii(str) {
12460 return [Link](/[^\x20-\x7E]/g, '');
12461 }
12462 </script>
12463
12464 <!-- Question 648 -->
12465 <h3>Question 648:</h3>
12466 <p>Write a JavaScript function to remove non-word characters.</p>
12467
12468 <!-- Answer 648 -->
12469 <script>
12470 function remove_non_word(str) {
12471 return [Link](/\W/g, ' ');
12472 }
12473 </script>
12474
12475 <!-- Question 649 -->
12476 <h3>Question 649:</h3>
12477 <p>Write a JavaScript function to convert a string to title case.</p>
12478
12479 <!-- Answer 649 -->
12480 <script>
12481 function sentenceCase(str) {
12482 return [Link](/\w\S*/g, function (txt) {
12483 return [Link](0).toUpperCase() + [Link](1).toLowerCase();
12484 });
12485 }
12486 </script>
12487
12488 <!-- Question 650 -->
12489 <h3>Question 650:</h3>
12490 <p>Write a JavaScript function to remove HTML/XML tags from a string.</p>
12491
12492 <!-- Answer 650 -->
12493 <script>
12494 function strip_html_tags(str) {
12495 return [Link](/<[^>]*>/g, '');
12496 }
12497 </script>
12498
12499 <!-- Question 651 -->
12500 <h3>Question 651:</h3>
12501 <p>Write a JavaScript function to create a Zerofilled value with an optional +, - sign.<
/p>
12502
12503 <!-- Answer 651 -->
12504 <script>
12505 function zeroFill(num, width, sign) {
12506 const paddedNum = [Link]().padStart(width, '0');
12507 return sign ? sign + paddedNum : paddedNum;
12508 }
12509 </script>
12510
12511 <!-- Question 652 -->
12512 <h3>Question 652:</h3>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 210/298
1/31/24, 9:21 AM [Link]
12513 <p>Write a JavaScript function to test case-insensitive (except special Unicode
characters) string comparison.</p>
12514
12515 <!-- Answer 652 -->
12516 <script>
12517 function compare_strings(str1, str2) {
12518 return [Link](str2, undefined, { sensitivity: 'base' }) === 0;
12519 }
12520 </script>
12521
12522 <!-- Question 653 -->
12523 <h3>Question 653:</h3>
12524 <p>Write a JavaScript function to create a case-insensitive search.</p>
12525
12526 <!-- Answer 653 -->
12527 <script>
12528 function case_insensitive_search(str, searchTerm) {
12529 const regex = new RegExp(searchTerm, 'i');
12530 return [Link](str) ? 'Matched' : 'Not Matched';
12531 }
12532 </script>
12533
12534 <!-- Question 654 -->
12535 <h3>Question 654:</h3>
12536 <p>Write a JavaScript function to Uncapitalize the first character of a string.</p>
12537
12538 <!-- Answer 654 -->
12539 <script>
12540 function Uncapitalize(str) {
12541 return [Link](0).toLowerCase() + [Link](1);
12542 }
12543 </script>
12544
12545 <!-- Question 655 -->
12546 <h3>Question 655:</h3>
12547 <p>Write a JavaScript function to Uncapitalize the first letter of each word of a
string.</p>
12548
12549 <!-- Answer 655 -->
12550 <script>
12551 function unCapitalize_Words(str) {
12552 return [Link](/\b[A-Z]/g, function (match) {
12553 return [Link]();
12554 });
12555 }
12556 </script>
12557 <!-- Question 656 -->
12558 <h3>Question 656:</h3>
12559 <p>Write a JavaScript function to capitalize each word in the string.</p>
12560
12561 <!-- Answer 656 -->
12562 <script>
12563 function capitalizeWords(str) {
12564 return [Link]();
12565 }
12566 </script>
12567
12568 <!-- Question 657 -->
12569 <h3>Question 657:</h3>
12570 <p>Write a JavaScript function to uncapitalize each word in the string.</p>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 211/298
1/31/24, 9:21 AM [Link]
12571
12572 <!-- Answer 657 -->
12573 <script>
12574 function unCapitalizeWords(str) {
12575 return [Link]();
12576 }
12577 </script>
12578
12579 <!-- Question 658 -->
12580 <h3>Question 658:</h3>
12581 <p>Write a JavaScript function to test whether the character at the provided (character)
index is upper case.</p>
12582
12583 <!-- Answer 658 -->
12584 <script>
12585 function isUpperCaseAt(str, index) {
12586 return [Link](index) === [Link](index).toUpperCase();
12587 }
12588 </script>
12589
12590 <!-- Question 659 -->
12591 <h3>Question 659:</h3>
12592 <p>Write a JavaScript function to test whether the character at the provided (character)
index is lower case.</p>
12593
12594 <!-- Answer 659 -->
12595 <script>
12596 function isLowerCaseAt(str, index) {
12597 return [Link](index) === [Link](index).toLowerCase();
12598 }
12599 </script>
12600
12601 <!-- Question 660 -->
12602 <h3>Question 660:</h3>
12603 <p>Write a JavaScript function to get humanized number with the correct suffix such as
1st, 2nd, 3rd or 4th.</p>
12604
12605 <!-- Answer 660 -->
12606 <script>
12607 function humanize(number) {
12608 const suffixes = ["th", "st", "nd", "rd"];
12609 const remainder = number % 100;
12610 const suffix = suffixes[(remainder - 20) % 10] || suffixes[remainder] ||
suffixes[0];
12611 return number + suffix;
12612 }
12613 </script>
12614
12615 <!-- Question 661 -->
12616 <h3>Question 661:</h3>
12617 <p>Write a JavaScript function to test whether a string starts with a specified string.<
/p>
12618
12619 <!-- Answer 661 -->
12620 <script>
12621 function startsWith(str, prefix) {
12622 return [Link](prefix);
12623 }
12624 </script>
12625
12626 <!-- Question 662 -->
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 212/298
1/31/24, 9:21 AM [Link]
12627 <h3>Question 662:</h3>
12628 <p>Write a JavaScript function to test whether a string ends with a specified string.<
/p>
12629
12630 <!-- Answer 662 -->
12631 <script>
12632 function endsWith(str, suffix) {
12633 return [Link](suffix);
12634 }
12635 </script>
12636
12637 <!-- Question 663 -->
12638 <h3>Question 663:</h3>
12639 <p>Write a JavaScript function to get the successor of a string.</p>
12640
12641 <!-- Answer 663 -->
12642 <script>
12643 [Link] = function () {
12644 const validChars = /^[0-9a-zA-Z]+$/;
12645 let str = this;
12646 if () return str;
12647
12648 let i = [Link] - 1;
12649 let carry = 1;
12650 let result = '';
12651
12652 while (i >= 0) {
12653 const char = str[i];
12654 if ([Link](validChars)) {
12655 let code = [Link](0) + carry;
12656 carry = [Link](code / 10);
12657 code %= 10;
12658 result = [Link](code + '0'.charCodeAt(0)) + result;
12659 } else {
12660 result = char + result;
12661 }
12662 i--;
12663 }
12664
12665 if (carry > 0) {
12666 while (carry > 0) {
12667 result = [Link]((carry % 10) + '0'.charCodeAt(0)) + result;
12668 carry = [Link](carry / 10);
12669 }
12670 }
12671
12672 return result;
12673 };
12674 </script>
12675 <!-- Question 664 -->
12676 <h3>Question 664:</h3>
12677 <p>Write a JavaScript function to get a unique GUID (Globally Unique Identifier) of the
specified length, or 32 by default.</p>
12678
12679 <!-- Answer 664 -->
12680 <script>
12681 function guid(length = 32) {
12682 const characters = 'abcdef0123456789';
12683 let result = '';
12684 for (let i = 0; i < length; i++) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 213/298
1/31/24, 9:21 AM [Link]
12685 result += characters[[Link]([Link]() * [Link])];
12686 }
12687 return result;
12688 }
12689 </script>
12690
12691 <!-- Question 665 -->
12692 <h3>Question 665:</h3>
12693 <p>Write a JavaScript program to test if the first character of a string is uppercase or
not.</p>
12694
12695 <!-- Answer 665 -->
12696 <script>
12697 function isFirstCharUppercase(str) {
12698 return str[0] === str[0].toUpperCase();
12699 }
12700 </script>
12701 <!-- Question 665 -->
12702 <h3>Question 665:</h3>
12703 <p>Write a JavaScript program to test if the first character of a string is uppercase or
not.</p>
12704
12705 <!-- Answer 665 -->
12706 <script>
12707 function isFirstCharUppercase(str) {
12708 return str[0] === str[0].toUpperCase();
12709 }
12710
12711 // Example usage
12712 const testString1 = "Hello";
12713 const testString2 = "world";
12714
12715 [Link](`Is "${testString1}" starts with uppercase?
${isFirstCharUppercase(testString1)}`);
12716 [Link](`Is "${testString2}" starts with uppercase?
${isFirstCharUppercase(testString2)}`);
12717 </script>
12718
12719 <!-- Question 666 -->
12720 <h3>Question 666:</h3>
12721 <p>Write a JavaScript program to check a credit card number.</p>
12722
12723 <!-- Answer 666 -->
12724 <script>
12725 function isValidCreditCard(cardNumber) {
12726 // Implementation goes here...
12727 }
12728
12729 // Example usage
12730 const creditCardNumber = "1234-5678-9012-3456";
12731 [Link](`Is "${creditCardNumber}" a valid credit card number?
${isValidCreditCard(creditCardNumber)}`);
12732 </script>
12733
12734 <!-- Question 667 -->
12735 <h3>Question 667:</h3>
12736 <p>Write a pattern that matches e-mail addresses.</p>
12737
12738 <!-- Answer 667 -->
12739 <script>
12740 function isValidEmail(email) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 214/298
1/31/24, 9:21 AM [Link]
12741 const emailPattern = /^[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'
*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
12742 return [Link](email);
12743 }
12744
12745 // Example usage
12746 const testEmail = "test@[Link]";
12747 [Link](`Is "${testEmail}" a valid email address? ${isValidEmail(testEmail)}`);
12748 </script>
12749
12750 <!-- Question 668 -->
12751 <h3>Question 668:</h3>
12752 <p>Write a JavaScript program to search a date within a string.</p>
12753
12754 <!-- Answer 668 -->
12755 <script>
12756 function findDateInString(inputString) {
12757 const datePattern = /\b\d{1,2}\/\d{1,2}\/\d{4}\b/g;
12758 return [Link](datePattern);
12759 }
12760
12761 // Example usage
12762 const testString = "Meeting on 12/31/2022 and 01/15/2023";
12763 [Link](`Dates found in "${testString}": ${findDateInString(testString)}`);
12764 </script>
12765
12766 <!-- Question 669 -->
12767 <h3>Question 669:</h3>
12768 <p>Write a JavaScript program that works as a trim function (string) using regular
expressions.</p>
12769
12770 <!-- Answer 669 -->
12771 <script>
12772 function customTrim(inputString) {
12773 return [Link](/^\s+|\s+$/g, '').replace(/\s+/g, ' ');
12774 }
12775
12776 // Example usage
12777 const testStringWithSpaces = " This is a test string. ";
12778 [Link](`Original string: "${testStringWithSpaces}"`);
12779 [Link](`After custom trim: "${customTrim(testStringWithSpaces)}"`);
12780 </script>
12781
12782 <!-- Question 670 -->
12783 <h3>Question 670:</h3>
12784 <p>Write a JavaScript program to count the number of words in a string.</p>
12785
12786 <!-- Answer 670 -->
12787 <script>
12788 function countWords(inputString) {
12789 const trimmedString = [Link]();
12790 const wordsArray = [Link](/\s+/);
12791 return [Link];
12792 }
12793
12794 // Example usage
12795 const testStringWithWords = "This is a test string.";
12796 [Link](`Number of words in "${testStringWithWords}":
${countWords(testStringWithWords)}`);
12797 </script>
12798
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 215/298
1/31/24, 9:21 AM [Link]
12799 <!-- Question 671 -->
12800 <h3>Question 671:</h3>
12801 <p>Write a JavaScript function to check whether a given value is an IP value or not.</p>
12802
12803 <!-- Answer 671 -->
12804 <script>
12805 function isIPAddress(value) {
12806 const ipAddressPattern = /^(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.){3}
(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$/;
12807 return [Link](value);
12808 }
12809
12810 // Example usage
12811 const testIPAddress = "[Link]";
12812 [Link](`Is "${testIPAddress}" a valid IP address? ${isIPAddress(testIPAddress)}
`);
12813 </script>
12814 <!-- Question 672 -->
12815 <h3>Question 672:</h3>
12816 <p>Write a JavaScript function to count the number of vowels in a given string.</p>
12817
12818 <!-- Answer 672 -->
12819 <script>
12820 function countVowels(inputString) {
12821 const vowels = 'aeiouAEIOU';
12822 let count = 0;
12823
12824 for (let char of inputString) {
12825 if ([Link](char)) {
12826 count++;
12827 }
12828 }
12829
12830 return count;
12831 }
12832
12833 // Example usage
12834 const testStringWithVowels = 'United States';
12835 [Link](`Number of vowels in "${testStringWithVowels}":
${countVowels(testStringWithVowels)}`);
12836 </script>
12837
12838 <!-- Question 673 -->
12839 <h3>Question 673:</h3>
12840 <p>Write a JavaScript function to check whether a given value is a valid URL or not.</p>
12841
12842 <!-- Answer 673 -->
12843 <script>
12844 function isValidURL(value) {
12845 try {
12846 new URL(value);
12847 return true;
12848 } catch (error) {
12849 return false;
12850 }
12851 }
12852
12853 // Example usage
12854 const testURL = '[Link]
12855 [Link](`Is "${testURL}" a valid URL? ${isValidURL(testURL)}`);
12856 </script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 216/298
1/31/24, 9:21 AM [Link]
12857
12858 <!-- Question 674 -->
12859 <h3>Question 674:</h3>
12860 <p>Write a JavaScript function to check whether a given value is alphanumeric or not.<
/p>
12861
12862 <!-- Answer 674 -->
12863 <script>
12864 function isAlphanumeric(value) {
12865 const alphanumericPattern = /^[a-zA-Z0-9]+$/;
12866 return [Link](value);
12867 }
12868
12869 // Example usage
12870 const testAlphanumeric = 'abc123';
12871 [Link](`Is "${testAlphanumeric}" alphanumeric?
${isAlphanumeric(testAlphanumeric)}`);
12872 </script>
12873
12874 <!-- Question 675 -->
12875 <h3>Question 675:</h3>
12876 <p>Write a JavaScript function to check whether a given value is a time string or not.<
/p>
12877
12878 <!-- Answer 675 -->
12879 <script>
12880 function isTimeString(value) {
12881 const timePattern = /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
12882 return [Link](value);
12883 }
12884
12885 // Example usage
12886 const testTimeString = '15:45';
12887 [Link](`Is "${testTimeString}" a valid time string?
${isTimeString(testTimeString)}`);
12888 </script>
12889
12890 <!-- Question 676 -->
12891 <h3>Question 676:</h3>
12892 <p>Write a JavaScript function to check whether a given value is a US ZIP code or not.<
/p>
12893
12894 <!-- Answer 676 -->
12895 <script>
12896 function isUSZipCode(value) {
12897 const usZipCodePattern = /^\d{5}(?:-\d{4})?$/;
12898 return [Link](value);
12899 }
12900
12901 // Example usage
12902 const testUSZipCode = '12345';
12903 [Link](`Is "${testUSZipCode}" a valid US ZIP code? ${isUSZipCode(testUSZipCode)
}`);
12904 </script>
12905
12906 <!-- Question 677 -->
12907 <h3>Question 677:</h3>
12908 <p>Write a JavaScript function to check whether a given value is a UK Post Code or not.<
/p>
12909
12910 <!-- Answer 677 -->
12911 <script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 217/298
1/31/24, 9:21 AM [Link]
12912 function isUKPostCode(value) {
12913 const ukPostCodePattern = /^[A-Z]{1,2}\d[A-Z\d]? \d[A-Z]{2}$/;
12914 return [Link](value);
12915 }
12916
12917 // Example usage
12918 const testUKPostCode = 'SW1A 1AA';
12919 [Link](`Is "${testUKPostCode}" a valid UK Post Code?
${isUKPostCode(testUKPostCode)}`);
12920 </script>
12921
12922 <!-- Question 678 -->
12923 <h3>Question 678:</h3>
12924 <p>Write a JavaScript function to check whether a given value is a Canada Post Code or
not.</p>
12925
12926 <!-- Answer 678 -->
12927 <script>
12928 function isCanadaPostCode(value) {
12929 const canadaPostCodePattern = /^[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d$/;
12930 return [Link](value);
12931 }
12932
12933 // Example usage
12934 const testCanadaPostCode = 'K1A 0B1';
12935 [Link](`Is "${testCanadaPostCode}" a valid Canada Post Code?
${isCanadaPostCode(testCanadaPostCode)}`);
12936 </script>
12937
12938 <!-- Question 679 -->
12939 <h3>Question 679:</h3>
12940 <p>Write a JavaScript function to check whether a given value is a social security
number or not.</p>
12941
12942 <!-- Answer 679 -->
12943 <script>
12944 function isSocialSecurityNumber(value) {
12945 const ssnPattern = /^\d{3}-\d{2}-\d{4}$/;
12946 return [Link](value);
12947 }
12948
12949 // Example usage
12950 const testSSN = '123-45-6789';
12951 [Link](`Is "${testSSN}" a valid Social Security Number?
${isSocialSecurityNumber(testSSN)}`);
12952 </script>
12953
12954 <!-- Question 680 -->
12955 <h3>Question 680:</h3>
12956 <p>Write a JavaScript function to check whether a given value is a hexadecimal value or
not.</p>
12957
12958 <!-- Answer 680 -->
12959 <script>
12960 function isHexadecimal(value) {
12961 const hexPattern = /^[0-9A-Fa-f]+$/;
12962 return [Link](value);
12963 }
12964
12965 // Example usage
12966 const testHexValue = '1A2F';
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 218/298
1/31/24, 9:21 AM [Link]
12967 [Link](`Is "${testHexValue}" a valid hexadecimal value?
${isHexadecimal(testHexValue)}`);
12968 </script>
12969
12970 <!-- Question 681 -->
12971 <h3>Question 681:</h3>
12972 <p>Write a JavaScript function to check whether a given value is a hex color value or
not.</p>
12973
12974 <!-- Answer 681 -->
12975 <script>
12976 function isHexColor(value) {
12977 const hexColorPattern = /^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;
12978 return [Link](value);
12979 }
12980
12981 // Example usage
12982 const testHexColor = '#1a2F4c';
12983 [Link](`Is "${testHexColor}" a valid hex color value?
${isHexColor(testHexColor)}`);
12984 </script>
12985
12986 <!-- Question 682 -->
12987 <h3>Question 682:</h3>
12988 <p>Write a JavaScript function to check whether a given value represents a domain or
not.</p>
12989
12990 <!-- Answer 682 -->
12991 <script>
12992 function isDomain(value) {
12993 const domainPattern = /^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
12994 return [Link](value);
12995 }
12996
12997 // Example usage
12998 const testDomain = '[Link]';
12999 [Link](`Is "${testDomain}" a valid domain? ${isDomain(testDomain)}`);
13000 </script>
13001
13002 <!-- Question 683 -->
13003 <h3>Question 683:</h3>
13004 <p>Write a JavaScript function to check whether a given value is HTML or not.</p>
13005
13006 <!-- Answer 683 -->
13007 <script>
13008 function isHTML(value) {
13009 const htmlPattern = /<\/?[a-z][\s\S]*>/i;
13010 return [Link](value);
13011 }
13012
13013 // Example usage
13014 const testHTML = '<p>This is a paragraph.</p>';
13015 [Link](`Does the string contain HTML? ${isHTML(testHTML)}`);
13016 </script>
13017
13018 <!-- Question 684 -->
13019 <h3>Question 684:</h3>
13020 <p>Write a JavaScript function to check if a given value contains alpha, dash, and
underscore.</p>
13021
13022 <!-- Answer 684 -->
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 219/298
1/31/24, 9:21 AM [Link]
13023 <script>
13024 function containsAlphaDashUnderscore(value) {
13025 const pattern = /^[a-zA-Z-_]+$/;
13026 return [Link](value);
13027 }
13028
13029 // Example usage
13030 const testString = 'alpha-Dash_123';
13031 [Link](`Does "${testString}" contain alpha, dash, and underscore?
${containsAlphaDashUnderscore(testString)}`);
13032 </script>
13033
13034 <!-- Question 685 -->
13035 <h3>Question 685:</h3>
13036 <p>Write a JavaScript function to print an integer with commas as thousands separators.<
/p>
13037
13038 <!-- Answer 685 -->
13039 <script>
13040 function thousandsSeparators(number) {
13041 return [Link]().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
13042 }
13043
13044 // Example usage
13045 const testNumber = 1234567;
13046 [Link](`Formatted number: ${thousandsSeparators(testNumber)}`);
13047 </script>
13048
13049 <!-- Question 686 -->
13050 <h3>Question 686:</h3>
13051 <p>Here is a sample HTML file with a submit button. Now modify the style of the
paragraph text through JavaScript code.</p>
13052
13053 <!-- Answer 686 -->
13054 <script>
13055 function js_style() {
13056 const paragraph = [Link]('text');
13057 [Link] = 'Arial, sans-serif';
13058 [Link] = '20px';
13059 [Link] = 'blue';
13060 }
13061 </script>
13062
13063 <!-- Additional HTML for Question 686 -->
13064 <p id='text'>JavaScript Exercises - InfoMatrix</p>
13065 <div>
13066 <button id="jsstyle" onclick="js_style()">Style</button>
13067 </div>
13068 <!-- Question 687 -->
13069 <h3>Question 687:</h3>
13070 <p>Write a JavaScript function to get the values of the First and Last name from the
following form.</p>
13071
13072 <!-- Answer 687 -->
13073 <script>
13074 function getFormvalue() {
13075 const firstName = [Link]('form1').elements['fname'].value;
13076 const lastName = [Link]('form1').elements['lname'].value;
13077 alert(`First Name: ${firstName}\nLast Name: ${lastName}`);
13078 }
13079 </script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 220/298
1/31/24, 9:21 AM [Link]
13080
13081 <!-- Additional HTML for Question 687 -->
13082 <form id="form1" onsubmit="getFormvalue()">
13083 First name: <input type="text" name="fname" value="David"><br>
13084 Last name: <input type="text" name="lname" value="Beckham"><br>
13085 <input type="submit" value="Submit">
13086 </form>
13087
13088 <!-- Question 688 -->
13089 <h3>Question 688:</h3>
13090 <p>Write a JavaScript program to set the background color of a paragraph.</p>
13091
13092 <!-- Answer 688 -->
13093 <script>
13094 [Link]("DOMContentLoaded", function () {
13095 const paragraph = [Link]('p');
13096 [Link] = 'This is a paragraph.';
13097 [Link] = 'lightblue';
13098 [Link](paragraph);
13099 });
13100 </script>
13101
13102 <!-- Question 689 -->
13103 <h3>Question 689:</h3>
13104 <p>Here is a sample html file with a submit button. Write a JavaScript function to get
the value of the href, hreflang, rel, target, and type attributes of the specified link.
</p>
13105
13106 <!-- Answer 689 -->
13107 <script>
13108 function getAttributes() {
13109 const link = [Link]('w3r');
13110 const href = [Link]('href');
13111 const hreflang = [Link]('hreflang');
13112 const rel = [Link]('rel');
13113 const target = [Link]('target');
13114 const type = [Link]('type');
13115
13116 alert(`Href: ${href}\nHreflang: ${hreflang}\nRel: ${rel}\nTarget: ${target}
\nType: ${type}`);
13117 }
13118 </script>
13119
13120 <!-- Additional HTML for Question 689 -->
13121 <p><a id="w3r" type="text/html" hreflang="en-us" rel="nofollow" target="_self" href="
[Link]
13122 <button onclick="getAttributes()">Click here to get attributes value</button>
13123
13124 <!-- Question 690 -->
13125 <h3>Question 690:</h3>
13126 <p>Write a JavaScript function to add rows to a table.</p>
13127
13128 <!-- Answer 690 -->
13129 <script>
13130 function insert_Row() {
13131 const table = [Link]('sampleTable');
13132 const newRow = [Link](-1);
13133 const cell1 = [Link](0);
13134 const cell2 = [Link](1);
13135 [Link] = 'New Row Cell 1';
13136 [Link] = 'New Row Cell 2';
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 221/298
1/31/24, 9:21 AM [Link]
13137 }
13138 </script>
13139
13140 <!-- Additional HTML for Question 690 -->
13141 <table id="sampleTable" border="1">
13142 <tr>
13143 <td>Row1 cell1</td>
13144 <td>Row1 cell2</td>
13145 </tr>
13146 <tr>
13147 <td>Row2 cell1</td>
13148 <td>Row2 cell2</td>
13149 </tr>
13150 </table>
13151 <br>
13152 <input type="button" onclick="insert_Row()" value="Insert row">
13153
13154 <!-- Question 691 -->
13155 <h3>Question 691:</h3>
13156 <p>Write a JavaScript function that accepts row, column, (to identify a particular cell)
and a string to update the content of that cell.</p>
13157
13158 <!-- Answer 691 -->
13159 <script>
13160 function changeContent() {
13161 const table = [Link]('myTable');
13162 const row = prompt('Enter the row number:');
13163 const col = prompt('Enter the column number:');
13164 const content = prompt('Enter the new content:');
13165
13166 if (row >= 0 && col >= 0) {
13167 [Link][row].cells[col].textContent = content;
13168 } else {
13169 alert('Invalid row or column number.');
13170 }
13171 }
13172 </script>
13173
13174 <!-- Additional HTML for Question 691 -->
13175 <table id="myTable" border="1">
13176 <tr>
13177 <td>Row1 cell1</td>
13178 <td>Row1 cell2</td>
13179 </tr>
13180 <tr>
13181 <td>Row2 cell1</td>
13182 <td>Row2 cell2</td>
13183 </tr>
13184 <tr>
13185 <td>Row3 cell1</td>
13186 <td>Row3 cell2</td>
13187 </tr>
13188 </table>
13189 <form>
13190 <input type="button" onclick="changeContent()" value="Change content">
13191 </form>
13192
13193 <!-- Question 692 -->
13194 <h3>Question 692:</h3>
13195 <p>Write a JavaScript program that creates a table, accepts row and column numbers from
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 222/298
1/31/24, 9:21 AM [Link]
the user, and inputs row-column number as content (e.g. Row-0 Column-0) of a cell.</p>
13196
13197 <!-- Answer 692 -->
13198 <script>
13199 function createTable() {
13200 const rows = prompt('Enter the number of rows:');
13201 const cols = prompt('Enter the number of columns:');
13202 const table = [Link]('myTable');
13203
13204 for (let i = 0; i < rows; i++) {
13205 const row = [Link](i);
13206 for (let j = 0; j < cols; j++) {
13207 const cell = [Link](j);
13208 [Link] = `Row-${i} Column-${j}`;
13209 }
13210 }
13211 }
13212 </script>
13213
13214 <!-- Additional HTML for Question 692 -->
13215 <style type="text/css">
13216 body {margin: 30px;}
13217 </style>
13218 <form>
13219 <input type="button" onclick="createTable()" value="Create the table">
13220 </form>
13221 <table id="myTable" border="1"></table>
13222
13223 <!-- Question 693 -->
13224 <h3>Question 693:</h3>
13225 <p>Write a JavaScript program to remove items from a dropdown list.</p>
13226
13227 <!-- Answer 693 -->
13228 <script>
13229 function removecolor() {
13230 const select = [Link]('colorSelect');
13231 const selectedIndex = [Link];
13232 if (selectedIndex !== -1) {
13233 [Link](selectedIndex);
13234 } else {
13235 alert('Please select an item to remove.');
13236 }
13237 }
13238 </script>
13239
13240 <!-- Additional HTML for Question 693 -->
13241 <form>
13242 <select id="colorSelect">
13243 <option>Red</option>
13244 <option>Green</option>
13245 <option>White</option>
13246 <option>Black</option>
13247 </select>
13248 <input type="button" onclick="removecolor()" value="Select and Remove">
13249 </form>
13250
13251 <!-- Question 694 -->
13252 <h3>Question 694:</h3>
13253 <p>Write a JavaScript program to count and display the items of a dropdown list in an
alert window.</p>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 223/298
1/31/24, 9:21 AM [Link]
13254
13255 <!-- Answer 694 -->
13256 <script>
13257 function getOptions() {
13258 const select = [Link]('mySelect');
13259 const optionsCount = [Link];
13260 let optionsList = '';
13261
13262 for (let i = 0; i < optionsCount; i++) {
13263 optionsList += `${i + 1}. ${[Link][i].text}\n`;
13264 }
13265
13266 alert(`Total items: ${optionsCount}\n\nItems:\n${optionsList}`);
13267 }
13268 </script>
13269
13270 <!-- Additional HTML for Question 694 -->
13271 <form>
13272 Select your favorite Color :
13273 <select id="mySelect">
13274 <option>Red</option>
13275 <option>Green</option>
13276 <option>Blue</option>
13277 <option>White</option>
13278 </select>
13279 <input type="button" onclick="getOptions()" value="Count and Output all items">
13280 </form>
13281 <style>
13282 #output {
13283 margin-top: 20px;
13284 padding: 10px;
13285 border: 1px solid #ccc;
13286 }
13287 #rectangularShape {
13288 width: 100px;
13289 height: 50px;
13290 background-color: lightblue;
13291 margin-top: 20px;
13292 }
13293 #circle {
13294 width: 100px;
13295 height: 100px;
13296 background-color: lightcoral;
13297 border-radius: 50%;
13298 margin-top: 20px;
13299 }
13300 </style>
13301 </head>
13302 <body>
13303
13304 <!-- Question 695 -->
13305 <h3>Question 695:</h3>
13306 <p>Write a JavaScript program to calculate the volume of a sphere.</p>
13307
13308 <!-- Answer 695 -->
13309 <script>
13310 function calculateSphereVolume(radius) {
13311 const volume = (4 / 3) * [Link] * [Link](radius, 3);
13312 return [Link](2);
13313 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 224/298
1/31/24, 9:21 AM [Link]
13314
13315 const radius = 5;
13316 const sphereVolume = calculateSphereVolume(radius);
13317
13318 [Link]('output').innerHTML = `Volume of the sphere with radius
${radius} units: ${sphereVolume} cubic units`;
13319 </script>
13320
13321 <!-- Output Container for Question 695 -->
13322 <div id="output"></div>
13323
13324 <!-- Question 696 -->
13325 <h3>Question 696:</h3>
13326 <p>Write a JavaScript program to display a random image (clicking on a button) from the
following list.</p>
13327
13328 <!-- Answer 696 -->
13329 <script>
13330 const images = [
13331 { src: "[Link] width:
240, height: 160 },
13332 { src: "[Link] width: 320,
height: 195 },
13333 { src: "[Link] width:
500, height: 343 }
13334 ];
13335
13336 function displayRandomImage() {
13337 const randomIndex = [Link]([Link]() * [Link]);
13338 const randomImage = images[randomIndex];
13339 const output = [Link]('output');
13340
13341 [Link] = `<img src="${[Link]}" alt="Random Image" width="
${[Link]}" height="${[Link]}">`;
13342 }
13343 </script>
13344
13345 <!-- Output Container for Question 696 -->
13346 <div>
13347 <button onclick="displayRandomImage()">Display Random Image</button>
13348 <div id="output"></div>
13349 </div>
13350
13351 <!-- Question 697 -->
13352 <h3>Question 697:</h3>
13353 <p>Write a JavaScript program to highlight the bold words of the following paragraph on
mouse over a certain link.</p>
13354
13355 <!-- Answer 697 -->
13356 <script>
13357 function highlightBoldWords() {
13358 const paragraph = [Link]('paragraphToHighlight');
13359 const boldWords = [Link]('strong');
13360
13361 for (let i = 0; i < [Link]; i++) {
13362 boldWords[i].[Link] = 'yellow';
13363 }
13364 }
13365 </script>
13366
13367 <!-- Additional HTML for Question 697 -->
13368 <p id="paragraphToHighlight">
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 225/298
1/31/24, 9:21 AM [Link]
13369 We have just started this section for the users (beginner to intermediate) who want
to work with various JavaScript
13370 problems and write scripts online to test their JavaScript skill.
13371 </p>
13372 <a href="#" onmouseover="highlightBoldWords()">On mouse over here bold words of the
following paragraph will be highlighted</a>
13373
13374 <!-- Question 698 -->
13375 <h3>Question 698:</h3>
13376 <p>Write a JavaScript program to get the width and height of the window (any time the
window is resized).</p>
13377
13378 <!-- Answer 698 -->
13379 <script>
13380 function getWindowDimensions() {
13381 const width = [Link] || [Link] ||
[Link];
13382 const height = [Link] || [Link] ||
[Link];
13383
13384 [Link]('output').innerHTML = `Window Width: ${width}px, Window
Height: ${height}px`;
13385 }
13386
13387 [Link]('resize', getWindowDimensions);
13388 getWindowDimensions(); // Initial call to display dimensions
13389 </script>
13390
13391 <!-- Output Container for Question 698 -->
13392 <div id="output"></div>
13393
13394 <!-- Question 699 -->
13395 <h3>Question 699:</h3>
13396 <p>Write a JavaScript program to draw the following rectangular shape.</p>
13397
13398 <!-- Answer 699 -->
13399 <div id="rectangularShape"></div>
13400
13401 <!-- Question 700 -->
13402 <h3>Question 700:</h3>
13403 <p>Write a JavaScript program to draw a circle.</p>
13404
13405 <!-- Answer 700 -->
13406 <div id="circle"></div>
13407
13408 <!-- JavaScript for Drawing Shapes -->
13409 <script>
13410 Drawing the rectangular shape
13411 const rectangularShape = [Link]('rectangularShape');
13412 [Link] = '100px';
13413 [Link] = '50px';
13414 [Link] = 'lightblue';
13415
13416 Drawing the circle
13417 const circle = [Link]('circle');
13418 [Link] = '100px';
13419 [Link] = '100px';
13420 [Link] = 'lightcoral';
13421 [Link] = '50%';
13422 </script>
13423 <style>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 226/298
1/31/24, 9:21 AM [Link]
13424 #output {
13425 margin-top: 20px;
13426 padding: 10px;
13427 border: 1px solid #ccc;
13428 }
13429 #intersectingRectangles {
13430 position: relative;
13431 width: 200px;
13432 height: 200px;
13433 background-color: lightblue;
13434 }
13435 #rightAngledTriangle {
13436 width: 0;
13437 height: 0;
13438 border-left: 50px solid transparent;
13439 border-bottom: 50px solid lightcoral;
13440 margin-top: 20px;
13441 }
13442 #movetoDiagram {
13443 position: relative;
13444 width: 200px;
13445 height: 100px;
13446 margin-top: 20px;
13447 }
13448 #diagonalCircles {
13449 position: relative;
13450 width: 200px;
13451 height: 200px;
13452 margin-top: 20px;
13453 }
13454 .circle {
13455 position: absolute;
13456 width: 20px;
13457 height: 20px;
13458 border-radius: 50%;
13459 }
13460 </style>
13461 </head>
13462 <body>
13463
13464 <!-- Question 701 -->
13465 <h3>Question 701:</h3>
13466 <p>Write a JavaScript program to draw two intersecting rectangles, one of which has
alpha transparency.</p>
13467
13468 <!-- Answer 701 -->
13469 <div id="intersectingRectangles">
13470 <div style="position: absolute; top: 50px; left: 50px; width: 100px; height: 100px;
background-color: lightcoral;"></div>
13471 <div style="position: absolute; top: 25px; left: 75px; width: 100px; height: 150px;
background-color: lightblue; opacity: 0.7;"></div>
13472 </div>
13473
13474 <!-- Question 702 -->
13475 <h3>Question 702:</h3>
13476 <p>Write a JavaScript program to draw the following right-angled triangle.</p>
13477
13478 <!-- Answer 702 -->
13479 <div id="rightAngledTriangle"></div>
13480
13481 <!-- Question 703 -->
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 227/298
1/31/24, 9:21 AM [Link]
13482 <h3>Question 703:</h3>
13483 <p>Write a JavaScript program to draw the following diagram [use moveto() function].</p>
13484
13485 <!-- Answer 703 -->
13486 <canvas id="movetoDiagram" width="200" height="100"></canvas>
13487
13488 <!-- Question 704 -->
13489 <h3>Question 704:</h3>
13490 <p>Write a JavaScript program to draw the following diagram [diagonal, white to black
circles].</p>
13491
13492 <!-- Answer 704 -->
13493 <div id="diagonalCircles"></div>
13494
13495 <!-- Question 705 -->
13496 <h3>Question 705:</h3>
13497 <p>Write a JavaScript program to list the properties of a JavaScript object.</p>
13498
13499 <!-- Answer 705 -->
13500 <script>
13501 var student = {
13502 name: "David Rayy",
13503 sclass: "VI",
13504 rollno: 12
13505 };
13506
13507 const properties = [Link](student).join(',');
13508 [Link]('output').innerHTML = properties;
13509 </script>
13510
13511 <!-- Output Container for Question 705 -->
13512 <div id="output"></div>
13513
13514 <!-- Question 706 -->
13515 <h3>Question 706:</h3>
13516 <p>Write a JavaScript program to delete the rollno property from the following object.
Also, print the object before or after deleting the property.</p>
13517
13518 <!-- Answer 706 -->
13519 <script>
13520 var student2 = {
13521 name: "David Rayy",
13522 sclass: "VI",
13523 rollno: 12
13524 };
13525
13526 [Link]('output').innerHTML = `Before deletion:
${[Link](student2)}`;
13527 delete [Link];
13528 [Link]('output').innerHTML += `<br>After deletion:
${[Link](student2)}`;
13529 </script>
13530
13531 <!-- Output Container for Question 706 -->
13532 <div id="output"></div>
13533
13534 <!-- JavaScript for Drawing Shapes -->
13535
13536 <!-- Answer 702 -->
13537 <script>
13538 const rightAngledTriangle = [Link]('rightAngledTriangle');
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 228/298
1/31/24, 9:21 AM [Link]
13539 [Link] = '0';
13540 [Link] = '0';
13541 [Link] = '50px solid transparent';
13542 [Link] = '50px solid lightcoral';
13543 </script>
13544
13545 <!-- Answer 703 -->
13546 <script>
13547 const movetoDiagram = [Link]('movetoDiagram');
13548 const ctx = [Link]('2d');
13549 [Link]();
13550 [Link](20, 20);
13551 [Link](20, 80);
13552 [Link](150, 80);
13553 [Link](20, 20);
13554 [Link]();
13555 </script>
13556
13557 <!-- Answer 704 -->
13558 <script>
13559 const diagonalCircles = [Link]('diagonalCircles');
13560 const circleCount = 5;
13561
13562 for (let i = 0; i < circleCount; i++) {
13563 const circle = [Link]('div');
13564 const percentage = (i / (circleCount - 1)) * 100;
13565 const color = `rgb(${percentage}%, ${percentage}%, ${percentage}%)`;
13566
13567 [Link] = 'circle';
13568 [Link] = `${percentage}%`;
13569 [Link] = `${percentage}%`;
13570 [Link] = color;
13571 [Link](circle);
13572 }
13573 </script>
13574 <style>
13575 #output {
13576 margin-top: 20px;
13577 padding: 10px;
13578 border: 1px solid #ccc;
13579 }
13580 </style>
13581 </head>
13582 <body>
13583
13584 <!-- Question 707 -->
13585 <h3>Question 707:</h3>
13586 <p>Write a JavaScript program to get the length of a JavaScript object.</p>
13587
13588 <!-- Answer 707 -->
13589 <script>
13590 var student = {
13591 name: "David Rayy",
13592 sclass: "VI",
13593 rollno: 12
13594 };
13595
13596 const objectLength = [Link](student).length;
13597 [Link]('output').innerHTML = `Length of the object: ${objectLength}
`;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 229/298
1/31/24, 9:21 AM [Link]
13598 </script>
13599
13600 <!-- Output Container for Question 707 -->
13601 <div id="output"></div>
13602
13603 <!-- Question 708 -->
13604 <h3>Question 708:</h3>
13605 <p>Write a JavaScript program to display the reading status of the books.</p>
13606
13607 <!-- Answer 708 -->
13608 <script>
13609 var library = [
13610 {
13611 author: 'Bill Gates',
13612 title: 'The Road Ahead',
13613 readingStatus: true
13614 },
13615 {
13616 author: 'Steve Jobs',
13617 title: 'Walter Isaacson',
13618 readingStatus: true
13619 },
13620 {
13621 author: 'Suzanne Collins',
13622 title: 'Mockingjay: The Final Book of The Hunger Games',
13623 readingStatus: false
13624 }
13625 ];
13626
13627 [Link](book => {
13628 const { title, author, readingStatus } = book;
13629 const status = readingStatus ? 'already read' : 'not read yet';
13630 [Link]('output').innerHTML += `${title} by ${author} -
${status}<br>`;
13631 });
13632 </script>
13633
13634 <!-- Output Container for Question 708 -->
13635 <div id="output"></div>
13636
13637 <!-- Question 709 -->
13638 <h3>Question 709:</h3>
13639 <p>Write a JavaScript program to get the volume of a Cylinder with four decimal places
using object classes.</p>
13640
13641 <!-- Answer 709 -->
13642 <script>
13643 class Cylinder {
13644 constructor(radius, height) {
13645 [Link] = radius;
13646 [Link] = height;
13647 }
13648
13649 getVolume() {
13650 const volume = [Link] * [Link]([Link], 2) * [Link];
13651 return [Link](4);
13652 }
13653 }
13654
13655 const cylinder = new Cylinder(3, 5);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 230/298
1/31/24, 9:21 AM [Link]
13656 [Link]('output').innerHTML = `Volume of the cylinder:
${[Link]()}`;
13657 </script>
13658
13659 <!-- Output Container for Question 709 -->
13660 <div id="output"></div>
13661
13662 <!-- Question 710 -->
13663 <h3>Question 710:</h3>
13664 <p>Write a Bubble Sort algorithm in JavaScript.</p>
13665
13666 <!-- Answer 710 -->
13667 <script>
13668 const bubbleSort = arr => {
13669 let swapped;
13670 do {
13671 swapped = false;
13672 for (let i = 0; i < [Link] - 1; i++) {
13673 if (arr[i] > arr[i + 1]) {
13674 [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
13675 swapped = true;
13676 }
13677 }
13678 } while (swapped);
13679
13680 return arr;
13681 };
13682
13683 const sampleData = [6, 4, 0, 3, -2, 1];
13684 const sortedData = bubbleSort(sampleData);
13685 [Link]('output').innerHTML = `Sorted Data: [${[Link](', ')
}]`;
13686 </script>
13687
13688 <!-- Output Container for Question 710 -->
13689 <div id="output"></div>
13690
13691 <!-- Question 711 -->
13692 <h3>Question 711:</h3>
13693 <p>Write a JavaScript program which returns a subset of a string.</p>
13694
13695 <!-- Answer 711 -->
13696 <script>
13697 const getSubsets = str => {
13698 const subsets = [];
13699 for (let i = 0; i < [Link]; i++) {
13700 for (let j = i + 1; j <= [Link]; j++) {
13701 [Link]([Link](i, j));
13702 }
13703 }
13704 return subsets;
13705 };
13706
13707 const subsets = getSubsets('dog');
13708 [Link]('output').innerHTML = `Subsets: [${[Link](subset => `"
${subset}"`).join(', ')}]`;
13709 </script>
13710
13711 <!-- Output Container for Question 711 -->
13712 <div id="output"></div>
13713
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 231/298
1/31/24, 9:21 AM [Link]
13714 <!-- Question 712 -->
13715 <h3>Question 712:</h3>
13716 <p>Write a JavaScript program to create a Clock.</p>
13717
13718 <!-- Answer 712 -->
13719 <script>
13720 const updateClock = () => {
13721 const now = new Date();
13722 const hours = [Link]().toString().padStart(2, '0');
13723 const minutes = [Link]().toString().padStart(2, '0');
13724 const seconds = [Link]().toString().padStart(2, '0');
13725
13726 [Link]('output').innerHTML = `${hours}:${minutes}:${seconds}`;
13727 };
13728
13729 setInterval(updateClock, 1000);
13730 </script>
13731
13732 <!-- Output Container for Question 712 -->
13733 <div id="output"></div>
13734 <style>
13735 #output {
13736 margin-top: 20px;
13737 padding: 10px;
13738 border: 1px solid #ccc;
13739 }
13740 </style>
13741 </head>
13742 <body>
13743
13744 <!-- Question 713 -->
13745 <h3>Question 713:</h3>
13746 <p>Write a JavaScript program to calculate the area and perimeter of a circle.</p>
13747
13748 <!-- Answer 713 -->
13749 <script>
13750 class Circle {
13751 constructor(radius) {
13752 [Link] = radius;
13753 }
13754
13755 calculateArea() {
13756 return [Link] * [Link]([Link], 2);
13757 }
13758
13759 calculatePerimeter() {
13760 return 2 * [Link] * [Link];
13761 }
13762 }
13763
13764 const userRadius = parseFloat(prompt('Enter the radius of the circle:'));
13765 const circle = new Circle(userRadius);
13766
13767 [Link]('output').innerHTML = `
13768 Area of the circle: ${[Link]().toFixed(2)} <br>
13769 Perimeter of the circle: ${[Link]().toFixed(2)}
13770 `;
13771 </script>
13772
13773 <!-- Output Container for Question 713 -->
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 232/298
1/31/24, 9:21 AM [Link]
13774 <div id="output"></div>
13775
13776 <!-- Question 714 -->
13777 <h3>Question 714:</h3>
13778 <p>Write a JavaScript program to sort an array of JavaScript objects.</p>
13779
13780 <!-- Answer 714 -->
13781 <script>
13782 var library = [
13783 {
13784 title: 'The Road Ahead',
13785 author: 'Bill Gates',
13786 libraryID: 1254
13787 },
13788 {
13789 title: 'Walter Isaacson',
13790 author: 'Steve Jobs',
13791 libraryID: 4264
13792 },
13793 {
13794 title: 'Mockingjay: The Final Book of The Hunger Games',
13795 author: 'Suzanne Collins',
13796 libraryID: 3245
13797 }
13798 ];
13799
13800 const sortedLibrary = [Link]((a, b) => [Link] - [Link]);
13801
13802 [Link]('output').innerHTML = `Sorted Library:
${[Link](sortedLibrary)}`;
13803 </script>
13804
13805 <!-- Output Container for Question 714 -->
13806 <div id="output"></div>
13807
13808 <!-- Question 715 -->
13809 <h3>Question 715:</h3>
13810 <p>Write a JavaScript function to print all the methods in a JavaScript object.</p>
13811
13812 <!-- Answer 715 -->
13813 <script>
13814 const all_properties = obj => {
13815 return [Link](obj);
13816 };
13817
13818 const arrayMethods = all_properties(Array);
13819 [Link]('output').innerHTML = `Methods in Array Object:
[${[Link](method => `"${method}"`).join(', ')}]`;
13820 </script>
13821
13822 <!-- Output Container for Question 715 -->
13823 <div id="output"></div>
13824 <style>
13825 #output {
13826 margin-top: 20px;
13827 padding: 10px;
13828 border: 1px solid #ccc;
13829 }
13830 </style>
13831 </head>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 233/298
1/31/24, 9:21 AM [Link]
13832 <body>
13833
13834 <!-- Question 716 -->
13835 <h3>Question 716:</h3>
13836 <p>Write a JavaScript function to parse a URL.</p>
13837
13838 <!-- Answer 716 -->
13839 <script>
13840 function parseURL(url) {
13841 const parser = new URL(url);
13842 const result = {
13843 protocol: [Link],
13844 host: [Link],
13845 hostname: [Link],
13846 port: [Link],
13847 pathname: [Link],
13848 search: [Link],
13849 hash: [Link]
13850 };
13851
13852 return result;
13853 }
13854
13855 const exampleURL = "[Link]
value#section";
13856 const parsedURL = parseURL(exampleURL);
13857
13858 [Link]('output').innerHTML = `Parsed URL:
${[Link](parsedURL, null, 2)}`;
13859 </script>
13860
13861 <!-- Output Container for Question 716 -->
13862 <div id="output"></div>
13863
13864 <!-- Question 717 -->
13865 <h3>Question 717:</h3>
13866 <p>Write a JavaScript function to retrieve all the names of an object's own and
inherited properties.</p>
13867
13868 <!-- Answer 717 -->
13869 <script>
13870 function getAllPropertyNames(obj) {
13871 const propertyNames = [];
13872 for (let key in obj) {
13873 [Link](key);
13874 }
13875 return propertyNames;
13876 }
13877
13878 const exampleObject = {
13879 prop1: 'value1',
13880 prop2: 'value2'
13881 };
13882
13883 const inheritedProperties = getAllPropertyNames([Link]);
13884
13885 [Link]('output').innerHTML = `Own Properties:
${getAllPropertyNames(exampleObject)} <br>
13886 Inherited Properties: ${inheritedProperties}`;
13887 </script>
13888
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 234/298
1/31/24, 9:21 AM [Link]
13889 <!-- Output Container for Question 717 -->
13890 <div id="output"></div>
13891
13892 <!-- Question 718 -->
13893 <h3>Question 718:</h3>
13894 <p>Write a JavaScript function to retrieve all the values of an object's properties.</p>
13895
13896 <!-- Answer 718 -->
13897 <script>
13898 function getAllPropertyValues(obj) {
13899 const propertyValues = [];
13900 for (let key in obj) {
13901 [Link](obj[key]);
13902 }
13903 return propertyValues;
13904 }
13905
13906 const exampleObject2 = {
13907 prop1: 'value1',
13908 prop2: 'value2'
13909 };
13910
13911 [Link]('output').innerHTML = `Property Values:
${getAllPropertyValues(exampleObject2)}`;
13912 </script>
13913
13914 <!-- Output Container for Question 718 -->
13915 <div id="output"></div>
13916
13917 <!-- Question 719 -->
13918 <h3>Question 719:</h3>
13919 <p>Write a JavaScript function to convert an object into a list of `[key, value]` pairs.
</p>
13920
13921 <!-- Answer 719 -->
13922 <script>
13923 function objectToList(obj) {
13924 return [Link](obj);
13925 }
13926
13927 const exampleObject3 = {
13928 prop1: 'value1',
13929 prop2: 'value2'
13930 };
13931
13932 [Link]('output').innerHTML = `Object as List:
${[Link](objectToList(exampleObject3), null, 2)}`;
13933 </script>
13934
13935 <!-- Output Container for Question 719 -->
13936 <div id="output"></div>
13937
13938 <!-- Question 720 -->
13939 <h3>Question 720:</h3>
13940 <p>Write a JavaScript function to get a copy of the object where the keys have become
the values and the values the keys.</p>
13941
13942 <!-- Answer 720 -->
13943 <script>
13944 function swapKeysAndValues(obj) {
13945 const swappedObject = {};
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 235/298
1/31/24, 9:21 AM [Link]
13946 for (let key in obj) {
13947 swappedObject[obj[key]] = key;
13948 }
13949 return swappedObject;
13950 }
13951
13952 const exampleObject4 = {
13953 prop1: 'value1',
13954 prop2: 'value2'
13955 };
13956
13957 [Link]('output').innerHTML = `Swapped Object:
${[Link](swapKeysAndValues(exampleObject4), null, 2)}`;
13958 </script>
13959
13960 <!-- Output Container for Question 720 -->
13961 <div id="output"></div>
13962
13963 <!-- Question 721 -->
13964 <h3>Question 721:</h3>
13965 <p>Write a JavaScript function to check whether an object contains a given property.</p>
13966
13967 <!-- Answer 721 -->
13968 <script>
13969 function hasProperty(obj, property) {
13970 return [Link](property);
13971 }
13972
13973 const exampleObject5 = {
13974 prop1: 'value1',
13975 prop2: 'value2'
13976 };
13977
13978 const checkProperty = 'prop1';
13979
13980 [Link]('output').innerHTML = `Object has property '${checkProperty}
': ${hasProperty(exampleObject5, checkProperty)}`;
13981 </script>
13982
13983 <!-- Output Container for Question 721 -->
13984 <div id="output"></div>
13985
13986 <!-- Question 722 -->
13987 <h3>Question 722:</h3>
13988 <p>Write a JavaScript function to check whether a given value is a DOM element.</p>
13989
13990 <!-- Answer 722 -->
13991 <script>
13992 function isDOMElement(value) {
13993 return value instanceof Element;
13994 }
13995
13996 const exampleElement = [Link]('output');
13997
13998 [Link]('output').innerHTML = `Is it a DOM Element?
${isDOMElement(exampleElement)}`;
13999 </script>
14000
14001 <!-- Output Container for Question 722 -->
14002 <div id="output"></div>
14003 <style>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 236/298
1/31/24, 9:21 AM [Link]
14004 #output {
14005 margin-top: 20px;
14006 padding: 10px;
14007 border: 1px solid #ccc;
14008 }
14009 </style>
14010 </head>
14011 <body>
14012
14013 <!-- Question 723 -->
14014 <h3>Question 723:</h3>
14015 <p>Write a JavaScript function to validate whether a given value type is boolean or not.
</p>
14016
14017 <!-- Answer 723 -->
14018 <script>
14019 function isBoolean(value) {
14020 return typeof value === 'boolean';
14021 }
14022
14023 const exampleBoolean = true;
14024
14025 [Link]('output723').innerHTML = `Is it a boolean?
${isBoolean(exampleBoolean)}`;
14026 </script>
14027
14028 <!-- Output Container for Question 723 -->
14029 <div id="output723"></div>
14030
14031 <!-- Question 724 -->
14032 <h3>Question 724:</h3>
14033 <p>Write a JavaScript function to validate whether a given value type is error or not.<
/p>
14034
14035 <!-- Answer 724 -->
14036 <script>
14037 function isError(value) {
14038 return value instanceof Error;
14039 }
14040
14041 const exampleError = new Error('This is an error');
14042
14043 [Link]('output724').innerHTML = `Is it an error?
${isError(exampleError)}`;
14044 </script>
14045
14046 <!-- Output Container for Question 724 -->
14047 <div id="output724"></div>
14048
14049 <!-- Question 725 -->
14050 <h3>Question 725:</h3>
14051 <p>Write a JavaScript function to validate whether a given value type is NaN or not.</p>
14052
14053 <!-- Answer 725 -->
14054 <script>
14055 function isNaNValue(value) {
14056 return typeof value === 'number' && isNaN(value);
14057 }
14058
14059 const exampleNaN = NaN;
14060
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 237/298
1/31/24, 9:21 AM [Link]
14061 [Link]('output725').innerHTML = `Is it NaN?
${isNaNValue(exampleNaN)}`;
14062 </script>
14063
14064 <!-- Output Container for Question 725 -->
14065 <div id="output725"></div>
14066
14067 <!-- Question 726 -->
14068 <h3>Question 726:</h3>
14069 <p>Write a JavaScript function to validate whether a given value type is null or not.<
/p>
14070
14071 <!-- Answer 726 -->
14072 <script>
14073 function isNull(value) {
14074 return value === null;
14075 }
14076
14077 const exampleNull = null;
14078
14079 [Link]('output726').innerHTML = `Is it null? ${isNull(exampleNull)}
`;
14080 </script>
14081
14082 <!-- Output Container for Question 726 -->
14083 <div id="output726"></div>
14084
14085 <!-- Question 727 -->
14086 <h3>Question 727:</h3>
14087 <p>Write a JavaScript function to validate whether a given value is number or not.</p>
14088
14089 <!-- Answer 727 -->
14090 <script>
14091 function isNumber(value) {
14092 return typeof value === 'number' && !isNaN(value);
14093 }
14094
14095 const exampleNumber = 42;
14096
14097 [Link]('output727').innerHTML = `Is it a number?
${isNumber(exampleNumber)}`;
14098 </script>
14099
14100 <!-- Output Container for Question 727 -->
14101 <div id="output727"></div>
14102
14103 <!-- Question 728 -->
14104 <h3>Question 728:</h3>
14105 <p>Write a JavaScript function to validate whether a given value is object or not.</p>
14106
14107 <!-- Answer 728 -->
14108 <script>
14109 function isObject(value) {
14110 return value !== null && typeof value === 'object';
14111 }
14112
14113 const exampleObject = { key: 'value' };
14114
14115 [Link]('output728').innerHTML = `Is it an object?
${isObject(exampleObject)}`;
14116 </script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 238/298
1/31/24, 9:21 AM [Link]
14117
14118 <!-- Output Container for Question 728 -->
14119 <div id="output728"></div>
14120
14121 <!-- Question 729 -->
14122 <h3>Question 729:</h3>
14123 <p>Write a JavaScript function to validate whether a given value type is a pure JSON
object or not.</p>
14124
14125 <!-- Answer 729 -->
14126 <script>
14127 function isPureJSONObject(value) {
14128 return value !== null && typeof value === 'object' && [Link] ===
Object;
14129 }
14130
14131 const exampleJSONObject = { key: 'value' };
14132
14133 [Link]('output729').innerHTML = `Is it a pure JSON object?
${isPureJSONObject(exampleJSONObject)}`;
14134 </script>
14135
14136 <!-- Output Container for Question 729 -->
14137 <div id="output729"></div>
14138
14139 <!-- Question 730 -->
14140 <h3>Question 730:</h3>
14141 <p>Write a JavaScript function to validate whether a given value is RegExp or not.</p>
14142
14143 <!-- Answer 730 -->
14144 <script>
14145 function isRegExp(value) {
14146 return value instanceof RegExp;
14147 }
14148
14149 const exampleRegExp = /[a-z]/;
14150
14151 [Link]('output730').innerHTML = `Is it a RegExp?
${isRegExp(exampleRegExp)}`;
14152 </script>
14153
14154 <!-- Output Container for Question 730 -->
14155 <div id="output730"></div>
14156
14157 <!-- Question 731 -->
14158 <h3>Question 731:</h3>
14159 <p>Write a JavaScript function to validate whether a given value type is char or not.<
/p>
14160
14161 <!-- Answer 731 -->
14162 <script>
14163 function isChar(value) {
14164 return typeof value === 'string' && [Link] === 1;
14165 }
14166
14167 const exampleChar = 'a';
14168
14169 [Link]('output731').innerHTML = `Is it a char?
${isChar(exampleChar)}`;
14170 </script>
14171
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 239/298
1/31/24, 9:21 AM [Link]
14172 <!-- Output Container for Question 731 -->
14173 <div id="output731"></div>
14174
14175 <!-- Question 732 -->
14176 <h3>Question 732:</h3>
14177 <p>Write a JavaScript function to check whether given value types are the same or not.<
/p>
14178
14179 <!-- Answer 732 -->
14180 <script>
14181 function areValueTypesSame(...values) {
14182 const firstType = typeof values[0];
14183 return [Link](value => typeof value === firstType);
14184 }
14185
14186 const exampleValues = [42, 'Hello', true];
14187
14188 [Link]('output732').innerHTML = `Are value types the same?
${areValueTypesSame(...exampleValues)}`;
14189 </script>
14190
14191 <!-- Output Container for Question 732 -->
14192 <div id="output732"></div>
14193 <style>
14194 #output {
14195 margin-top: 20px;
14196 padding: 10px;
14197 border: 1px solid #ccc;
14198 }
14199 </style>
14200 </head>
14201 <body>
14202
14203 <!-- Question 733 -->
14204 <h3>Question 733:</h3>
14205 <p>Write a JavaScript program to sort a list of elements using Quick sort.</p>
14206
14207 <!-- Answer 733 -->
14208 <script>
14209 function quickSort(arr) {
14210 if ([Link] <= 1) {
14211 return arr;
14212 }
14213
14214 const pivot = arr[0];
14215 const left = [];
14216 const right = [];
14217
14218 for (let i = 1; i < [Link]; i++) {
14219 arr[i] < pivot ? [Link](arr[i]) : [Link](arr[i]);
14220 }
14221
14222 return quickSort(left).concat(pivot, quickSort(right));
14223 }
14224
14225 const exampleArrayQuickSort = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
14226
14227 [Link]('output733').innerHTML = `Quick Sort Result:
${quickSort(exampleArrayQuickSort)}`;
14228 </script>
14229
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 240/298
1/31/24, 9:21 AM [Link]
14230 <!-- Output Container for Question 733 -->
14231 <div id="output733"></div>
14232
14233 <!-- Question 734 -->
14234 <h3>Question 734:</h3>
14235 <p>Write a JavaScript program to sort a list of elements using Merge sort.</p>
14236
14237 <!-- Answer 734 -->
14238 <script>
14239 function mergeSort(arr) {
14240 if ([Link] <= 1) {
14241 return arr;
14242 }
14243
14244 const middle = [Link]([Link] / 2);
14245 const left = [Link](0, middle);
14246 const right = [Link](middle);
14247
14248 return merge(mergeSort(left), mergeSort(right));
14249 }
14250
14251 function merge(left, right) {
14252 let result = [];
14253 let leftIndex = 0;
14254 let rightIndex = 0;
14255
14256 while (leftIndex < [Link] && rightIndex < [Link]) {
14257 if (left[leftIndex] < right[rightIndex]) {
14258 [Link](left[leftIndex]);
14259 leftIndex++;
14260 } else {
14261 [Link](right[rightIndex]);
14262 rightIndex++;
14263 }
14264 }
14265
14266 return [Link]([Link](leftIndex), [Link](rightIndex));
14267 }
14268
14269 const exampleArrayMergeSort = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
14270
14271 [Link]('output734').innerHTML = `Merge Sort Result:
${mergeSort(exampleArrayMergeSort)}`;
14272 </script>
14273
14274 <!-- Output Container for Question 734 -->
14275 <div id="output734"></div>
14276
14277 <!-- Question 735 -->
14278 <h3>Question 735:</h3>
14279 <p>Write a JavaScript program to sort a list of elements using Heap sort.</p>
14280
14281 <!-- Answer 735 -->
14282 <script>
14283 function heapSort(arr) {
14284 let len = [Link];
14285
14286 for (let i = [Link](len / 2); i >= 0; i--) {
14287 heapify(arr, i, len);
14288 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 241/298
1/31/24, 9:21 AM [Link]
14289
14290 for (let i = len - 1; i > 0; i--) {
14291 [arr[0], arr[i]] = [arr[i], arr[0]];
14292 heapify(arr, 0, i);
14293 }
14294
14295 return arr;
14296 }
14297
14298 function heapify(arr, index, heapSize) {
14299 let largest = index;
14300 const left = 2 * index + 1;
14301 const right = 2 * index + 2;
14302
14303 if (left < heapSize && arr[left] > arr[largest]) {
14304 largest = left;
14305 }
14306
14307 if (right < heapSize && arr[right] > arr[largest]) {
14308 largest = right;
14309 }
14310
14311 if (largest !== index) {
14312 [arr[index], arr[largest]] = [arr[largest], arr[index]];
14313 heapify(arr, largest, heapSize);
14314 }
14315 }
14316
14317 const exampleArrayHeapSort = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
14318
14319 [Link]('output735').innerHTML = `Heap Sort Result:
${heapSort(exampleArrayHeapSort)}`;
14320 </script>
14321
14322 <!-- Output Container for Question 735 -->
14323 <div id="output735"></div>
14324
14325 <!-- Question 736 -->
14326 <h3>Question 736:</h3>
14327 <p>Write a JavaScript program to sort a list of elements using Insertion sort.</p>
14328
14329 <!-- Answer 736 -->
14330 <script>
14331 function insertionSort(arr) {
14332 for (let i = 1; i < [Link]; i++) {
14333 let currentVal = arr[i];
14334 let j = i - 1;
14335
14336 while (j >= 0 && arr[j] > currentVal) {
14337 arr[j + 1] = arr[j];
14338 j--;
14339 }
14340
14341 arr[j + 1] = currentVal;
14342 }
14343
14344 return arr;
14345 }
14346
14347 const exampleArrayInsertionSort = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 242/298
1/31/24, 9:21 AM [Link]
14348
14349 [Link]('output736').innerHTML = `Insertion Sort Result:
${insertionSort(exampleArrayInsertionSort)}`;
14350 </script>
14351
14352 <!-- Output Container for Question 736 -->
14353 <div id="output736"></div>
14354
14355 <!-- Question 737 -->
14356 <h3>Question 737:</h3>
14357 <p>Write a JavaScript program to sort a list of elements using the Selection sort
algorithm.</p>
14358
14359 <!-- Answer 737 -->
14360 <script>
14361 function selectionSort(arr) {
14362 const len = [Link];
14363
14364 for (let i = 0; i < len - 1; i++) {
14365 let minIndex = i;
14366
14367 for (let j = i + 1; j < len; j++) {
14368 if (arr[j] < arr[minIndex]) {
14369 minIndex = j;
14370 }
14371 }
14372
14373 [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
14374 }
14375
14376 return arr;
14377 }
14378
14379 const exampleArraySelectionSort = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
14380
14381 [Link]('output737').innerHTML = `Selection Sort Result:
${selectionSort(exampleArraySelectionSort)}`;
14382 </script>
14383
14384 <!-- Output Container for Question 737 -->
14385 <div id="output737"></div>
14386
14387 <!-- Question 738 -->
14388 <h3>Question 738:</h3>
14389 <p>Write a JavaScript program to sort a list of elements using Shell sort.</p>
14390
14391 <!-- Answer 738 -->
14392 <script>
14393 function shellSort(arr) {
14394 const len = [Link];
14395 let gap = [Link](len / 2);
14396
14397 while (gap > 0) {
14398 for (let i = gap; i < len; i++) {
14399 let temp = arr[i];
14400 let j = i;
14401
14402 while (j >= gap && arr[j - gap] > temp) {
14403 arr[j] = arr[j - gap];
14404 j -= gap;
14405 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 243/298
1/31/24, 9:21 AM [Link]
14406
14407 arr[j] = temp;
14408 }
14409
14410 gap = [Link](gap / 2);
14411 }
14412
14413 return arr;
14414 }
14415
14416 const exampleArrayShellSort = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
14417
14418 [Link]('output738').innerHTML = `Shell Sort Result:
${shellSort(exampleArrayShellSort)}`;
14419 </script>
14420
14421 <!-- Output Container for Question 738 -->
14422 <div id="output738"></div>
14423
14424 <!-- Question 739 -->
14425 <h3>Question 739:</h3>
14426 <p>Write a JavaScript program to sort a list of elements using Bubble sort.</p>
14427
14428 <!-- Answer 739 -->
14429 <script>
14430 function bubbleSort(arr) {
14431 const len = [Link];
14432
14433 for (let i = 0; i < len - 1; i++) {
14434 for (let j = 0; j < len - 1 - i; j++) {
14435 if (arr[j] > arr[j + 1]) {
14436 [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
14437 }
14438 }
14439 }
14440
14441 return arr;
14442 }
14443
14444 const exampleArrayBubbleSort = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
14445
14446 [Link]('output739').innerHTML = `Bubble Sort Result:
${bubbleSort(exampleArrayBubbleSort)}`;
14447 </script>
14448
14449 <!-- Output Container for Question 739 -->
14450 <div id="output739"></div>
14451
14452 <!-- Question 740 -->
14453 <h3>Question 740:</h3>
14454 <p>Write a JavaScript program to sort a list of elements using Cocktail shaker sort.</p>
14455
14456 <!-- Answer 740 -->
14457 <script>
14458 function cocktailShakerSort(arr) {
14459 let swapped;
14460 do {
14461 swapped = false;
14462 for (let i = 0; i < [Link] - 1; i++) {
14463 if (arr[i] > arr[i + 1]) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 244/298
1/31/24, 9:21 AM [Link]
14464 [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
14465 swapped = true;
14466 }
14467 }
14468 if (!swapped) break;
14469 swapped = false;
14470 for (let i = [Link] - 2; i >= 0; i--) {
14471 if (arr[i] > arr[i + 1]) {
14472 [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
14473 swapped = true;
14474 }
14475 }
14476 } while (swapped);
14477
14478 return arr;
14479 }
14480
14481 const exampleArrayCocktailShakerSort = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
14482
14483 [Link]('output740').innerHTML = `Cocktail Shaker Sort Result:
${cocktailShakerSort(exampleArrayCocktailShakerSort)}`;
14484 </script>
14485
14486 <!-- Output Container for Question 740 -->
14487 <div id="output740"></div>
14488
14489 <!-- Question 741 -->
14490 <h3>Question 741:</h3>
14491 <p>Write a JavaScript program to sort a list of elements using Comb sort.</p>
14492
14493 <!-- Answer 741 -->
14494 <script>
14495 function combSort(arr) {
14496 const shrinkFactor = 1.3;
14497 let gap = [Link];
14498 let swapped = true;
14499
14500 while (gap > 1 || swapped) {
14501 if (gap > 1) {
14502 gap = [Link](gap / shrinkFactor);
14503 }
14504
14505 swapped = false;
14506 let i = 0;
14507
14508 while (i + gap < [Link]) {
14509 if (arr[i] > arr[i + gap]) {
14510 [arr[i], arr[i + gap]] = [arr[i + gap], arr[i]];
14511 swapped = true;
14512 }
14513
14514 i++;
14515 }
14516 }
14517
14518 return arr;
14519 }
14520
14521 const exampleArrayCombSort = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
14522
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 245/298
1/31/24, 9:21 AM [Link]
14523 [Link]('output741').innerHTML = `Comb Sort Result:
${combSort(exampleArrayCombSort)}`;
14524 </script>
14525
14526 <!-- Output Container for Question 741 -->
14527 <div id="output741"></div>
14528 <style>
14529 #output743, #output744, #output745, #output747, #output748, #output750,
#output751 {
14530 margin-top: 20px;
14531 padding: 10px;
14532 border: 1px solid #ccc;
14533 }
14534 </style>
14535 </head>
14536 <body>
14537
14538 <!-- Question 742 -->
14539 <h3>Question 742:</h3>
14540 <p>Write a JavaScript program to sort a list of elements using Gnome sort.</p>
14541
14542 <!-- Answer 742 -->
14543 <script>
14544 function gnomeSort(arr) {
14545 let index = 0;
14546
14547 while (index < [Link]) {
14548 if (index === 0 || arr[index] >= arr[index - 1]) {
14549 index++;
14550 } else {
14551 [arr[index], arr[index - 1]] = [arr[index - 1], arr[index]];
14552 index--;
14553 }
14554 }
14555
14556 return arr;
14557 }
14558
14559 const exampleArrayGnomeSort = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
14560
14561 [Link]('output742').innerHTML = `Gnome Sort Result:
${gnomeSort(exampleArrayGnomeSort)}`;
14562 </script>
14563
14564 <!-- Output Container for Question 742 -->
14565 <div id="output742"></div>
14566
14567 <!-- Question 743 -->
14568 <h3>Question 743:</h3>
14569 <p>Write a JavaScript program to sort a list of elements using Counting sort.</p>
14570
14571 <!-- Answer 743 -->
14572 <script>
14573 function countingSort(arr) {
14574 const max = [Link](...arr);
14575 const min = [Link](...arr);
14576 const countArray = Array(max - min + 1).fill(0);
14577
14578 for (let i = 0; i < [Link]; i++) {
14579 countArray[arr[i] - min]++;
14580 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 246/298
1/31/24, 9:21 AM [Link]
14581
14582 let sortedIndex = 0;
14583 for (let i = min; i <= max; i++) {
14584 while (countArray[i - min] > 0) {
14585 arr[sortedIndex++] = i;
14586 countArray[i - min]--;
14587 }
14588 }
14589
14590 return arr;
14591 }
14592
14593 const exampleArrayCountingSort = [4, 2, 3, 1, 0, 5, 4, 7];
14594
14595 [Link]('output743').innerHTML = `Counting Sort Result:
${countingSort(exampleArrayCountingSort)}`;
14596 </script>
14597
14598 <!-- Output Container for Question 743 -->
14599 <div id="output743"></div>
14600
14601 <!-- Question 744 -->
14602 <h3>Question 744:</h3>
14603 <p>Write a JavaScript program to sort a list of elements using Flash sort.</p>
14604
14605 <!-- Answer 744 -->
14606 <script>
14607 function flashSort(arr) {
14608 const length = [Link];
14609 if (length === 0) {
14610 return arr;
14611 }
14612
14613 const max = [Link](...arr);
14614 const min = [Link](...arr);
14615 const range = max - min + 1;
14616
14617 if (range === 0) {
14618 return arr;
14619 }
14620
14621 const buckets = new Array(range);
14622 const sortedArray = new Array(length);
14623
14624 for (let i = 0; i < length; i++) {
14625 const index = [Link](((arr[i] - min) / range) * (length - 1));
14626 if (!buckets[index]) {
14627 buckets[index] = [];
14628 }
14629 buckets[index].push(arr[i]);
14630 }
14631
14632 let k = 0;
14633 for (let i = 0; i < range; i++) {
14634 if (buckets[i]) {
14635 const sortedBucket = flashSort(buckets[i]);
14636 for (let j = 0; j < [Link]; j++) {
14637 sortedArray[k++] = sortedBucket[j];
14638 }
14639 }
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 247/298
1/31/24, 9:21 AM [Link]
14640 }
14641
14642 return sortedArray;
14643 }
14644
14645 const exampleArrayFlashSort = [4, 2, 3, 1, 0, 5, 4, 7];
14646
14647 [Link]('output744').innerHTML = `Flash Sort Result:
${flashSort(exampleArrayFlashSort)}`;
14648 </script>
14649
14650 <!-- Output Container for Question 744 -->
14651 <div id="output744"></div>
14652
14653 <!-- Question 745 -->
14654 <h3>Question 745:</h3>
14655 <p>Write a JavaScript program to sort a list of elements using Pancake sort.</p>
14656
14657 <!-- Answer 745 -->
14658 <script>
14659 function pancakeSort(arr) {
14660 const flip = (arr, i) => {
14661 let start = 0;
14662 while (start < i) {
14663 [arr[start], arr[i]] = [arr[i], arr[start]];
14664 start++;
14665 i--;
14666 }
14667 };
14668
14669 const findMaxIndex = (arr, n) => {
14670 let maxIndex = 0;
14671 for (let i = 0; i < n; i++) {
14672 if (arr[i] > arr[maxIndex]) {
14673 maxIndex = i;
14674 }
14675 }
14676 return maxIndex;
14677 };
14678
14679 const pancakeSortHelper = (arr, n) => {
14680 for (let currSize = n; currSize > 1; currSize--) {
14681 const maxIndex = findMaxIndex(arr, currSize);
14682 if (maxIndex !== currSize - 1) {
14683 flip(arr, maxIndex);
14684 flip(arr, currSize - 1);
14685 }
14686 }
14687 };
14688
14689 pancakeSortHelper(arr, [Link]);
14690 return arr;
14691 }
14692
14693 const exampleArrayPancakeSort = [4, 2, 3, 1, 0, 5, 4, 7];
14694
14695 [Link]('output745').innerHTML = `Pancake Sort Result:
${pancakeSort(exampleArrayPancakeSort)}`;
14696 </script>
14697
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 248/298
1/31/24, 9:21 AM [Link]
14698 <!-- Output Container for Question 745 -->
14699 <div id="output745"></div>
14700
14701 <!-- Question 746 -->
14702 <h3>Question 746:</h3>
14703 <p>Write a JavaScript program to sort a list of elements using Bogosort.</p>
14704
14705 <!-- Answer 746 -->
14706 <script>
14707 function isSorted(arr) {
14708 for (let i = 1; i < [Link]; i++) {
14709 if (arr[i] < arr[i - 1]) {
14710 return false;
14711 }
14712 }
14713 return true;
14714 }
14715
14716 function bogosort(arr) {
14717 while (!isSorted(arr)) {
14718 for (let i = [Link] - 1; i > 0; i--) {
14719 const j = [Link]([Link]() * (i + 1));
14720 [arr[i], arr[j]] = [arr[j], arr[i]];
14721 }
14722 }
14723 return arr;
14724 }
14725
14726 const exampleArrayBogosort = [4, 2, 3, 1, 0, 5, 4, 7];
14727
14728 [Link]('output746').innerHTML = `Bogosort Result:
${bogosort(exampleArrayBogosort)}`;
14729 </script>
14730
14731 <!-- Output Container for Question 746 -->
14732 <div id="output746"></div>
14733
14734 <!-- Question 747 -->
14735 <h3>Question 747:</h3>
14736 <p>Write a JavaScript program to sort an array of numbers, using the bucket sort
algorithm.</p>
14737
14738 <!-- Answer 747 -->
14739 <script>
14740 function bucketSort(arr) {
14741 const max = [Link](...arr);
14742 const min = [Link](...arr);
14743 const bucketSize = 5;
14744
14745 const bucketCount = [Link]((max - min) / bucketSize) + 1;
14746 const buckets = new Array(bucketCount).fill().map(() => []);
14747
14748 for (let i = 0; i < [Link]; i++) {
14749 const bucketIndex = [Link]((arr[i] - min) / bucketSize);
14750 buckets[bucketIndex].push(arr[i]);
14751 }
14752
14753 [Link] = 0;
14754 for (let i = 0; i < [Link]; i++) {
14755 buckets[i].sort((a, b) => a - b);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 249/298
1/31/24, 9:21 AM [Link]
14756 [Link](...buckets[i]);
14757 }
14758
14759 return arr;
14760 }
14761
14762 const exampleArrayBucketSort = [4, 2, 3, 1, 0, 5, 4, 7];
14763
14764 [Link]('output747').innerHTML = `Bucket Sort Result:
${bucketSort(exampleArrayBucketSort)}`;
14765 </script>
14766
14767 <!-- Output Container for Question 747 -->
14768 <div id="output747"></div>
14769
14770 <!-- Question 748 -->
14771 <h3>Question 748:</h3>
14772 <p>Write a JavaScript program to sort an array of objects, ordered by properties and
orders.</p>
14773
14774 <!-- Answer 748 -->
14775 <script>
14776 function orderByPropertiesAndOrders(arr, props, orders) {
14777 return [Link]((a, b) => {
14778 for (let i = 0; i < [Link]; i++) {
14779 const prop = props[i];
14780 const order = orders[i] === 'asc' ? 1 : -1;
14781
14782 if (a[prop] < b[prop]) return -1 * order;
14783 if (a[prop] > b[prop]) return 1 * order;
14784 }
14785 return 0;
14786 });
14787 }
14788
14789 const exampleArrayObjectsSort = [
14790 { name: 'John', age: 30 },
14791 { name: 'Alice', age: 25 },
14792 { name: 'Bob', age: 35 }
14793 ];
14794
14795 const sortedObjects = orderByPropertiesAndOrders(exampleArrayObjectsSort, ['age', '
name'], ['asc', 'desc']);
14796
14797 [Link]('output748').innerHTML = `Objects Sort Result:
${[Link](sortedObjects)}`;
14798 </script>
14799
14800 <!-- Output Container for Question 748 -->
14801 <div id="output748"></div>
14802
14803 <!-- Question 750 -->
14804 <h3>Question 750:</h3>
14805 <p>Write a JavaScript program to sort an array of objects, ordered by a property, based
on the array of orders provided.</p>
14806
14807 <!-- Answer 750 -->
14808 <script>
14809 function orderByPropertyAndOrders(arr, prop, orders) {
14810 return [Link]((a, b) => {
14811 const order = [Link](a[prop]) - [Link](b[prop]);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 250/298
1/31/24, 9:21 AM [Link]
14812 return order;
14813 });
14814 }
14815
14816 const exampleArrayObjectsSort2 = [
14817 { name: 'John', age: 30 },
14818 { name: 'Alice', age: 25 },
14819 { name: 'Bob', age: 35 }
14820 ];
14821
14822 const sortedObjects2 = orderByPropertyAndOrders(exampleArrayObjectsSort2, 'name', ['
Bob', 'Alice', 'John']);
14823
14824 [Link]('output750').innerHTML = `Objects Sort Result:
${[Link](sortedObjects2)}`;
14825 </script>
14826
14827 <!-- Output Container for Question 750 -->
14828 <div id="output750"></div>
14829
14830 <!-- Question 751 -->
14831 <h3>Question 751:</h3>
14832 <p>Write a JavaScript program to sort the characters in a string alphabetically.</p>
14833
14834 <!-- Answer 751 -->
14835 <script>
14836 function sortStringAlphabetically(str) {
14837 return [Link]('').sort().join('');
14838 }
14839
14840 const exampleStringSort = 'hello';
14841
14842 [Link]('output751').innerHTML = `String Sort Result:
${sortStringAlphabetically(exampleStringSort)}`;
14843 </script>
14844
14845 <!-- Output Container for Question 751 -->
14846 <div id="output751"></div>
14847 <style>
14848 #output752, #output753, #output754, #output755, #output756 {
14849 margin-top: 20px;
14850 padding: 10px;
14851 border: 1px solid #ccc;
14852 }
14853 </style>
14854 </head>
14855 <body>
14856
14857 <!-- Question 752 -->
14858 <h3>Question 752:</h3>
14859 <p>Write a JavaScript program to find the lowest index at which a value should be
inserted into an array in order to maintain its sorting order, based on the provided
iterator function.</p>
14860
14861 <!-- Answer 752 -->
14862 <script>
14863 function findLowestIndexWithIterator(arr, value, iterator) {
14864 let low = 0;
14865 let high = [Link];
14866
14867 while (low < high) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 251/298
1/31/24, 9:21 AM [Link]
14868 const mid = [Link]((low + high) / 2);
14869 if (iterator(arr[mid]) < iterator(value)) {
14870 low = mid + 1;
14871 } else {
14872 high = mid;
14873 }
14874 }
14875
14876 return low;
14877 }
14878
14879 const exampleArray752 = [1, 3, 5, 7, 9];
14880 const valueToInsert752 = 6;
14881 const iteratorFunction752 = (x) => x * 2;
14882
14883 const indexToInsert752 = findLowestIndexWithIterator(exampleArray752,
valueToInsert752, iteratorFunction752);
14884
14885 [Link]('output752').innerHTML = `Lowest Index to Insert:
${indexToInsert752}`;
14886 </script>
14887
14888 <!-- Output Container for Question 752 -->
14889 <div id="output752"></div>
14890
14891 <!-- Question 753 -->
14892 <h3>Question 753:</h3>
14893 <p>Write a JavaScript program to find the index of a given element in a sorted array
using the binary search algorithm.</p>
14894
14895 <!-- Answer 753 -->
14896 <script>
14897 function binarySearch(arr, target) {
14898 let low = 0;
14899 let high = [Link] - 1;
14900
14901 while (low <= high) {
14902 const mid = [Link]((low + high) / 2);
14903
14904 if (arr[mid] === target) {
14905 return mid;
14906 } else if (arr[mid] < target) {
14907 low = mid + 1;
14908 } else {
14909 high = mid - 1;
14910 }
14911 }
14912
14913 return -1;
14914 }
14915
14916 const exampleArray753 = [1, 3, 5, 7, 9];
14917 const targetElement753 = 5;
14918
14919 const indexOfElement753 = binarySearch(exampleArray753, targetElement753);
14920
14921 [Link]('output753').innerHTML = `Index of Element:
${indexOfElement753}`;
14922 </script>
14923
14924 <!-- Output Container for Question 753 -->
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 252/298
1/31/24, 9:21 AM [Link]
14925 <div id="output753"></div>
14926
14927 <!-- Question 754 -->
14928 <h3>Question 754:</h3>
14929 <p>Write a JavaScript program to find the lowest index at which a value should be
inserted into an array in order to maintain its sorting order.</p>
14930
14931 <!-- Answer 754 -->
14932 <script>
14933 function findLowestIndex(arr, value) {
14934 let low = 0;
14935 let high = [Link];
14936
14937 while (low < high) {
14938 const mid = [Link]((low + high) / 2);
14939 if (arr[mid] < value) {
14940 low = mid + 1;
14941 } else {
14942 high = mid;
14943 }
14944 }
14945
14946 return low;
14947 }
14948
14949 const exampleArray754 = [1, 3, 5, 7, 9];
14950 const valueToInsert754 = 6;
14951
14952 const indexToInsert754 = findLowestIndex(exampleArray754, valueToInsert754);
14953
14954 [Link]('output754').innerHTML = `Lowest Index to Insert:
${indexToInsert754}`;
14955 </script>
14956
14957 <!-- Output Container for Question 754 -->
14958 <div id="output754"></div>
14959
14960 <!-- Question 755 -->
14961 <h3>Question 755:</h3>
14962 <p>Write a JavaScript program to find the highest index at which a value should be
inserted into an array in order to maintain its sort order.</p>
14963
14964 <!-- Answer 755 -->
14965 <script>
14966 function findHighestIndex(arr, value) {
14967 let low = 0;
14968 let high = [Link];
14969
14970 while (low < high) {
14971 const mid = [Link]((low + high) / 2);
14972 if (arr[mid] <= value) {
14973 low = mid + 1;
14974 } else {
14975 high = mid;
14976 }
14977 }
14978
14979 return low - 1;
14980 }
14981
14982 const exampleArray755 = [1, 3, 5, 7, 9];
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 253/298
1/31/24, 9:21 AM [Link]
14983 const valueToInsert755 = 6;
14984
14985 const indexToInsert755 = findHighestIndex(exampleArray755, valueToInsert755);
14986
14987 [Link]('output755').innerHTML = `Highest Index to Insert:
${indexToInsert755}`;
14988 </script>
14989
14990 <!-- Output Container for Question 755 -->
14991 <div id="output755"></div>
14992
14993 <!-- Question 756 -->
14994 <h3>Question 756:</h3>
14995 <p>Write a JavaScript program to check if a numeric array is sorted or not.</p>
14996
14997 <!-- Answer 756 -->
14998 <script>
14999 function isSorted(arr) {
15000 for (let i = 1; i < [Link]; i++) {
15001 if (arr[i] < arr[i - 1]) {
15002 return false;
15003 }
15004 }
15005 return true;
15006 }
15007
15008 const exampleArray756 = [1, 3, 5, 7, 4];
15009
15010 const isArraySorted756 = isSorted(exampleArray756);
15011
15012 [Link]('output756').innerHTML = `Array is Sorted:
${isArraySorted756}`;
15013 </script>
15014
15015 <!-- Output Container for Question 756 -->
15016 <div id="output756"></div>
15017
15018 // --------------------------------- 501 - 600 -----------------------------------------
--------
15019
15020 <h4>
15021 501. Write a JavaScript function for the Pythagorean theorem. According to
15022 Wikipedia : In mathematics, the Pythagorean theorem, also known as
15023 Pythagoras' theorem, is a relation in Euclidean geometry among the three
15024 sides of a right triangle. It states that the square of the hypotenuse
15025 (the side opposite the right angle) is equal to the sum of the squares of
15026 the other two sides. The theorem can be written as an equation relating
15027 the lengths of the sides a, b and c, often called the "Pythagorean
15028 equation". Test Data : [Link](pythagorean(4, 3)); 5
15029 </h4>
15030 <script>
15031 // 501. JavaScript function for the Pythagorean theorem
15032 function pythagorean(a, b) {
15033 return [Link](a * a + b * b);
15034 }
15035
15036 // Test Data
15037 [Link](pythagorean(4, 3)); // Output: 5
15038 </script>
15039 <hr />
15040
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 254/298
1/31/24, 9:21 AM [Link]
15041 <script>
15042 // 502. JavaScript function to check if a number is a power of two
15043 function isPower_of_two(num) {
15044 return (num & (num - 1)) === 0 && num !== 0;
15045 }
15046
15047 // Test Data
15048 [Link](isPower_of_two(64)); // Output: true
15049 [Link](isPower_of_two(94)); // Output: false
15050 </script>
15051 <hr />
15052
15053 <h4>503. Write a JavaScript function to limit a value inside a certain range.
15054 Note : If the value is higher than max it will return max. and if the value is smaller
than min it will return the
15055 min.
15056 Test Data :
15057 [Link](value_limit(7, 1, 12));
15058 7
15059 [Link](value_limit(-7, 0, 12));
15060 0
15061 [Link](value_limit(15, 0, 12));
15062 12
15063 </h4>
15064 <script>
15065 // JavaScript function to limit a value inside a certain range
15066 function value_limit(value, min, max) {
15067 return [Link]([Link](value, min), max);
15068 }
15069
15070 // Test Data
15071 [Link](value_limit(7, 1, 12)); // Output: 7
15072 [Link](value_limit(-7, 0, 12)); // Output: 0
15073 [Link](value_limit(15, 0, 12)); // Output: 12
15074 </script>
15075 <hr>
15076
15077 <script>
15078 // 504. JavaScript function to check if a number is a whole number or has a decimal
place
15079 function number_test(num) {
15080 return [Link](num) ? "It is a whole number." : "Number has a decimal
place.";
15081 }
15082
15083 // Test Data
15084 [Link](number_test(25.66)); // Output: "Number has a decimal place."
15085 [Link](number_test(10)); // Output: "It is a whole number."
15086 </script>
15087
15088 <script>
15089 // 505. JavaScript function to print an integer with commas as thousands separators
15090 function thousands_separators(num) {
15091 return [Link]().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
15092 }
15093
15094 // Test Data
15095 [Link](thousands_separators(1000)); // Output: "1,000"
15096 [Link](thousands_separators(10000.23));// Output: "10,000.23"
15097 [Link](thousands_separators(100000)); // Output: "100,000"
15098 </script>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 255/298
1/31/24, 9:21 AM [Link]
15099
15100 <script>
15101 // 506. JavaScript function to create random background color
15102 function random_bg_color() {
15103 const randomColor = '#' + [Link]([Link]() * 16777215).toString(16);
15104 [Link] = randomColor;
15105 }
15106
15107 // Call the function to change the background color
15108 random_bg_color();
15109 </script>
15110
15111 <script>
15112 // 507. JavaScript function to count the digits of an integer
15113 function count_digits(num) {
15114 return [Link]().length;
15115 }
15116
15117 // Test Data
15118 [Link](count_digits(12345)); // Output: 5
15119 </script>
15120
15121 <script>
15122 // 508. JavaScript function to calculate the combination of n and r
15123 function combinations(n, r) {
15124 function factorial(num) {
15125 if (num === 0 || num === 1) return 1;
15126 return num * factorial(num - 1);
15127 }
15128 return factorial(n) / (factorial(r) * factorial(n - r));
15129 }
15130
15131 // Test Data
15132 [Link](combinations(6, 2)); // Output: 15
15133 [Link](combinations(5, 3)); // Output: 10
15134 </script>
15135
15136 <script>
15137 // 509. JavaScript function to get all prime numbers from 0 to a specified number
15138 function primeFactorsTo(num) {
15139 const primes = [];
15140 for (let i = 2; i <= num; i++) {
15141 let isPrime = true;
15142 for (let j = 2; j <= [Link](i); j++) {
15143 if (i % j === 0) {
15144 isPrime = false;
15145 break;
15146 }
15147 }
15148 if (isPrime) [Link](i);
15149 }
15150 return primes;
15151 }
15152
15153 // Test Data
15154 [Link](primeFactorsTo(5)); // Output: [2, 3, 5]
15155 [Link](primeFactorsTo(15)); // Output: [2, 3, 5, 7, 11, 13]
15156 </script>
15157
15158 <!-- Other tasks -->
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 256/298
1/31/24, 9:21 AM [Link]
15159
15160 <script>
15161 // 510. JavaScript function to show the first twenty Hamming numbers
15162 function hammingNumbers() {
15163 let hamming = [1];
15164 let i2 = 0, i3 = 0, i5 = 0;
15165 let next_mult_of_2 = 2, next_mult_of_3 = 3, next_mult_of_5 = 5;
15166
15167 for (let i = 1; i < 20; i++) {
15168 let next_ham = [Link](next_mult_of_2, next_mult_of_3, next_mult_of_5);
15169 [Link](next_ham);
15170
15171 if (next_ham === next_mult_of_2) {
15172 i2++;
15173 next_mult_of_2 = hamming[i2] * 2;
15174 }
15175 if (next_ham === next_mult_of_3) {
15176 i3++;
15177 next_mult_of_3 = hamming[i3] * 3;
15178 }
15179 if (next_ham === next_mult_of_5) {
15180 i5++;
15181 next_mult_of_5 = hamming[i5] * 5;
15182 }
15183 }
15184 return hamming;
15185 }
15186
15187 [Link](hammingNumbers()); // Output: First 20 Hamming numbers
15188 </script>
15189
15190 <script>
15191 // 511. JavaScript function to subtract elements from one another in an array
15192 function subtractElements(arr) {
15193 return [Link]((acc, curr) => acc - curr);
15194 }
15195
15196 // Test Data
15197 [Link](subtractElements([10, 5, 3])); // Output: 2
15198 </script>
15199
15200 <script>
15201 // 512. JavaScript function to calculate the divisor and modulus of two integers
15202 function calculateDivMod(a, b) {
15203 return { divisor: [Link](a / b), modulus: a % b };
15204 }
15205
15206 // Test Data
15207 [Link](calculateDivMod(10, 3)); // Output: { divisor: 3, modulus: 1 }
15208 </script>
15209
15210 <script>
15211 // 513. JavaScript function to calculate the extended Euclid Algorithm or extended GCD
15212 function extendedEuclid(a, b) {
15213 if (a === 0) {
15214 return { gcd: b, x: 0, y: 1 };
15215 } else {
15216 const result = extendedEuclid(b % a, a);
15217 return { gcd: [Link], x: result.y - [Link](b / a) * result.x, y:
result.x };
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 257/298
1/31/24, 9:21 AM [Link]
15218 }
15219 }
15220 // Test Data
15221 [Link](extendedEuclid(30, 18)); // Output: { gcd: 6, x: 1, y: -1 }
15222 </script>
15223
15224 // 515. Calculate Lanczos approximation gamma
15225 function gammaLanczos(x) {
15226 var p = [
15227 0.99999999999980993,
15228 676.5203681218851,
15229 -1259.1392167224028,
15230 771.32342877765313,
15231 -176.61502916214059,
15232 12.507343278686905,
15233 -0.13857109526572012,
15234 9.9843695780195716e-6,
15235 1.5056327351493116e-7
15236 ];
15237 var g = 7;
15238 if (x < 0.5) return [Link] / ([Link]([Link] * x) * gammaLanczos(1 - x));
15239 x -= 1;
15240 var a = p[0];
15241 var t = x + g + 0.5;
15242 for (var i = 1; i < [Link]; i++) {
15243 a += p[i] / (x + i);
15244 }
15245 return [Link](2 * [Link]) * [Link](t, x + 0.5) * [Link](-t) * a;
15246 }
15247
15248 // 516. Add two complex numbers
15249 function addComplex(c1, c2) {
15250 return {real: [Link] + [Link], imag: [Link] + [Link]};
15251 }
15252
15253 // 517. Subtract two complex numbers
15254 function subtractComplex(c1, c2) {
15255 return {real: [Link] - [Link], imag: [Link] - [Link]};
15256 }
15257
15258 // 518. Multiply two complex numbers
15259 function multiplyComplex(c1, c2) {
15260 return {
15261 real: [Link] * [Link] - [Link] * [Link],
15262 imag: [Link] * [Link] + [Link] * [Link]
15263 };
15264 }
15265
15266 // 519. Divide two complex numbers
15267 function divideComplex(c1, c2) {
15268 var denominator = [Link] * [Link] + [Link] * [Link];
15269 return {
15270 real: ([Link] * [Link] + [Link] * [Link]) / denominator,
15271 imag: ([Link] * [Link] - [Link] * [Link]) / denominator
15272 };
15273 }
15274
15275 // 520. Check if input is an array
15276 function isArray(input) {
15277 return [Link](input);
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 258/298
1/31/24, 9:21 AM [Link]
15278 }
15279
15280 // 521. Clone an array
15281 function arrayClone(arr) {
15282 return [Link](0);
15283 }
15284
15285 // 522. Get the first n elements of an array
15286 function first(arr, n = 1) {
15287 return [Link](0, n);
15288 }
15289
15290 // 523. Get the last n elements of an array
15291 function last(arr, n = 1) {
15292 return [Link]([Link]([Link] - n, 0));
15293 }
15294
15295 // Testing the functions
15296 [Link](gammaLanczos(5)); // Example of using Lanczos approximation
15297 [Link](addComplex({real: 1, imag: 2}, {real: 2, imag: 3})); // {real: 3, imag: 5}
15298 [Link](subtractComplex({real: 4, imag: 5}, {real: 1, imag: 2})); // {real: 3, imag:
3}
15299 [Link](multiplyComplex({real: 1, imag: 2}, {real: 2, imag: 3})); // {real: -4,
imag: 7}
15300 [Link](divideComplex({real: 5, imag: 3}, {real: 2, imag: 1})); // {real: 2.2, imag:
0.4}
15301 [Link](isArray('InfoMatrix')); // false
15302 [Link](isArray([1, 2, 4, 0])); // true
15303 [Link](arrayClone([1, 2, 4, 0])); // [1, 2, 4, 0]
15304 [Link](arrayClone([1, 2, [4, 0]])); // [1, 2, [4, 0]]
15305 [Link](first([7, 9, 0, -2])); // 7
15306 [Link](first([], 3)); // []
15307 [Link](first([7, 9, 0, -2], 3)); // [7, 9, 0]
15308 [Link](first([7, 9, 0, -2], 6)); // [7, 9, 0, -2]
15309 [Link](first([7, 9, 0, -2], -3)); // []
15310 [Link](last([7, 9, 0, -2])); // -2
15311 [Link](last([7, 9, 0, -2], 3)); // [9, 0, -2]
15312 [Link](last([7, 9, 0, -2], 6)); // [7, 9, 0, -2]
15313
15314
15315 <p><strong>524. Join all elements of the array into a string:</strong></p>
15316 <pre>
15317 var myColor = ["Red", "Green", "White", "Black"];
15318 var joinedWithComma = [Link](",");
15319 var joinedWithPlus = [Link]("+");
15320
15321 [Link](joinedWithComma); // "Red,Green,White,Black"
15322 [Link](joinedWithComma); // "Red,Green,White,Black"
15323 [Link](joinedWithPlus); // "Red+Green+White+Black"
15324 </pre>
15325
15326 <p><strong>525. Insert dashes between each two even numbers:</strong></p>
15327 <pre>
15328 function insertDashes(num) {
15329 var numStr = [Link]();
15330 var result = numStr[0];
15331 for (var i = 1; i < [Link]; i++) {
15332 if (numStr[i - 1] % 2 === 0 && numStr[i] % 2 === 0) {
15333 result += '-' + numStr[i];
15334 } else {
15335 result += numStr[i];
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 259/298
1/31/24, 9:21 AM [Link]
15336 }
15337 }
15338 return result;
15339 }
15340
15341 [Link](insertDashes(025468)); // "0-254-6-8"
15342 </pre>
15343
15344 <p><strong>526. Sort the items of an array:</strong></p>
15345 <pre>
15346 var arr1 = [ 3, 8, 7, 6, 5, -4, 3, 2, 1 ];
15347 [Link](function(a, b) {
15348 return a - b;
15349 });
15350 [Link]([Link](',')); // "-4,-3,1,2,3,5,6,7,8"
15351 </pre>
15352
15353 <p><strong>527. Find the most frequent item of an array:</strong></p>
15354 <pre>
15355 var arr1 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 2, 4, 9, 3];
15356 var freqMap = {};
15357 var maxFreq = 0;
15358 var mostFreqItem;
15359
15360 [Link](function(item) {
15361 freqMap[item] = (freqMap[item] || 0) + 1;
15362 if (freqMap[item] > maxFreq) {
15363 maxFreq = freqMap[item];
15364 mostFreqItem = item;
15365 }
15366 });
15367
15368 [Link](mostFreqItem + " ( " + maxFreq + " times )"); // "a ( 5 times )"
15369 </pre>
15370
15371 <p><strong>528. Swap the case of each character in a string:</strong></p>
15372 <pre>
15373 function swapCase(str) {
15374 var swapped = '';
15375 for (var i = 0; i < [Link]; i++) {
15376 var char = str[i];
15377 if (char === [Link]()) {
15378 swapped += [Link]();
15379 } else {
15380 swapped += [Link]();
15381 }
15382 }
15383 return swapped;
15384 }
15385
15386 [Link](swapCase('The Quick Brown Fox')); // "tHE qUICK bROWN fOX"
15387 </pre>
15388
15389 <p><strong>529. Print the elements of a nested array using nested for loops:</strong><
/p>
15390 <pre>
15391 var a = [
15392 [1, 2, 1, 24],
15393 [8, 11, 9, 4],
15394 [7, 0, 7, 27],
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 260/298
1/31/24, 9:21 AM [Link]
15395 [7, 4, 28, 14],
15396 [3, 10, 26, 7]
15397 ];
15398
15399 for (var i = 0; i < [Link]; i++) {
15400 [Link]("row " + i);
15401 for (var j = 0; j < a[i].length; j++) {
15402 [Link](" " + a[i][j]);
15403 }
15404 }
15405 </pre>
15406
15407 <p><strong>530. Find the sum of squares of a numeric vector:</strong></p>
15408 <pre>
15409 function sumOfSquares(arr) {
15410 return [Link](function(sum, num) {
15411 return sum + (num * num);
15412 }, 0);
15413 }
15414
15415 [Link](sumOfSquares([1, 2, 3, 4])); // 30 (1^2 + 2^2 + 3^2 + 4^2)
15416 </pre>
15417
15418 <p><strong>531. Compute the sum and product of an array of integers:</strong></p>
15419 <pre>
15420 function sumAndProduct(arr) {
15421 var sum = [Link](function(acc, num) {
15422 return acc + num;
15423 }, 0);
15424 var product = [Link](function(acc, num) {
15425 return acc * num;
15426 }, 1);
15427 return { sum: sum, product: product };
15428 }
15429
15430 [Link](sumAndProduct([1, 2, 3, 4])); // { sum: 10, product: 24 }
15431 </pre>
15432
15433 <p><strong>532. Add items to an array and display them:</strong></p>
15434 <pre>
15435 var items = [];
15436
15437 function addItem(item) {
15438 [Link](item);
15439 [Link]("Items: " + [Link](', '));
15440 }
15441
15442 addItem('apple');
15443 addItem('banana');
15444 addItem('orange');
15445 </pre>
15446
15447 <p><strong>533. Remove duplicate items from an array (ignore case sensitivity):</strong>
</p>
15448 <pre>
15449 function removeDuplicates(arr) {
15450 var uniqueArray = [Link](function(item, index, self) {
15451 return [Link]([Link]()) === index;
15452 });
15453 return uniqueArray;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 261/298
1/31/24, 9:21 AM [Link]
15454 }
15455
15456 var colors = ["Red", "red", "Green", "blue", "Green", "yellow", "Yellow"];
15457 [Link](removeDuplicates(colors)); // ["Red", "Green", "blue", "yellow"]
15458 </pre>
15459
15460 <p><strong>534. Display colors using ordinal numbers:</strong></p>
15461 <pre>
15462 var color = ["Blue ", "Green", "Red", "Orange", "Violet", "Indigo", "Yellow "];
15463 var o = ["th", "st", "nd", "rd"];
15464
15465 for (var i = 0; i < [Link]; i++) {
15466 var ordinal = (i + 1) % 10;
15467 var suffix = (ordinal <= 3) ? o[ordinal] : o[0];
15468 [Link]((i + 1) + suffix + " choice is " + color[i]);
15469 }
15470 </pre>
15471
15472 <p><strong>535. Find leap years in a given range of years:</strong></p>
15473 <pre>
15474 function findLeapYears(startYear, endYear) {
15475 var leapYears = [];
15476 for (var year = startYear; year <= endYear; year++) {
15477 if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)) {
15478 [Link](year);
15479 }
15480 }
15481 return leapYears;
15482 }
15483
15484 [Link](findLeapYears(2000, 2024)); // [2000, 2004, ..., 2020, 2024]
15485 </pre>
15486
15487 <p><strong>536. Shuffle an array:</strong></p>
15488 <pre>
15489 function shuffleArray(arr) {
15490 for (var i = [Link] - 1; i > 0; i--) {
15491 var j = [Link]([Link]() * (i + 1));
15492 var temp = arr[i];
15493 arr[i] = arr[j];
15494 arr[j] = temp;
15495 }
15496 return arr;
15497 }
15498
15499 var myArray = [1, 2, 3, 4, 5];
15500 [Link](shuffleArray(myArray));
15501 </pre>
15502
15503 <p><strong>537. Perform a binary search:</strong></p>
15504 <pre>
15505 function binarySearch(arr, key) {
15506 var low = 0;
15507 var high = [Link] - 1;
15508 while (low <= high) {
15509 var mid = [Link]((low + high) / 2);
15510 if (arr[mid] === key) {
15511 return mid;
15512 } else if (arr[mid] < key) {
15513 low = mid + 1;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 262/298
1/31/24, 9:21 AM [Link]
15514 } else {
15515 high = mid - 1;
15516 }
15517 }
15518 return -1;
15519 }
15520
15521 var items = [1, 2, 3, 4, 5, 7, 8, 9];
15522 [Link](binarySearch(items, 1)); // 0
15523 [Link](binarySearch(items, 5)); // 4
15524 </pre>
15525
15526 <p><strong>538. Compute the sum of each individual index value from two given arrays:<
/strong></p>
15527 <pre>
15528 function sumArrays(arr1, arr2) {
15529 var maxLength = [Link]([Link], [Link]);
15530 var result = [];
15531 for (var i = 0; i < maxLength; i++) {
15532 var sum = (arr1[i] || 0) + (arr2[i] || 0);
15533 [Link](sum);
15534 }
15535 return result;
15536 }
15537
15538 var array1 = [1, 0, 2, 3, 4];
15539 var array2 = [3, 5, 6, 7, 8, 13];
15540 [Link](sumArrays(array1, array2)); // [4, 5, 8, 10, 12, 13]
15541 </pre>
15542
15543 <p><strong>539. Find duplicate values in a JavaScript array:</strong></p>
15544 <pre>
15545 function findDuplicates(arr) {
15546 var duplicates = {};
15547 var result = [];
15548 [Link](function(item) {
15549 if (duplicates[item]) {
15550 duplicates[item]++;
15551 } else {
15552 duplicates[item] = 1;
15553 }
15554 });
15555 for (var key in duplicates) {
15556 if (duplicates[key] > 1) {
15557 [Link](key);
15558 }
15559 }
15560 return result;
15561 }
15562
15563 var myArray = [1, 2, 3, 4, 2, 7, 8, 8, 3];
15564 [Link](findDuplicates(myArray)); // [2, 3, 8]
15565 </pre>
15566
15567 <p><strong>540. Flatten a nested array:</strong></p>
15568 <pre>
15569 function flatten(arr, shallow) {
15570 var flat = [];
15571 [Link](function(item) {
15572 if ([Link](item) && !shallow) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 263/298
1/31/24, 9:21 AM [Link]
15573 flat = [Link](flatten(item));
15574 } else {
15575 [Link](item);
15576 }
15577 });
15578 return flat;
15579 }
15580
15581 [Link](flatten([1, [2], [3, [[4]]], [5, 6]])); // [1, 2, 3, 4, 5, 6]
15582 [Link](flatten([1, [2], [3, [[4]]], [5, 6]], true)); // [1, 2, 3, [[4]], 5, 6]
15583 </pre>
15584
15585 <p><strong>541. Compute the union of two arrays:</strong></p>
15586 <pre>
15587 function union(arr1, arr2) {
15588 var unionArr = [Link]([Link](function(item) {
15589 return [Link](item) === -1;
15590 }));
15591 return unionArr;
15592 }
15593
15594 [Link](union([1, 2, 3], [100, 2, 1, 10])); // [1, 2, 3, 10, 100]
15595 </pre>
15596
15597 <p><strong>542. Find the difference of two arrays:</strong></p>
15598 <pre>
15599 function difference(arr1, arr2) {
15600 var diff = [Link](function(item) {
15601 return [Link](item) === -1;
15602 }).concat([Link](function(item) {
15603 return [Link](item) === -1;
15604 }));
15605 return diff;
15606 }
15607
15608 [Link](difference([1, 2, 3], [100, 2, 1, 10])); // ["3", "10", "100"]
15609 [Link](difference([1, 2, 3, 4, 5], [1, [2], [3, [[4]]], [5, 6]])); // ["6"]
15610 [Link](difference([1, 2, 3], [100, 2, 1, 10])); // ["3", "10", "100"]
15611 </pre>
15612
15613 <p><strong>543. Remove null, 0, "", false, undefined, and NaN values from an array:<
/strong></p>
15614 <pre>
15615 function cleanArray(arr) {
15616 var cleanedArray = [Link](function(item) {
15617 return item !== null && item !== 0 && item !== "" && item !== false && item !==
undefined && !isNaN(item);
15618 });
15619 return cleanedArray;
15620 }
15621
15622 var sampleArray = [NaN, 0, 15, false, -22, '', undefined, 47, null];
15623 [Link](cleanArray(sampleArray)); // [15, -22, 47]
15624 </pre>
15625
15626 <p><strong>544. Sort an array of objects by title value:</strong></p>
15627 <pre>
15628 var library = [
15629 { author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254},
15630 { author: 'Steve Jobs', title: 'Walter Isaacson', libraryID: 4264},
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 264/298
1/31/24, 9:21 AM [Link]
15631 { author: 'Suzanne Collins', title: 'Mockingjay: The Final Book of The Hunger Games'
, libraryID: 3245}
15632 ];
15633
15634 function sortByTitle(arr) {
15635 [Link](function(a, b) {
15636 var titleA = [Link]();
15637 var titleB = [Link]();
15638 if (titleA < titleB) {
15639 return -1;
15640 }
15641 if (titleA > titleB) {
15642 return 1;
15643 }
15644 return 0;
15645 });
15646 return arr;
15647 }
15648
15649 [Link](sortByTitle(library));
15650 </pre>
15651
15652 <p><strong>545. Find a pair of elements whose sum equals a specific target number:<
/strong></p>
15653 <pre>
15654 function findPair(numbers, target) {
15655 var indices = [];
15656 for (var i = 0; i < [Link]; i++) {
15657 for (var j = i + 1; j < [Link]; j++) {
15658 if (numbers[i] + numbers[j] === target) {
15659 [Link](i, j);
15660 return indices;
15661 }
15662 }
15663 }
15664 return indices;
15665 }
15666
15667 var numbers = [10, 20, 10, 40, 50, 60, 70];
15668 var target = 50;
15669 [Link](findPair(numbers, target));
15670 </pre>
15671
15672 <p><strong>546. Retrieve the value of a given property from all elements in an array:<
/strong></p>
15673 <pre>
15674 function getProperty(arr, prop) {
15675 return [Link](function(item) {
15676 return item[prop];
15677 });
15678 }
15679
15680 var sampleArray = [NaN, 0, 15, false, -22, '', undefined, 47, null];
15681 [Link](getProperty(sampleArray, '15')); // [15, -22, 47]
15682 </pre>
15683
15684 <p><strong>547. Find the longest common starting substring in a set of strings:</strong>
</p>
15685 <pre>
15686 function longestCommonStartingSubstring(arr) {
15687 if ([Link] === 0) return '';
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 265/298
1/31/24, 9:21 AM [Link]
15688 var firstStr = arr[0];
15689 for (var i = 0; i < [Link]; i++) {
15690 for (var j = 1; j < [Link]; j++) {
15691 if (firstStr[i] !== arr[j][i]) {
15692 return [Link](0, i);
15693 }
15694 }
15695 }
15696 return firstStr;
15697 }
15698
15699 [Link](longestCommonStartingSubstring(['go', 'google'])); // "go"
15700 </pre>
15701
15702 <p><strong>548. Fill an array with values (numeric, string with one character) on
supplied bounds:</strong></p>
15703 <pre>
15704 function numStringRange(start, end, step) {
15705 var arr = [];
15706 if (typeof start === 'number' && typeof end === 'number') {
15707 for (var i = start; i <= end; i += step) {
15708 [Link](i);
15709 }
15710 } else if (typeof start === 'string' && typeof end === 'string') {
15711 for (var charCode = [Link](0); charCode <= [Link](0); charCode
+= step) {
15712 [Link]([Link](charCode));
15713 }
15714 }
15715 return arr;
15716 }
15717
15718 [Link](numStringRange('a', 'z', 2)); // ["a", "c", "e", "g", "i", "k", "m", "o", "
q", "s", "u", "w", "y"]
15719 </pre>
15720
15721 <p><strong>549. Merge two arrays and remove all duplicate elements:</strong></p>
15722 <pre>
15723 function mergeArray(arr1, arr2) {
15724 var merged = [Link](arr2);
15725 var unique = [Link](function(item, index) {
15726 return [Link](item) === index;
15727 });
15728 return unique;
15729 }
15730
15731 var array1 = [1, 2, 3];
15732 var array2 = [2, 30, 1];
15733 [Link](mergeArray(array1, array2)); // [3, 2, 30, 1]
15734 </pre>
15735
15736 <p><strong>550. Remove a specific element from an array:</strong></p>
15737 <pre>
15738 function removeArrayElement(arr, elem) {
15739 return [Link](function(item) {
15740 return item !== elem;
15741 });
15742 }
15743
15744 [Link](removeArrayElement([2, 5, 9, 6], 5)); // [2, 9, 6]
15745 </pre>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 266/298
1/31/24, 9:21 AM [Link]
15746
15747 <p><strong>551. Check if an array contains a specific element:</strong></p>
15748 <pre>
15749 function contains(arr, elem) {
15750 return [Link](elem);
15751 }
15752
15753 var arr = [2, 5, 9, 6];
15754 [Link](contains(arr, 5)); // true
15755 </pre>
15756
15757 <p><strong>552. Empty an array while keeping the original:</strong></p>
15758 <pre>
15759 function emptyArray(arr) {
15760 [Link] = 0;
15761 }
15762
15763 var originalArray = [1, 2, 3, 4, 5];
15764 var copiedArray = [Link]();
15765 emptyArray(originalArray);
15766 [Link](originalArray); // []
15767 [Link](copiedArray); // [1, 2, 3, 4, 5]
15768 </pre>
15769
15770 <p><strong>553. Get the nth largest element from an unsorted array:</strong></p>
15771 <pre>
15772 function nthLargest(arr, n) {
15773 if (n > [Link] || n < 1) return null;
15774 var sorted = [Link]().sort(function(a, b) {
15775 return b - a;
15776 });
15777 return sorted[n - 1];
15778 }
15779
15780 [Link](nthLargest([43, 56, 23, 89, 88, 90, 99, 652], 4)); // 89
15781 </pre>
15782
15783 <p><strong>554. Get a random item from an array:</strong></p>
15784 <pre>
15785 function getRandomItem(arr) {
15786 return arr[[Link]([Link]() * [Link])];
15787 }
15788
15789 var myArray = [1, 2, 3, 4, 5];
15790 [Link](getRandomItem(myArray));
15791 </pre>
15792
15793 <p><strong>555. Create a specified number of elements with pre-filled numeric value
array:</strong></p>
15794 <pre>
15795 function arrayFilled(length, value) {
15796 return Array(length).fill(value);
15797 }
15798
15799 [Link](arrayFilled(6, 0)); // [0, 0, 0, 0, 0, 0]
15800 [Link](arrayFilled(4, 11)); // [11, 11, 11, 11]
15801 </pre>
15802
15803 <p><strong>556. Create a specified number of elements with pre-filled string value
array:</strong></p>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 267/298
1/31/24, 9:21 AM [Link]
15804 <pre>
15805 function arrayFilled(length, value) {
15806 return Array(length).fill(value);
15807 }
15808
15809 [Link](arrayFilled(3, 'default value')); // ["default value", "default value", "
default value"]
15810 [Link](arrayFilled(4, 'password')); // ["password", "password", "password", "
password"]
15811 </pre>
15812
15813 <p><strong>557. Move an array element from one position to another:</strong></p>
15814 <pre>
15815 function move(arr, fromIndex, toIndex) {
15816 [Link](toIndex, 0, [Link](fromIndex, 1)[0]);
15817 return arr;
15818 }
15819
15820 [Link](move([10, 20, 30, 40, 50], 0, 2)); // [20, 30, 10, 40, 50]
15821 [Link](move([10, 20, 30, 40, 50], -1, -2)); // [10, 20, 30, 50, 40]
15822 </pre>
15823
15824 <p><strong>558. Filter false, null, 0, and blank values from an array:</strong></p>
15825 <pre>
15826 function filterArrayValues(arr) {
15827 return [Link](Boolean);
15828 }
15829
15830 [Link](filterArrayValues([58, '', 'abcd', true, null, false, 0])); // [58, "abcd",
true]
15831 </pre>
15832
15833 <p><strong>559. Generate an array of specified length, filled with integer numbers,
increasing by one from starting position:</strong></p>
15834 <pre>
15835 function arrayRange(start, length) {
15836 return [Link]({ length: length }, (_, i) => start + i);
15837 }
15838
15839 [Link](arrayRange(1, 4)); // [1, 2, 3, 4]
15840 [Link](arrayRange(-6, 4)); // [-6, -5, -4, -3]
15841 </pre>
15842
15843 <p><strong>560. Generate an array between two integers of 1 step length:</strong></p>
15844 <pre>
15845 function rangeBetween(start, end) {
15846 return [Link]({ length: [Link](end - start) + 1 }, (_, i) => start < end ?
start + i : start - i);
15847 }
15848
15849 [Link](rangeBetween(4, 7)); // [4, 5, 6, 7]
15850 [Link](rangeBetween(-4, 7)); // [-4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
15851 </pre>
15852
15853 <p><strong>561. Find the unique elements from two arrays:</strong></p>
15854 <pre>
15855 function difference(arr1, arr2) {
15856 var combined = [Link](arr2);
15857 return [Link](new Set([Link](String)));
15858 }
15859
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 268/298
1/31/24, 9:21 AM [Link]
15860 [Link](difference([1, 2, 3], [100, 2, 1, 10])); // ["1", "2", "3", "10", "100"]
15861 [Link](difference([1, 2, 3, 4, 5], [1, [2], [3, [[4]]],[5,6]])); // ["1", "2", "3",
"4", "5", "6"]
15862 [Link](difference([1, 2, 3], [100, 2, 1, 10])); // ["1", "2", "3", "10", "100"]
15863 </pre>
15864
15865 <p><strong>562. Create an array of arrays, ungrouping the elements produced by zip:<
/strong></p>
15866 <pre>
15867 function unzip(arr) {
15868 return arr[0].map((_, i) => [Link](row => row[i]));
15869 }
15870
15871 [Link](unzip([['a', 1, true], ['b', 2, false]]));
15872 [Link](unzip([['a', 1, true], ['b', 2]]));
15873 // Expected Output:
15874 // [["a","b"],[1,2],[true,false]]
15875 // [["a","b"],[1,2],[true]]
15876 </pre>
15877
15878 <p><strong>563. Create an object from an array, using the specified key and excluding it
from each value:</strong></p>
15879 <pre>
15880 function indexOn(arr, keyFunc) {
15881 return [Link]((acc, obj) => {
15882 const key = keyFunc(obj);
15883 const { [key]: omit, ...rest } = obj;
15884 return { ...acc, [key]: rest };
15885 }, {});
15886 }
15887
15888 [Link](indexOn([ { id: 10, name: 'apple' }, { id: 20, name: 'orange' } ], x =>
[Link]));
15889 // Expected Output:
15890 // {"10":{"name":"apple"},"20":{"name":"orange"}}
15891 </pre>
15892
15893 <p><strong>564. Check whether an input is a date object or not:</strong></p>
15894 <pre>
15895 function isDate(input) {
15896 return input instanceof Date && !isNaN(input);
15897 }
15898
15899 [Link](isDate("October 13, 2014 [Link]")); // false
15900 [Link](isDate(new Date(86400000))); // true
15901 [Link](isDate(new Date(99,5,24,11,33,30,0))); // true
15902 [Link](isDate([1, 2, 4, 0])); // false
15903 </pre>
15904
15905 <p><strong>565. Get the current date with a specified separator:</strong></p>
15906 <pre>
15907 function curDay(separator) {
15908 const today = new Date();
15909 const day = [Link]().toString().padStart(2, '0');
15910 const month = ([Link]() + 1).toString().padStart(2, '0');
15911 const year = [Link]();
15912 return `${month}${separator}${day}${separator}${year}`;
15913 }
15914
15915 [Link](curDay('/')); // "11/13/2014"
15916 [Link](curDay('-')); // "11-13-2014"
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 269/298
1/31/24, 9:21 AM [Link]
15917 </pre>
15918
15919 <p><strong>566. Get the number of days in a month:</strong></p>
15920 <pre>
15921 function getDaysInMonth(month, year) {
15922 return new Date(year, month, 0).getDate();
15923 }
15924
15925 [Link](getDaysInMonth(1, 2012)); // 31
15926 [Link](getDaysInMonth(2, 2012)); // 29
15927 [Link](getDaysInMonth(9, 2012)); // 30
15928 [Link](getDaysInMonth(12, 2012)); // 31
15929 </pre>
15930
15931 <p><strong>567. Get the month name from a particular date:</strong></p>
15932 <pre>
15933 function monthName(date) {
15934 const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', '
August', 'September', 'October', 'November', 'December'];
15935 return months[[Link]()];
15936 }
15937
15938 [Link](monthName(new Date("10/11/2009"))); // "October"
15939 [Link](monthName(new Date("11/13/2014"))); // "November"
15940 </pre>
15941
15942 <p><strong>568. Compare dates (greater than, less than, or equal to):</strong></p>
15943 <pre>
15944 function compareDates(date1, date2) {
15945 if ([Link]() === [Link]()) {
15946 return "Date1 = Date2";
15947 } else if (date1 > date2) {
15948 return "Date1 > Date2";
15949 } else {
15950 return "Date2 > Date1";
15951 }
15952 }
15953
15954 [Link](compareDates(new Date('11/14/2013 00:00'), new Date('11/14/2013 00:00')));
15955 [Link](compareDates(new Date('11/14/2013 00:01'), new Date('11/14/2013 00:00')));
15956 [Link](compareDates(new Date('11/14/2013 00:00'), new Date('11/14/2013 00:01')));
15957 // Output:
15958 // "Date1 = Date2"
15959 // "Date1 > Date2"
15960 // "Date2 > Date1"
15961 </pre>
15962
15963 <p><strong>569. Add specified minutes to a Date object:</strong></p>
15964 <pre>
15965 function addMinutes(date, minutes) {
15966 return new Date([Link]() + minutes * 60000);
15967 }
15968
15969 [Link](addMinutes(new Date(2014,10,2), 30).toString());
15970 // Output:
15971 // "Sun Nov 02 2014 [Link] GMT+0530 (India Standard Time)"
15972 </pre>
15973
15974 <p><strong>570. Test whether a date is a weekend:</strong></p>
15975 <pre>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 270/298
1/31/24, 9:21 AM [Link]
15976 function isWeekend(dateString) {
15977 const date = new Date(dateString);
15978 const dayOfWeek = [Link]();
15979 return dayOfWeek === 0 || dayOfWeek === 6 ? "weekend" : undefined;
15980 }
15981
15982 [Link](isWeekend('Nov 15, 2014'));
15983 [Link](isWeekend('Nov 16, 2014'));
15984 [Link](isWeekend('Nov 17, 2014'));
15985 // Output:
15986 // "weekend"
15987 // "weekend"
15988 // undefined
15989 </pre>
15990
15991 <p><strong>571. Get difference between two dates in days:</strong></p>
15992 <pre>
15993 function dateDiffInDays(dateString1, dateString2) {
15994 const date1 = new Date(dateString1);
15995 const date2 = new Date(dateString2);
15996 const diffInMs = [Link](date2 - date1);
15997 return [Link](diffInMs / (1000 * 60 * 60 * 24));
15998 }
15999
16000 [Link](dateDiffInDays('04/02/2014', '11/04/2014'));
16001 [Link](dateDiffInDays('12/02/2014', '11/04/2014'));
16002 // Output:
16003 // 216
16004 // -28
16005 </pre>
16006
16007 <p><strong>572. Get the last day of a month:</strong></p>
16008 <pre>
16009 function lastDay(year, month) {
16010 return new Date(year, month + 1, 0).getDate();
16011 }
16012
16013 [Link](lastDay(2014, 0));
16014 [Link](lastDay(2014, 1));
16015 [Link](lastDay(2014, 11));
16016 // Output:
16017 // 31
16018 // 28
16019 // 31
16020 </pre>
16021
16022 <p><strong>573. Calculate 'yesterday day':</strong></p>
16023 <pre>
16024 function yesterday(dateString) {
16025 const date = new Date(dateString);
16026 [Link]([Link]() - 1);
16027 return [Link]();
16028 }
16029
16030 [Link](yesterday('Nov 15, 2014'));
16031 [Link](yesterday('Nov 16, 2015'));
16032 [Link](yesterday('Nov 17, 2016'));
16033 // Output:
16034 // "Fri Nov 14 2014 [Link] GMT+0530 (India Standard Time)"
16035 // "Sun Nov 15 2015 [Link] GMT+0530 (India Standard Time)"
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 271/298
1/31/24, 9:21 AM [Link]
16036 // "Wed Nov 16 2016 [Link] GMT+0530 (India Standard Time)"
16037 </pre>
16038
16039 <p><strong>574. Get the maximum date from an array of dates:</strong></p>
16040 <pre>
16041 function maxDate(dateArray) {
16042 return new Date([Link](null, [Link](date => new Date(date))));
16043 }
16044
16045 [Link](maxDate(['2015/02/01', '2015/02/02', '2015/01/03']));
16046 // Output:
16047 // "2015/02/02"
16048 </pre>
16049
16050 <p><strong>575. Get the minimum date from an array of dates:</strong></p>
16051 <pre>
16052 function minDate(dateArray) {
16053 return new Date([Link](null, [Link](date => new Date(date))));
16054 }
16055
16056 [Link](minDate(['2015/02/01', '2015/02/02', '2015/01/03']));
16057 // Output:
16058 // "2015/01/03"
16059 </pre>
16060
16061 <p><strong>576. Return the number of minutes in hours and minutes:</strong></p>
16062 <pre>
16063 function timeConvert(minutes) {
16064 const hours = [Link](minutes / 60);
16065 const remainingMinutes = minutes % 60;
16066 return `${minutes} minutes = ${hours} hour(s) and ${remainingMinutes} minute(s).`;
16067 }
16068
16069 [Link](timeConvert(200));
16070 // Output:
16071 // "200 minutes = 3 hour(s) and 20 minute(s)."
16072 </pre>
16073
16074 <p><strong>577. Get the amount of days of a year:</strong></p>
16075 <pre>
16076 function daysOfAYear(year) {
16077 return new Date(year, 11, 31).getDate();
16078 }
16079
16080 [Link](daysOfAYear(2015)); // 365
16081 [Link](daysOfAYear(2016)); // 366
16082 </pre>
16083
16084 <p><strong>578. Get the quarter (1 to 4) of the year:</strong></p>
16085 <pre>
16086 function quarterOfTheYear(date) {
16087 const month = [Link]();
16088 return [Link](month / 3) + 1;
16089 }
16090
16091 [Link](quarterOfTheYear(new Date(2015, 1, 21))); // 2
16092 [Link](quarterOfTheYear(new Date(2015, 10, 18))); // 4
16093 </pre>
16094
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 272/298
1/31/24, 9:21 AM [Link]
16095 <p><strong>579. Count the number of days passed since the beginning of the year:<
/strong></p>
16096 <pre>
16097 function daysPassed(date) {
16098 const startOfYear = new Date([Link](), 0, 0);
16099 const diff = date - startOfYear;
16100 const oneDay = 1000 * 60 * 60 * 24;
16101 return [Link](diff / oneDay);
16102 }
16103
16104 [Link](daysPassed(new Date(2015, 0, 15))); // 15
16105 [Link](daysPassed(new Date(2015, 11, 14))); // 348
16106 </pre>
16107
16108 <p><strong>580. Convert a Unix timestamp to time:</strong></p>
16109 <pre>
16110 function convertUnixTimestamp(timestamp) {
16111 const date = new Date(timestamp * 1000);
16112 return [Link]();
16113 }
16114
16115 [Link](convertUnixTimestamp(1486932600)); // "2/12/2017"
16116 [Link](convertUnixTimestamp(1611840000)); // "1/28/2021"
16117 </pre>
16118
16119 <p><strong>581. Calculate age:</strong></p>
16120 <pre>
16121 function calculateAge(birthDate) {
16122 const today = new Date();
16123 const diff = today - birthDate;
16124 const ageDate = new Date(diff);
16125 return [Link]([Link]() - 1970);
16126 }
16127
16128 [Link](calculateAge(new Date(1982, 11, 4))); // 39
16129 [Link](calculateAge(new Date(1962, 1, 1))); // 59
16130 </pre>
16131
16132 <p><strong>582. Get the day of the month, 2 digits with leading zeros:</strong></p>
16133 <pre>
16134 function dayOfMonth(date) {
16135 return ('0' + [Link]()).slice(-2);
16136 }
16137
16138 const d = new Date(2015, 10, 1);
16139 [Link](dayOfMonth(d)); // "01"
16140 </pre>
16141
16142 <p><strong>583. Get a textual representation of a day (three letters, Mon through Sun):<
/strong></p>
16143 <pre>
16144 function shortDays(date) {
16145 const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
16146 return days[[Link]()];
16147 }
16148
16149 const dt = new Date(2015, 10, 1);
16150 [Link](shortDays(dt)); // "Sun"
16151 </pre>
16152
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 273/298
1/31/24, 9:21 AM [Link]
16153 <p><strong>584. Get a full textual representation of the day of the week (Sunday through
Saturday):</strong></p>
16154 <pre>
16155 function longDays(date) {
16156 const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', '
Saturday'];
16157 return days[[Link]()];
16158 }
16159
16160 const dt = new Date(2015, 10, 1);
16161 [Link](longDays(dt)); // "Sunday"
16162 </pre>
16163
16164 <p><strong>585. Get ISO-8601 numeric representation of the day of the week (1 to 7):<
/strong></p>
16165 <pre>
16166 function ISONumericDate(date) {
16167 return [Link]() || 7;
16168 }
16169
16170 const dt = new Date(2015, 10, 1);
16171 [Link](ISONumericDate(dt)); // 7
16172 </pre>
16173
16174 <p><strong>586. Get English ordinal suffix for the day of the month (st, nd, rd, or th):
</strong></p>
16175 <pre>
16176 function ordinalSuffix(date) {
16177 const day = [Link]();
16178 if (day > 3 && day < 21) return 'th';
16179 switch (day % 10) {
16180 case 1: return 'st';
16181 case 2: return 'nd';
16182 case 3: return 'rd';
16183 default: return 'th';
16184 }
16185 }
16186
16187 const dt = new Date(2015, 10, 1);
16188 [Link](ordinalSuffix(dt)); // "st"
16189 </pre>
16190
16191 <p><strong>587. Get ISO-8601 week number of year (weeks starting on Monday):</strong><
/p>
16192 <pre>
16193 function ISO8601WeekNo(date) {
16194 const oneJan = new Date([Link](), 0, 1);
16195 const difference = date - oneJan;
16196 const dayOfYear = [Link](difference / 86400000);
16197 const weekNo = [Link]((dayOfYear + [Link]() + 1) / 7);
16198 return weekNo;
16199 }
16200
16201 const dt = new Date(2015, 10, 1);
16202 [Link](ISO8601WeekNo(dt)); // 44
16203 </pre>
16204
16205 <p><strong>588. Get a full textual representation of a month (such as January or June):<
/strong></p>
16206 <pre>
16207 function fullMonth(date) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 274/298
1/31/24, 9:21 AM [Link]
16208 const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', '
August', 'September', 'October', 'November', 'December'];
16209 return months[[Link]()];
16210 }
16211
16212 const dt = new Date(2015, 10, 1);
16213 [Link](fullMonth(dt)); // "November"
16214 </pre>
16215
16216 <p><strong>589. Get a numeric representation of a month, with leading zeros (01 through
12):</strong></p>
16217 <pre>
16218 function numericMonth(date) {
16219 return ('0' + ([Link]() + 1)).slice(-2);
16220 }
16221
16222 const dt = new Date(2015, 10, 1);
16223 [Link](numericMonth(dt)); // "11"
16224 </pre>
16225
16226 <p><strong>590. Get a short textual representation of a month, three letters (Jan
through Dec):</strong></p>
16227 <pre>
16228 function shortMonths(date) {
16229 const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'
, 'Nov', 'Dec'];
16230 return months[[Link]()];
16231 }
16232
16233 const dt = new Date(2015, 10, 1);
16234 [Link](shortMonths(dt)); // "Nov"
16235 </pre>
16236
16237 <p><strong>591. Get a full numeric representation of a year (4 digits):</strong></p>
16238 <pre>
16239 function fullYear(date) {
16240 return [Link]();
16241 }
16242
16243 const dt = new Date(2015, 10, 1);
16244 [Link](fullYear(dt)); // 2015
16245 </pre>
16246
16247 <p><strong>592. Get a two-digit representation of a year:</strong></p>
16248 <pre>
16249 function shortYear(date) {
16250 return ('' + [Link]()).slice(-2);
16251 }
16252
16253 const dt = new Date(1989, 10, 1);
16254 [Link](shortYear(dt)); // "89"
16255 </pre>
16256
16257 <p><strong>593. Get lowercase Ante meridiem and Post meridiem:</strong></p>
16258 <pre>
16259 function lowercaseMeridiem() {
16260 const date = new Date();
16261 const hours = [Link]();
16262 return hours < 12 ? 'am' : 'pm';
16263 }
16264
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 275/298
1/31/24, 9:21 AM [Link]
16265 [Link](lowercaseMeridiem()); // "pm" (example)
16266 </pre>
16267
16268 <p><strong>594. Get uppercase Ante meridiem and Post meridiem:</strong></p>
16269 <pre>
16270 function uppercaseMeridiem() {
16271 const date = new Date();
16272 const hours = [Link]();
16273 return hours < 12 ? 'AM' : 'PM';
16274 }
16275
16276 [Link](uppercaseMeridiem()); // "PM" (example)
16277 </pre>
16278
16279 <p><strong>595. Swatch Internet time (000 through 999):</strong></p>
16280 <pre>
16281 function internetTime(date) {
16282 const hours = [Link]();
16283 const minutes = [Link]();
16284 const seconds = [Link]();
16285 const beats = [Link]((hours * 3600 + minutes * 60 + seconds + 36) / 86.4);
16286 return ('00' + beats).slice(-3);
16287 }
16288
16289 const dt = new Date(1989, 10, 1);
16290 [Link](internetTime(dt)); // 812
16291 </pre>
16292
16293 <p><strong>596. Get 12-hour format of an hour with leading zeros:</strong></p>
16294 <pre>
16295 function hoursWithZeroes(date) {
16296 const hours = [Link]() % 12 || 12;
16297 return ('0' + hours).slice(-2);
16298 }
16299
16300 const dt = new Date(1989, 10, 1);
16301 [Link](hoursWithZeroes(dt)); // "12"
16302 </pre>
16303
16304 <p><strong>597. Get 24-hour format of an hour without leading zeros:</strong></p>
16305 <pre>
16306 function hoursWithoutZeroes(date) {
16307 return [Link]();
16308 }
16309
16310 const dt = new Date(1989, 10, 1);
16311 [Link](hoursWithoutZeroes(dt)); // 0
16312 </pre>
16313
16314 <p><strong>598. Get minutes with leading zeros (00 to 59):</strong></p>
16315 <pre>
16316 function minutesWithLeadingZeros(date) {
16317 const minutes = [Link]();
16318 return ('0' + minutes).slice(-2);
16319 }
16320
16321 const dt = new Date(1989, 10, 1);
16322 [Link](minutesWithLeadingZeros(dt)); // "00"
16323 </pre>
16324
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 276/298
1/31/24, 9:21 AM [Link]
16325 <p><strong>599. Get seconds with leading zeros (00 through 59):</strong></p>
16326 <pre>
16327 function secondsWithLeadingZeros(date) {
16328 const seconds = [Link]();
16329 return ('0' + seconds).slice(-2);
16330 }
16331
16332 const dt = new Date(1989, 10, 1);
16333 [Link](secondsWithLeadingZeros(dt)); // "00"
16334 </pre>
16335
16336 <p><strong>600. Get Timezone:</strong></p>
16337 <pre>
16338 function getTimezone() {
16339 const date = new Date();
16340 return [Link]().match(/\(([^)]+)\)$/)[1];
16341 }
16342
16343 [Link](getTimezone()); // "India Standard Time" (example)
16344 </pre>
16345
16346 // ---------------------------- 300 - 400 -------------------------
16347
16348 <p><strong>301. Run a function in a separate thread using Web Worker:</strong></p>
16349 <pre>
16350 // [Link]
16351 [Link] = function(e) {
16352 const result = longRunningFunction([Link]);
16353 [Link](result);
16354 };
16355
16356 // Main JavaScript file
16357 const worker = new Worker('[Link]');
16358 [Link](data);
16359 [Link] = function(e) {
16360 [Link]([Link]); // Result from the longRunningFunction
16361 };
16362 </pre>
16363
16364 <p><strong>302. Round a number to a specified amount of digits:</strong></p>
16365 <pre>
16366 function roundNumber(num, digits) {
16367 return Number([Link](digits));
16368 }
16369
16370 [Link](roundNumber(3.14159, 2)); // 3.14
16371 </pre>
16372
16373 <p><strong>303. Reverse the order of characters in a string:</strong></p>
16374 <pre>
16375 function reverseString(str) {
16376 return [Link]('').reverse().join('');
16377 }
16378
16379 [Link](reverseString('hello')); // "olleh"
16380 </pre>
16381
16382 <p><strong>304. Create an object composed of properties for which a given function
returns falsey:</strong></p>
16383 <pre>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 277/298
1/31/24, 9:21 AM [Link]
16384 function pickBy(object, predicate) {
16385 return [Link](
16386 [Link](object).filter(([key, value]) => !predicate(value, key))
16387 );
16388 }
16389
16390 const obj = { a: 1, b: null, c: undefined, d: 0 };
16391 [Link](pickBy(obj, (value, key) => value == null)); // { a: 1, d: 0 }
16392 </pre>
16393
16394 <p><strong>305. Filter array keeping elements where predicate returns false:</strong><
/p>
16395 <pre>
16396 function reject(array, predicate) {
16397 return [Link](element => !predicate(element));
16398 }
16399
16400 const numbers = [1, 2, 3, 4, 5];
16401 [Link](reject(numbers, x => x % 2 === 0)); // [1, 3, 5]
16402 </pre>
16403
16404 <p><strong>306. Apply a function against an accumulator and each element in the array,
returning an array of successively reduced values:</strong></p>
16405 <pre>
16406 function reduceRight(array, func, initialValue) {
16407 let accumulator = initialValue;
16408 for (let i = [Link] - 1; i >= 0; i--) {
16409 accumulator = func(accumulator, array[i], i, array);
16410 }
16411 return accumulator;
16412 }
16413
16414 const numbers = [1, 2, 3, 4, 5];
16415 const sum = reduceRight(numbers, (acc, curr) => acc + curr, 0);
16416 [Link](sum); // 15
16417 </pre>
16418
16419 <p><strong>307. Redirect to a specified URL:</strong></p>
16420 <pre>
16421 // JavaScript
16422 [Link] = '[Link]
16423
16424 // HTML
16425 <meta http-equiv="refresh" content="0; URL='[Link] />
16426 </pre>
16427
16428 <p><strong>308. Create a function that invokes the provided function with its arguments
arranged according to the specified indexes:</strong></p>
16429 <pre>
16430 function rearg(func, indexes) {
16431 return (...args) => func(...[Link](index => args[index]));
16432 }
16433
16434 const reargedFunction = rearg((a, b, c) => [a, b, c], [2, 0, 1]);
16435 [Link](reargedFunction(1, 2, 3)); // [3, 1, 2]
16436 </pre>
16437
16438 <p><strong>309. Get an array of lines from the specified file:</strong></p>
16439 <pre>
16440 // Assuming a function fetchFileLines() is defined elsewhere
16441 fetchFileLines('[Link]')
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 278/298
1/31/24, 9:21 AM [Link]
16442 .then(lines => [Link](lines))
16443 .catch(error => [Link](error));
16444 </pre>
16445
16446 <p><strong>310. Mutate the original array to filter out the values specified, based on a
given iterator function:</strong></p>
16447 <pre>
16448 function pull(array, ...values) {
16449 const pullSet = new Set(values);
16450 let index = 0;
16451 for (let i = 0; i < [Link]; i++) {
16452 if () {
16453 array[index++] = array[i];
16454 }
16455 }
16456 [Link] = index;
16457 return array;
16458 }
16459
16460 const array = [1, 2, 3, 4, 5];
16461 pull(array, 2, 4);
16462 [Link](array); // [1, 3, 5]
16463 </pre>
16464
16465 <p><strong>311. Mutate the original array to filter out the values specified. Returns
the removed elements:</strong></p>
16466 <pre>
16467 function pullAt(array, ...indexes) {
16468 const removed = [];
16469 [Link]((a, b) => a - b);
16470 let pullOffset = 0;
16471 [Link]((index, i) => {
16472 const adjustedIndex = index - pullOffset++;
16473 [Link]([Link](adjustedIndex, 1)[0]);
16474 });
16475 return removed;
16476 }
16477
16478 const array = ['a', 'b', 'c', 'd'];
16479 const removed = pullAt(array, 1, 3);
16480 [Link](array); // ['a', 'c']
16481 [Link](removed); // ['b', 'd']
16482 </pre>
16483
16484 <p><strong>312. Convert an asynchronous function to return a promise:</strong></p>
16485 <pre>
16486 function promisify(asyncFunction) {
16487 return function(...args) {
16488 return new Promise((resolve, reject) => {
16489 asyncFunction(...args, (error, result) => {
16490 if (error) {
16491 reject(error);
16492 } else {
16493 resolve(result);
16494 }
16495 });
16496 });
16497 };
16498 }
16499
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 279/298
1/31/24, 9:21 AM [Link]
16500 // Usage example:
16501 const readFileAsync = promisify([Link]);
16502 readFileAsync('[Link]', 'utf8')
16503 .then(data => [Link](data))
16504 .catch(error => [Link](error));
16505 </pre>
16506
16507 <p><strong>313. Convert a number in bytes to a human-readable string:</strong></p>
16508 <pre>
16509 function bytesToSize(bytes) {
16510 const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
16511 if (bytes === 0) return '0 Byte';
16512 const i = [Link]([Link](bytes) / [Link](1024));
16513 return parseFloat((bytes / [Link](1024, i)).toFixed(2)) + ' ' + sizes[i];
16514 }
16515
16516 [Link](bytesToSize(1024)); // 1 KB
16517 </pre>
16518
16519 <p><strong>314. Return the singular or plural form of the word based on the input
number:</strong></p>
16520 <pre>
16521 function pluralize(number, word) {
16522 return number === 1 ? word : word + 's';
16523 }
16524
16525 [Link](pluralize(1, 'apple')); // apple
16526 [Link](pluralize(3, 'apple')); // apples
16527 </pre>
16528
16529 <p><strong>315. Perform left-to-right function composition:</strong></p>
16530 <pre>
16531 function compose(...fns) {
16532 return value => [Link]((acc, fn) => fn(acc), value);
16533 }
16534
16535 const add5 = x => x + 5;
16536 const multiplyBy2 = x => x * 2;
16537 const divideBy3 = x => x / 3;
16538
16539 const composedFunction = compose(add5, multiplyBy2, divideBy3);
16540 [Link](composedFunction(6)); // ((6 / 3) * 2) + 5 = 9
16541 </pre>
16542
16543 <p><strong>316. Perform left-to-right function composition for asynchronous functions:<
/strong></p>
16544 <pre>
16545 async function composeAsync(...fns) {
16546 return async value => {
16547 for (const fn of fns) {
16548 value = await fn(value);
16549 }
16550 return value;
16551 };
16552 }
16553
16554 const add5Async = async x => x + 5;
16555 const multiplyBy2Async = async x => x * 2;
16556 const divideBy3Async = async x => x / 3;
16557
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 280/298
1/31/24, 9:21 AM [Link]
16558 const composedAsyncFunction = await composeAsync(add5Async, multiplyBy2Async,
divideBy3Async);
16559 [Link](await composedAsyncFunction(6)); // ((6 / 3) * 2) + 5 = 9
16560 </pre>
16561
16562 <p><strong>317. Calculate how many numbers in the given array are less or equal to the
given value using the percentile formula:</strong></p>
16563 <pre>
16564 function percentile(array, value) {
16565 const count = [Link]((acc, num) => num <= value ? acc + 1 : acc, 0);
16566 return count / [Link];
16567 }
16568
16569 const numbers = [1, 2, 3, 4, 5];
16570 [Link](percentile(numbers, 3)); // 0.6
16571 </pre>
16572
16573 <p><strong>318. Group the elements into two arrays, depending on the provided function's
truthiness for each element:</strong></p>
16574 <pre>
16575 function partition(array, predicate) {
16576 return [Link]((acc, curr) => {
16577 if (predicate(curr)) {
16578 acc[0].push(curr);
16579 } else {
16580 acc[1].push(curr);
16581 }
16582 return acc;
16583 }, [[], []]);
16584 }
16585
16586 const numbers = [1, 2, 3, 4, 5];
16587 const isEven = num => num % 2 === 0;
16588 [Link](partition(numbers, isEven)); // [[2, 4], [1, 3, 5]]
16589 </pre>
16590
16591 <p><strong>319. Create a function that invokes fn with partials appended to the
arguments it receives:</strong></p>
16592 <pre>
16593 function partialRight(fn, ...partials) {
16594 return (...args) => fn(...args, ...partials);
16595 }
16596
16597 const greet = (greeting, name) => `${greeting}, ${name}!`;
16598 const greetGoodMorning = partialRight(greet, 'Good morning');
16599 [Link](greetGoodMorning('John')); // "Good morning, John!"
16600 </pre>
16601
16602 <p><strong>320. Create a function that invokes fn with partials prepended to the
arguments it receives:</strong></p>
16603 <pre>
16604 function partial(fn, ...partials) {
16605 return (...args) => fn(...partials, ...args);
16606 }
16607
16608 const greet = (greeting, name) => `${greeting}, ${name}!`;
16609 const greetGoodMorning = partial(greet, 'Good morning');
16610 [Link](greetGoodMorning('John')); // "Good morning, John!"
16611 </pre>
16612
16613 <p><strong>321. Parse an HTTP Cookie header string and return an object of all cookie
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 281/298
1/31/24, 9:21 AM [Link]
name-value pairs:</strong></p>
16614 <pre>
16615 function parseCookie(cookie) {
16616 return [Link](';').reduce((acc, curr) => {
16617 const [key, value] = [Link]().split('=');
16618 acc[key] = value;
16619 return acc;
16620 }, {});
16621 }
16622
16623 const cookieString = 'name=John; age=30; role=admin';
16624 [Link](parseCookie(cookieString)); // { name: "John", age: "30", role: "admin" }
16625 </pre>
16626
16627 <p><strong>322. Create a function that invokes the provided function with its arguments
transformed:</strong></p>
16628 <pre>
16629 function mapArgs(fn, mapper) {
16630 return (...args) => fn(...[Link](mapper));
16631 }
16632
16633 const add = (a, b) => a + b;
16634 const doubleMapper = x => x * 2;
16635 const addDoubles = mapArgs(add, doubleMapper);
16636 [Link](addDoubles(1, 2)); // 6 (1 * 2 + 2 * 2 = 6)
16637 </pre>
16638
16639 <p><strong>323. Get the nth element from a given array:</strong></p>
16640 <pre>
16641 function getNthElement(arr, n) {
16642 return arr[n];
16643 }
16644
16645 const array = [1, 2, 3, 4, 5];
16646 [Link](getNthElement(array, 2)); // 3
16647 </pre>
16648
16649 <p><strong>324. Convert a NodeList to an array:</strong></p>
16650 <pre>
16651 function nodeListToArray(nodeList) {
16652 return [Link](nodeList);
16653 }
16654
16655 const nodeList = [Link]('p');
16656 const arrayFromNodeList = nodeListToArray(nodeList);
16657 [Link](arrayFromNodeList); // Array of p elements
16658 </pre>
16659
16660 <p><strong>325. Get the index of the function in an array of functions which executed
the fastest:</strong></p>
16661 <pre>
16662 async function fastestFunctionIndex(...functions) {
16663 const results = await [Link]([Link](fn => fn()));
16664 const executionTimes = [Link](result => ([Link] === 'fulfilled') ?
[Link] : Infinity);
16665 return [Link]([Link](...executionTimes));
16666 }
16667
16668 const func1 = async () => {
16669 await new Promise(resolve => setTimeout(resolve, 100));
16670 return 1;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 282/298
1/31/24, 9:21 AM [Link]
16671 };
16672 const func2 = async () => {
16673 await new Promise(resolve => setTimeout(resolve, 50));
16674 return 2;
16675 };
16676 const func3 = async () => {
16677 await new Promise(resolve => setTimeout(resolve, 200));
16678 return 3;
16679 };
16680
16681 fastestFunctionIndex(func1, func2, func3).then(index => {
16682 [Link]('Index of the fastest function:', index);
16683 });
16684 </pre>
16685
16686 <p><strong>326. Get the n minimum elements from the provided array. If n is greater than
or equal to the provided array's
16687 length, then return the original array(sorted in ascending order):</strong></p>
16688 <pre>
16689 function getNMinimumElements(arr, n) {
16690 return [Link](0, [Link](n, 0)).sort((a, b) => a - b);
16691 }
16692
16693 const array = [4, 2, 8, 1, 6];
16694 [Link](getNMinimumElements(array, 3)); // [1, 2, 4]
16695 </pre>
16696
16697 <p><strong>327. Get the minimum value of an array, after mapping each element to a value
using the provided function:</strong></p>
16698 <pre>
16699 function minMappedValue(arr, mapper) {
16700 return [Link](...[Link](mapper));
16701 }
16702
16703 const array = [2, 4, 6, 8, 10];
16704 const mapper = x => x * 2;
16705 [Link](minMappedValue(array, mapper)); // 4
16706 </pre>
16707
16708 <p><strong>328. Create a new object from the combination of two or more objects:<
/strong></p>
16709 <pre>
16710 function mergeObjects(...objects) {
16711 return [Link]({}, ...objects);
16712 }
16713
16714 const obj1 = { a: 1, b: 2 };
16715 const obj2 = { c: 3 };
16716 const obj3 = { d: 4, e: 5 };
16717
16718 [Link](mergeObjects(obj1, obj2, obj3)); // { a: 1, b: 2, c: 3, d: 4, e: 5 }
16719 </pre>
16720
16721 <p><strong>329. Compare two objects to determine if the first one contains equivalent
property values to the second one,
16722 based on a provided function:</strong></p>
16723 <pre>
16724 function compareObjects(obj1, obj2, comparer) {
16725 const keys1 = [Link](obj1);
16726 const keys2 = [Link](obj2);
16727 if ([Link] !== [Link]) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 283/298
1/31/24, 9:21 AM [Link]
16728 return false;
16729 }
16730 return [Link](key => comparer(obj1[key], obj2[key]));
16731 }
16732
16733 const obj1 = { a: 1, b: 2 };
16734 const obj2 = { a: 1, b: 2 };
16735 const comparer = (a, b) => a === b;
16736
16737 [Link](compareObjects(obj1, obj2, comparer)); // true
16738 </pre>
16739
16740 <p><strong>330. Create a new object from the specified object, where all the keys are in
lowercase:</strong></p>
16741 <pre>
16742 function convertKeysToLowerCase(obj) {
16743 return [Link]([Link](obj).map(([key, value]) =>
[[Link](), value]));
16744 }
16745
16746 const obj = { Name: 'John', Age: 30 };
16747 [Link](convertKeysToLowerCase(obj)); // { name: "John", age: 30 }
16748 </pre>
16749
16750 <p><strong>331. Get the last element from a given array:</strong></p>
16751 <pre>
16752 function getLastElement(arr) {
16753 return arr[[Link] - 1];
16754 }
16755
16756 const array = [1, 2, 3, 4, 5];
16757 [Link](getLastElement(array)); // 5
16758 </pre>
16759
16760 <p><strong>332. Join all elements of an array into a string and return this string. Uses
a separator and an end separator:</strong></p>
16761 <pre>
16762 function joinArrayWithSeparators(arr, separator = ',', endSeparator = separator) {
16763 return [Link](separator) + endSeparator;
16764 }
16765
16766 const array = [1, 2, 3, 4, 5];
16767 [Link](joinArrayWithSeparators(array)); // "1,2,3,4,5"
16768 [Link](joinArrayWithSeparators(array, '-', '.')); // "1-2-3-4-5."
16769 </pre>
16770
16771 <p><strong>333. Check if the provided argument is a valid JSON:</strong></p>
16772 <pre>
16773 function isValidJSON(jsonString) {
16774 try {
16775 [Link](jsonString);
16776 return true;
16777 } catch (error) {
16778 return false;
16779 }
16780 }
16781
16782 const jsonString = '{"name": "John", "age": 30}';
16783 [Link](isValidJSON(jsonString)); // true
16784 [Link](isValidJSON('{name: "John", age: 30}')); // false
16785 </pre>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 284/298
1/31/24, 9:21 AM [Link]
16786
16787 <p><strong>334. Check if a given string is uppercase or not:</strong></p>
16788 <pre>
16789 function isUpperCase(str) {
16790 return str === [Link]();
16791 }
16792
16793 [Link](isUpperCase('HELLO')); // true
16794 [Link](isUpperCase('Hello')); // false
16795 </pre>
16796
16797 <p><strong>335. Return true if the specified value is undefined, false otherwise:<
/strong></p>
16798 <pre>
16799 function isUndefined(value) {
16800 return value === undefined;
16801 }
16802
16803 [Link](isUndefined(undefined)); // true
16804 [Link](isUndefined(null)); // false
16805 </pre>
16806
16807 <p><strong>336. Check if the given argument is a symbol:</strong></p>
16808 <pre>
16809 function isSymbol(value) {
16810 return typeof value === 'symbol';
16811 }
16812
16813 [Link](isSymbol(Symbol())); // true
16814 [Link](isSymbol('abc')); // false
16815 </pre>
16816
16817 <p><strong>337. Check if the given argument is a string:</strong></p>
16818 <pre>
16819 function isString(value) {
16820 return typeof value === 'string';
16821 }
16822
16823 [Link](isString('Hello')); // true
16824 [Link](isString(123)); // false
16825 </pre>
16826
16827 <p><strong>338. Return 1 if the array is sorted in ascending order, -1 if it is sorted
in descending order, or 0 if it is not sorted:</strong></p>
16828 <pre>
16829 function checkArraySorting(arr) {
16830 const ascending = [Link]([Link]().sort((a, b) => a - b)) ===
[Link](arr);
16831 const descending = [Link]([Link]().sort((a, b) => b - a)) ===
[Link](arr);
16832 if (ascending) return 1;
16833 if (descending) return -1;
16834 return 0;
16835 }
16836
16837 [Link](checkArraySorting([1, 2, 3, 4])); // 1
16838 [Link](checkArraySorting([4, 3, 2, 1])); // -1
16839 [Link](checkArraySorting([1, 3, 2, 4])); // 0
16840 </pre>
16841
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 285/298
1/31/24, 9:21 AM [Link]
16842 <p><strong>339. Return true if an object looks like a Promise, false otherwise:</strong>
</p>
16843 <pre>
16844 function isPromiseLike(obj) {
16845 return obj !== null && (typeof obj === 'object' || typeof obj === 'function') &&
typeof [Link] === 'function';
16846 }
16847
16848 [Link](isPromiseLike([Link]())); // true
16849 [Link](isPromiseLike({ then: () => {} })); // true
16850 [Link](isPromiseLike({})); // false
16851 </pre>
16852
16853 <p><strong>340. Get a boolean determining if the passed value is primitive or not:<
/strong></p>
16854 <pre>
16855 function isPrimitive(value) {
16856 return Object(value) !== value;
16857 }
16858
16859 [Link](isPrimitive(123)); // true
16860 [Link](isPrimitive('Hello')); // true
16861 [Link](isPrimitive([1, 2, 3])); // false
16862 [Link](isPrimitive({ key: 'value' })); // false
16863 </pre>
16864
16865 <p><strong>341. Check if the provided integer is a prime number or not:</strong></p>
16866 <pre>
16867 function isPrime(num) {
16868 if (num <= 1) return false;
16869 for (let i = 2; i <= [Link](num); i++) {
16870 if (num % i === 0) return false;
16871 }
16872 return true;
16873 }
16874
16875 [Link](isPrime(7)); // true
16876 [Link](isPrime(10)); // false
16877 </pre>
16878
16879 <p><strong>342. Check if the provided value is an object created by the Object
constructor:</strong></p>
16880 <pre>
16881 function isObjectByConstructor(value) {
16882 return value !== null && typeof value === 'object' && [Link] === Object;
16883 }
16884
16885 [Link](isObjectByConstructor({})); // true
16886 [Link](isObjectByConstructor(new Object())); // true
16887 [Link](isObjectByConstructor([])); // false
16888 </pre>
16889
16890 <p><strong>343. Check if a value is object-like:</strong></p>
16891 <pre>
16892 function isObjectLike(value) {
16893 return value !== null && typeof value === 'object';
16894 }
16895
16896 [Link](isObjectLike({})); // true
16897 [Link](isObjectLike(null)); // false
16898 </pre>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 286/298
1/31/24, 9:21 AM [Link]
16899
16900 <p><strong>344. Get a boolean determining if the passed value is an object or not:<
/strong></p>
16901 <pre>
16902 function isObject(value) {
16903 return value !== null && typeof value === 'object';
16904 }
16905
16906 [Link](isObject({})); // true
16907 [Link](isObject(null)); // false
16908 </pre>
16909
16910 <p><strong>345. Check if a given argument is a number:</strong></p>
16911 <pre>
16912 function isNumber(value) {
16913 return typeof value === 'number' && !isNaN(value);
16914 }
16915
16916 [Link](isNumber(123)); // true
16917 [Link](isNumber('abc')); // false
16918 </pre>
16919
16920 <p><strong>346. Return true if the specified value is null, false otherwise:</strong><
/p>
16921 <pre>
16922 function isNull(value) {
16923 return value === null;
16924 }
16925
16926 [Link](isNull(null)); // true
16927 [Link](isNull(123)); // false
16928 </pre>
16929
16930 <p><strong>347. Check if a string is lowercase or not:</strong></p>
16931 <pre>
16932 function isLowerCase(str) {
16933 return str === [Link]();
16934 }
16935
16936 [Link](isLowerCase('hello')); // true
16937 [Link](isLowerCase('Hello')); // false
16938 </pre>
16939
16940 <p><strong>348. Check if the given argument is a function:</strong></p>
16941 <pre>
16942 function isFunction(value) {
16943 return typeof value === 'function';
16944 }
16945
16946 [Link](isFunction(() => {})); // true
16947 [Link](isFunction('abc')); // false
16948 </pre>
16949
16950 <p><strong>349. Return true if the given number is even, false otherwise:</strong></p>
16951 <pre>
16952 function isEven(num) {
16953 return num % 2 === 0;
16954 }
16955
16956 [Link](isEven(4)); // true
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 287/298
1/31/24, 9:21 AM [Link]
16957 [Link](isEven(7)); // false
16958 </pre>
16959
16960 <p><strong>350. Return true if a value is an empty object, collection, map, set, or has
no enumerable properties:</strong></p>
16961 <pre>
16962 function isEmpty(value) {
16963 return value == null || (typeof value === 'object' && [Link](value).length ===
0);
16964 }
16965
16966 [Link](isEmpty({})); // true
16967 [Link](isEmpty([])); // true
16968 [Link](isEmpty('')); // true
16969 [Link](isEmpty(null)); // true
16970 [Link](isEmpty(123)); // false
16971 </pre>
16972
16973 <p><strong>351. Check if the first numeric argument is divisible by the second one:<
/strong></p>
16974 <pre>
16975 function isDivisible(num, divisor) {
16976 return num % divisor === 0;
16977 }
16978
16979 [Link](isDivisible(10, 2)); // true
16980 [Link](isDivisible(10, 3)); // false
16981 </pre>
16982
16983 <p><strong>352. Check if a given number is even or not:</strong></p>
16984 <pre>
16985 function isEven(num) {
16986 return num % 2 === 0;
16987 }
16988
16989 [Link](isEven(4)); // true
16990 [Link](isEven(7)); // false
16991 </pre>
16992
16993 <p><strong>353. Determine if the current runtime environment is a browser:</strong></p>
16994 <pre>
16995 function isBrowser() {
16996 return typeof window !== 'undefined' && typeof document !== 'undefined';
16997 }
16998
16999 [Link](isBrowser()); // true (in a browser)
17000 [Link](isBrowser()); // false (in [Link])
17001 </pre>
17002
17003 <p><strong>354. Check if the given argument is a native boolean element:</strong></p>
17004 <pre>
17005 function isBoolean(value) {
17006 return typeof value === 'boolean';
17007 }
17008
17009 [Link](isBoolean(true)); // true
17010 [Link](isBoolean('true')); // false
17011 </pre>
17012
17013 <p><strong>355. Check if the provided argument is array-like (i.e., is iterable):<
/strong></p>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 288/298
1/31/24, 9:21 AM [Link]
17014 <pre>
17015 function isArrayLike(value) {
17016 return typeof value !== 'function' && value !== null && typeof value !== 'undefined'
&& typeof [Link] === 'number';
17017 }
17018
17019 [Link](isArrayLike([])); // true
17020 [Link](isArrayLike({ length: 5 })); // true
17021 [Link](isArrayLike('hello')); // true
17022 [Link](isArrayLike(() => {})); // false
17023 </pre>
17024
17025 <p><strong>356. Check if a given string is an anagram of another string (case-
insensitive, ignores spaces, punctuation and special characters):</strong></p>
17026 <pre>
17027 function isAnagram(str1, str2) {
17028 const formatString = str => [Link](/[^\w]/g, '').toLowerCase();
17029 return formatString(str1) === formatString(str2);
17030 }
17031
17032 [Link](isAnagram('listen', 'silent')); // true
17033 [Link](isAnagram('hello', 'world')); // false
17034 </pre>
17035
17036 <p><strong>357. Return true if the given string is an absolute URL, false otherwise:<
/strong></p>
17037 <pre>
17038 function isAbsoluteURL(url) {
17039 const pattern = /^(?:\w+:)\/\//;
17040 return [Link](url);
17041 }
17042
17043 [Link](isAbsoluteURL('[Link] // true
17044 [Link](isAbsoluteURL('/path/to/resource')); // false
17045 </pre>
17046
17047 <p><strong>358. Check if the provided value is of the specified type:</strong></p>
17048 <pre>
17049 function isType(value, type) {
17050 return typeof value === type;
17051 }
17052
17053 [Link](isType('hello', 'string')); // true
17054 [Link](isType(123, 'number')); // true
17055 [Link](isType(true, 'boolean')); // true
17056 </pre>
17057
17058 <p><strong>359. Get a list of elements that exist in both arrays, using a provided
comparator function:</strong></p>
17059 <pre>
17060 function intersectionWith(arr1, arr2, comparator) {
17061 return [Link](a => [Link](b => comparator(a, b)));
17062 }
17063
17064 [Link](intersectionWith([1, 2, 3], [2, 3, 4], (a, b) => a === b)); // [2, 3]
17065 </pre>
17066
17067 <p><strong>360. Get a list of elements that exist in both arrays, after applying the
provided function to each array element of both:</strong></p>
17068 <pre>
17069 function intersectionBy(arr1, arr2, iteratee) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 289/298
1/31/24, 9:21 AM [Link]
17070 const set = new Set([Link](iteratee));
17071 return [Link](item => [Link](iteratee(item)));
17072 }
17073
17074 [Link](intersectionBy([1.1, 2.2, 3.3], [3.4, 2.5, 1.6], [Link])); // [1.1, 2.2,
3.3]
17075 </pre>
17076
17077 <p><strong>361. Get a list of elements that exist in both arrays:</strong></p>
17078 <pre>
17079 function intersection(arr1, arr2) {
17080 return [Link](value => [Link](value));
17081 }
17082
17083 [Link](intersection([1, 2, 3], [2, 3, 4])); // [2, 3]
17084 </pre>
17085
17086 <p><strong>362. Create an n-dimensional array with a given value:</strong></p>
17087 <pre>
17088 function createNDArray(dimensions, value) {
17089 if ([Link] === 0) return value;
17090 const result = [];
17091 for (let i = 0; i < dimensions[0]; i++) {
17092 [Link](createNDArray([Link](1), value));
17093 }
17094 return result;
17095 }
17096
17097 [Link](createNDArray([3, 3], 0)); // [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
17098 </pre>
17099
17100 <p><strong>363. Initialize and fill an array with the specified values:</strong></p>
17101 <pre>
17102 function initializeArray(length, value) {
17103 return [Link]({ length }, () => value);
17104 }
17105
17106 [Link](initializeArray(5, 1)); // [1, 1, 1, 1, 1]
17107 </pre>
17108
17109 <p><strong>364. Initialize an array containing numbers in the specified range (in
reverse), where start and end are inclusive with their common difference step:</strong><
/p>
17110 <pre>
17111 function initializeArrayRange(start, end, step = 1) {
17112 return [Link]({ length: [Link]((end - start) / step) + 1 }, (_, index) =>
end - index * step);
17113 }
17114
17115 [Link](initializeArrayRange(5, 1)); // [5, 4, 3, 2, 1]
17116 </pre>
17117
17118 <p><strong>365. Get all elements of an array except the last one:</strong></p>
17119 <pre>
17120 function getAllExceptLast(arr) {
17121 return [Link](0, -1);
17122 }
17123
17124 [Link](getAllExceptLast([1, 2, 3, 4])); // [1, 2, 3]
17125 </pre>
17126
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 290/298
1/31/24, 9:21 AM [Link]
17127 <p><strong>366. Get all indices of val in an array. If val never occurs, returns []:<
/strong></p>
17128 <pre>
17129 function getAllIndices(arr, val) {
17130 return [Link]((acc, item, index) => (item === val ? [...acc, index] : acc), []);
17131 }
17132
17133 [Link](getAllIndices([1, 2, 3, 4, 2, 5], 2)); // [1, 4]
17134 </pre>
17135
17136 <p><strong>367. Check if the given number falls within the given range:</strong></p>
17137 <pre>
17138 function isInRange(num, range) {
17139 const [min, max] = [Link]((a, b) => a - b);
17140 return num >= min && num <= max;
17141 }
17142
17143 [Link](isInRange(5, [1, 10])); // true
17144 [Link](isInRange(15, [1, 10])); // false
17145 </pre>
17146
17147 <p><strong>368. Get the number of times a function is executed per second. "hz" is the
unit for hertz, the unit of frequency defined as one cycle per second:</strong></p>
17148 <pre>
17149 function hz(fn) {
17150 const start = [Link]();
17151 let count = 0;
17152 while ([Link]() - start < 1000) {
17153 fn();
17154 count++;
17155 }
17156 return count;
17157 }
17158
17159 [Link](hz(() => [Link]('Hello World!')));
17160 </pre>
17161
17162 <p><strong>369. Calculate the Hamming distance between two values:</strong></p>
17163 <pre>
17164 function hammingDistance(str1, str2) {
17165 let distance = 0;
17166 for (let i = 0; i < [Link]; i++) {
17167 if (str1[i] !== str2[i]) distance++;
17168 }
17169 return distance;
17170 }
17171
17172 [Link](hammingDistance('karolin', 'kathrin')); // 3
17173 </pre>
17174
17175
17176 <p><strong>370. Get the native type of a value:</strong></p>
17177 <pre>
17178 function getNativeType(value) {
17179 return value === null ? 'null' : value === undefined ? 'undefined' :
[Link]();
17180 }
17181
17182 [Link](getNativeType('hello')); // string
17183 [Link](getNativeType(123)); // number
17184 [Link](getNativeType(null)); // null
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 291/298
1/31/24, 9:21 AM [Link]
17185 </pre>
17186
17187 <p><strong>371. Get a string of the form HH:MM:SS from a Date object:</strong></p>
17188 <pre>
17189 function formatTime(date) {
17190 const hours = String([Link]()).padStart(2, '0');
17191 const minutes = String([Link]()).padStart(2, '0');
17192 const seconds = String([Link]()).padStart(2, '0');
17193 return `${hours}:${minutes}:${seconds}`;
17194 }
17195
17196 [Link](formatTime(new Date())); // "[Link]"
17197 </pre>
17198
17199 <p><strong>372. Initialize an array containing numbers in the specified range:</strong><
/p>
17200 <pre>
17201 function initializeArrayRange(start, end, step) {
17202 if (step === 1) throw new Error('Step cannot be 1.');
17203 const arr = [];
17204 for (let i = start; i <= end; i *= step) {
17205 [Link](i);
17206 }
17207 return arr;
17208 }
17209
17210 [Link](initializeArrayRange(1, 100, 2)); // [1, 2, 4, 8, 16, 32, 64]
17211 </pre>
17212
17213 <p><strong>373. Calculate the greatest common divisor between two or more numbers:<
/strong></p>
17214 <pre>
17215 function gcd(...numbers) {
17216 const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
17217 return [Link]((a, b) => _gcd(a, b));
17218 }
17219
17220 [Link](gcd(8, 12, 16)); // 4
17221 </pre>
17222
17223 <p><strong>374. Remove HTML/XML tags from string:</strong></p>
17224 <pre>
17225 function removeTags(str) {
17226 return [Link](/<[^>]*>/g, '');
17227 }
17228
17229 [Link](removeTags('<p>Hello <b>world</b>!</p>')); // "Hello world!"
17230 </pre>
17231
17232 <p><strong>375. Get the standard deviation of an array of numbers:</strong></p>
17233 <pre>
17234 function standardDeviation(arr) {
17235 const mean = [Link]((acc, val) => acc + val, 0) / [Link];
17236 const variance = [Link]((acc, val) => acc + (val - mean) ** 2, 0) / [Link];
17237 return [Link](variance);
17238 }
17239
17240 [Link](standardDeviation([1, 2, 3, 4, 5])); // 1.4142135623730951
17241 </pre>
17242
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 292/298
1/31/24, 9:21 AM [Link]
17243 <p><strong>376. Get n random elements at unique keys from array up to the size of array:
</strong></p>
17244 <pre>
17245 function getRandomElements(arr, n) {
17246 return arr
17247 .map((value) => ({ value, sort: [Link]() }))
17248 .sort((a, b) => [Link] - [Link])
17249 .slice(0, n)
17250 .map((item) => [Link]);
17251 }
17252
17253 [Link](getRandomElements([1, 2, 3, 4, 5], 2)); // [2, 3] (example)
17254 </pre>
17255
17256 <p><strong>377. Remove elements from an array for which the given function returns
false:</strong></p>
17257 <pre>
17258 function filterFalsy(arr, fn) {
17259 return [Link]((item) => fn(item));
17260 }
17261
17262 [Link](filterFalsy([0, 1, '', 'hello', null, true], Boolean)); // [1, 'hello',
true]
17263 </pre>
17264
17265 <p><strong>378. Log the name of a function:</strong></p>
17266 <pre>
17267 function logFunctionName(fn) {
17268 [Link]([Link]);
17269 }
17270
17271 logFunctionName(function myFunction() {}); // "myFunction"
17272 </pre>
17273
17274 <p><strong>379. Convert a string from camelcase:</strong></p>
17275 <pre>
17276 function fromCamelCase(str) {
17277 return [Link](/([A-Z])/g, ' $1').toLowerCase();
17278 }
17279
17280 [Link](fromCamelCase('helloWorld')); // "hello world"
17281 </pre>
17282
17283 <p><strong>380. Get the human-readable format of the given number of milliseconds:<
/strong></p>
17284 <pre>
17285 function formatMilliseconds(ms) {
17286 const seconds = [Link](ms / 1000) % 60;
17287 const minutes = [Link](ms / (1000 * 60)) % 60;
17288 const hours = [Link](ms / (1000 * 60 * 60)) % 24;
17289 const days = [Link](ms / (1000 * 60 * 60 * 24));
17290 return `${days}d ${hours}h ${minutes}m ${seconds}s`;
17291 }
17292
17293 [Link](formatMilliseconds(1000000000)); // "11d 13h 46m 40s"
17294 </pre>
17295
17296 <p><strong>381. Iterate over all own properties of an object in reverse, running a
callback for each one:</strong></p>
17297 <pre>
17298 function iterateReverse(obj, callback) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 293/298
1/31/24, 9:21 AM [Link]
17299 const keys = [Link](obj).reverse();
17300 [Link]((key) => callback(key, obj[key]));
17301 }
17302
17303 const obj = { a: 1, b: 2, c: 3 };
17304 iterateReverse(obj, (key, value) => [Link](`${key}: ${value}`));
17305 </pre>
17306
17307 <p><strong>382. Take a function as an argument, then make the first argument the last:<
/strong></p>
17308 <pre>
17309 function switchArguments(fn) {
17310 return function(...args) {
17311 return fn(...[Link](1), args[0]);
17312 };
17313 }
17314
17315 const subtract = (a, b) => a - b;
17316 const subtractWithSwitchedArgs = switchArguments(subtract);
17317 [Link](subtractWithSwitchedArgs(5, 3)); // -2
17318 </pre>
17319
17320 <p><strong>383. Flatten an object with the paths for keys:</strong></p>
17321 <pre>
17322 function flattenObject(obj, path = '') {
17323 return [Link](obj).reduce((acc, key) => {
17324 const fullPath = path ? `${path}.${key}` : key;
17325 if (typeof obj[key] === 'object' && obj[key] !== null) {
17326 [Link](acc, flattenObject(obj[key], fullPath));
17327 } else {
17328 acc[fullPath] = obj[key];
17329 }
17330 return acc;
17331 }, {});
17332 }
17333
17334 const nestedObj = {
17335 a: {
17336 b: {
17337 c: 1,
17338 d: 2
17339 },
17340 e: 3
17341 },
17342 f: 4
17343 };
17344
17345 [Link](flattenObject(nestedObj));
17346 </pre>
17347
17348 <p><strong>384. Flatten a given array up to the specified depth:</strong></p>
17349 <pre>
17350 function flattenArray(arr, depth = 1) {
17351 return [Link]((acc, item) => {
17352 if ([Link](item) && depth > 0) {
17353 [Link](...flattenArray(item, depth - 1));
17354 } else {
17355 [Link](item);
17356 }
17357 return acc;
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 294/298
1/31/24, 9:21 AM [Link]
17358 }, []);
17359 }
17360
17361 [Link](flattenArray([1, [2, [3, [4]], 5]], 2)); // [1, 2, 3, [4], 5]
17362 </pre>
17363
17364 <p><strong>385. Get the last key that satisfies the provided testing function, otherwise
undefined is returned:</strong></p>
17365 <pre>
17366 function findLastKey(obj, predicate) {
17367 const keys = [Link](obj).reverse();
17368 return [Link]((key) => predicate(obj[key]));
17369 }
17370
17371 const obj = { a: 1, b: 2, c: 3, d: 4 };
17372 [Link](findLastKey(obj, (value) => value % 2 === 0)); // "d"
17373 </pre>
17374
17375 <p><strong>386. Get the first key that satisfies the provided testing function.
Otherwise, return undefined:</strong></p>
17376 <pre>
17377 function findFirstKey(obj, predicate) {
17378 const keys = [Link](obj);
17379 return [Link]((key) => predicate(obj[key]));
17380 }
17381
17382 const obj = { a: 1, b: 2, c: 3, d: 4 };
17383 [Link](findFirstKey(obj, (value) => value % 2 === 0)); // "b"
17384 </pre>
17385
17386 <p><strong>387. Generate an array containing the Fibonacci sequence, up until the nth
term:</strong></p>
17387 <pre>
17388 function fibonacci(n) {
17389 const sequence = [0, 1];
17390 for (let i = 2; i < n; i++) {
17391 [Link](sequence[i - 1] + sequence[i - 2]);
17392 }
17393 return [Link](0, n);
17394 }
17395
17396 [Link](fibonacci(10)); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
17397 </pre>
17398
17399 <p><strong>388. Calculate the factorial of a number:</strong></p>
17400 <pre>
17401 function factorial(n) {
17402 if (n === 0 || n === 1) return 1;
17403 let result = 1;
17404 for (let i = 2; i <= n; i++) {
17405 result *= i;
17406 }
17407 return result;
17408 }
17409
17410 [Link](factorial(5)); // 120
17411 </pre>
17412
17413 <p><strong>389. Escape a string to use in a regular expression:</strong></p>
17414 <pre>
17415 function escapeRegExp(str) {
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 295/298
1/31/24, 9:21 AM [Link]
17416 return [Link](/[.*+?^${}()|[\]\\]/g, '\\$&');
17417 }
17418
17419 const input = 'Escaping [special] characters in (regex)';
17420 const regex = new RegExp(escapeRegExp('['), 'g');
17421 [Link]([Link](regex, '\\[')); // "Escaping \[special\] characters in (regex)
"
17422 </pre>
17423
17424 <p><strong>390. Check if the parent element contains the child element:</strong></p>
17425 <pre>
17426 function isChildOf(parent, child) {
17427 return [Link](child);
17428 }
17429
17430 const parent = [Link]('parent');
17431 const child = [Link]('child');
17432 [Link](isChildOf(parent, child)); // true or false
17433 </pre>
17434
17435 <p><strong>391. Remove elements in an array until the passed function returns true:<
/strong></p>
17436 <pre>
17437 function removeUntil(arr, fn) {
17438 while (!fn(arr[0])) {
17439 [Link]();
17440 }
17441 return arr;
17442 }
17443
17444 const arr = [1, 2, 3, 4, 5];
17445 [Link](removeUntil(arr, (x) => x > 2)); // [3, 4, 5]
17446 </pre>
17447
17448 <p><strong>392. Remove elements from the end of an array until the passed function
returns true:</strong></p>
17449 <pre>
17450 function removeFromEndUntil(arr, fn) {
17451 while (!fn(arr[[Link] - 1])) {
17452 [Link]();
17453 }
17454 return arr;
17455 }
17456
17457 const arr = [1, 2, 3, 4, 5];
17458 [Link](removeFromEndUntil(arr, (x) => x > 3)); // [1, 2, 3]
17459 </pre>
17460
17461 <p><strong>393. Get the distance between two given points:</strong></p>
17462 <pre>
17463 function distanceBetweenPoints(point1, point2) {
17464 const [x1, y1] = point1;
17465 const [x2, y2] = point2;
17466 return [Link]((x2 - x1) ** 2 + (y2 - y1) ** 2);
17467 }
17468
17469 [Link](distanceBetweenPoints([1, 2], [4, 6])); // 5
17470 </pre>
17471
17472 <p><strong>394. Get the difference between two given arrays:</strong></p>
17473 <pre>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 296/298
1/31/24, 9:21 AM [Link]
17474 function arrayDifference(arr1, arr2) {
17475 const set = new Set(arr2);
17476 return [Link]((item) => );
17477 }
17478
17479 [Link](arrayDifference([1, 2, 3], [2, 3, 4])); // [1]
17480 </pre>
17481
17482 <p><strong>395. Invoke the provided function after wait milliseconds:</strong></p>
17483 <pre>
17484 function delay(fn, wait, ...args) {
17485 return setTimeout(fn, wait, ...args);
17486 }
17487
17488 delay([Link], 1000, 'Delayed message');
17489 </pre>
17490
17491 <p><strong>396. Convert a given angle from degrees to radians:</strong></p>
17492 <pre>
17493 function degreesToRadians(degrees) {
17494 return degrees * ([Link] / 180);
17495 }
17496
17497 [Link](degreesToRadians(90)); // 1.5707963267948966
17498 </pre>
17499
17500 <p><strong>397. Assign default values for all properties in an object that are
undefined:</strong></p>
17501 <pre>
17502 function assignDefaults(obj, defaults) {
17503 for (const key in defaults) {
17504 if ([Link](defaults, key) && obj[key] ===
undefined) {
17505 obj[key] = defaults[key];
17506 }
17507 }
17508 return obj;
17509 }
17510
17511 const obj = { a: 1, b: undefined };
17512 [Link](assignDefaults(obj, { a: 0, b: 2, c: 3 })); // { a: 1, b: 2, c: 3 }
17513 </pre>
17514
17515 <p><strong>398. Deep flatten an array:</strong></p>
17516 <pre>
17517 function deepFlatten(arr) {
17518 return [Link]((acc, val) => [Link](val) ? [Link](deepFlatten(val)) :
[Link](val), []);
17519 }
17520
17521 [Link](deepFlatten([1, [2, [3, [4]], 5]])); // [1, 2, 3, 4, 5]
17522 </pre>
17523
17524 <p><strong>399. Get the current URL:</strong></p>
17525 <pre>
17526 const currentURL = [Link];
17527 [Link](currentURL);
17528 </pre>
17529
17530 <p><strong>400. Create an element from a string (without appending it to the document):<
/strong></p>
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 297/298
1/31/24, 9:21 AM [Link]
17531 <pre>
17532 function createElementFromString(str) {
17533 const template = [Link]('template');
17534 [Link] = [Link]();
17535 return [Link];
17536 }
17537
17538 const elementString = '<div>Hello World</div>';
17539 const element = createElementFromString(elementString);
17540 [Link](element); // <div>Hello World</div>
17541 </pre>
17542
17543
17544
17545 </body>
17546 </html>
17547
localhost:62992/36c130dd-866f-439d-acf5-15edac5aafb3/ 298/298