0% found this document useful (0 votes)
2 views1 page

Coding Problems Solutions

The document contains a series of JavaScript code snippets demonstrating basic programming tasks. These include sorting an array, finding the middle node of an array, swapping two variables without a third variable, creating a throttle function, and calculating the square of a number. Each code snippet is accompanied by example usage and expected output.

Uploaded by

bc210415570
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views1 page

Coding Problems Solutions

The document contains a series of JavaScript code snippets demonstrating basic programming tasks. These include sorting an array, finding the middle node of an array, swapping two variables without a third variable, creating a throttle function, and calculating the square of a number. Each code snippet is accompanied by example usage and expected output.

Uploaded by

bc210415570
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1. Write a code to sort an array without using any built-in function.

function sortArray(arr) { for (let i = 0; i < [Link]; i++) { for (let j = i + 1; j <
[Link]; j++) { if (arr[i] > arr[j]) { let temp = arr[i]; arr[i] = arr[j]; arr[j] =
temp; } } } return arr; } [Link](sortArray([5, 2, 9, 1, 3])); // [1, 2, 3, 5, 9]

2. Write a code for finding the middle node of an array.


function findMiddle(arr) { let mid = [Link]([Link] / 2); if ([Link] % 2 ===
0) { return [arr[mid - 1], arr[mid]]; } else { return arr[mid]; } }
[Link](findMiddle([1, 2, 3, 4, 5])); // 3 [Link](findMiddle([1, 2, 3, 4, 5,
6])); // [3, 4]

3. Swap a = 10, b = 20 without using a third variable.


let a = 10, b = 20; a = a + b; b = a - b; a = a - b; [Link](a, b); // 20, 10

4. Write a throttle function.


function throttle(fn, delay) { let lastCall = 0; return function(...args) { let now =
new Date().getTime(); if (now - lastCall >= delay) { lastCall = now; fn(...args); } }; }
// Example: const log = () => [Link]("Throttled!"); const throttledLog =
throttle(log, 2000); [Link]("scroll", throttledLog);

5. Write a code where we give input n and see output n * n.


function square(n) { return n * n; } [Link](square(5)); // 25

You might also like