├── Practice Problems ├── 21.Power.js ├── 29.String4.js ├── 24.Map.js ├── 01.Sum.js ├── 30.Class.js ├── 18.AscendingArray.js ├── 16.duplicates.js ├── 04.Factorial.js ├── 23.Array5.js ├── 15.factorial2.js ├── 11.repetitive function.js ├── 27.Vowels.js ├── 14.SumArray.js ├── 28.String3.js ├── 02.Reverse.js ├── 22.String2.js ├── 26.Array6.js ├── 17.string.js ├── 09.Palindrome.js ├── 03.Max.js ├── 06.Array.js ├── 10.FibonacciSequence.js ├── 07.ChangeString.js ├── 08.NestedArray.js ├── 20.Array4.js ├── 13.Array2.js ├── 19.Array3.js ├── 12.flattenArray.js ├── 05.Prime.js └── 25.Anagrams.js ├── Solutions ├── Problem-09.js ├── Problem-05.js ├── Problem-12.js ├── Problem-01.js ├── Problem-02.js ├── Problem-17.js ├── Problem-18.js ├── Problem-06.js ├── Problem-16.js ├── Problem-11.js ├── Problem-08.js ├── Problem-23.js ├── Problem-10.js ├── Problem-15.js ├── Problem-13.js ├── Problem-07.js ├── Problem-21.js ├── Problem-14.js ├── Problem-25.js ├── Problem-03.js ├── Problem-04.js ├── Problem-27.js ├── Problem-29.js ├── Problem-26.js ├── Problem-19.js ├── Problem-22.js ├── Problem-24.js ├── Problem-20.js ├── Problem-30.js └── Problem-28.js └── README.md /Practice Problems/21.Power.js: -------------------------------------------------------------------------------- 1 | // 21.Calculate the Power of a Number in JavaScript : 2 | 3 | 4 | function power(base, exponent) 5 | { 6 | return base ** exponent; 7 | } 8 | 9 | console.log(power(3, 4)); -------------------------------------------------------------------------------- /Practice Problems/29.String4.js: -------------------------------------------------------------------------------- 1 | // 29. Convert a string to an array of words in JavaScript : 2 | 3 | 4 | let sentence = "Shubham Bhoite"; 5 | let wordsArray = sentence.split(" "); 6 | console.log(wordsArray); 7 | -------------------------------------------------------------------------------- /Practice Problems/24.Map.js: -------------------------------------------------------------------------------- 1 | // 24. Use the map function on an array in JavaScript : 2 | 3 | 4 | let numbers = [5, 6, 7]; 5 | let ans = numbers.map(function (num) { 6 | return num * 2; 7 | }); 8 | console.log(ans); 9 | -------------------------------------------------------------------------------- /Solutions/Problem-09.js: -------------------------------------------------------------------------------- 1 | /* 9.Return Length of Arguments Passed : 2 | Write a function argumentsLength that returns the count of arguments passed to it. 3 | */ 4 | 5 | 6 | var argumentsLength = function(...args) { 7 | return args.length 8 | 9 | }; -------------------------------------------------------------------------------- /Practice Problems/01.Sum.js: -------------------------------------------------------------------------------- 1 | // 1. Write a JavaScript function that calculates the sum of two numbers : 2 | 3 | 4 | function sum(a, b) { 5 | return a + b; 6 | } 7 | const num1 = 10; 8 | const num2 = 20; 9 | const result = sum(num1, num2); 10 | console.log("The sum of", num1, "and", num2, "is", result); 11 | -------------------------------------------------------------------------------- /Practice Problems/30.Class.js: -------------------------------------------------------------------------------- 1 | // 30. Write a Program to create a simple class in JavaScript : 2 | 3 | 4 | 5 | class Animals { 6 | constructor(name) { 7 | this.name = name; 8 | } 9 | speak() { 10 | console.log(`${this.name} makes a noise`); 11 | } 12 | } 13 | let dog = new Animals("Dog"); 14 | dog.speak(); 15 | -------------------------------------------------------------------------------- /Practice Problems/18.AscendingArray.js: -------------------------------------------------------------------------------- 1 | // 18. Write a function that categorizes an array of numbers in ascending order : 2 | 3 | 4 | function sortNumbersAscending(arr) { 5 | return arr.sort((a, b) => a - b); 6 | } 7 | const numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]; 8 | const sortedNumbers = sortNumbersAscending(numbers); 9 | console.log(sortedNumbers); 10 | 11 | -------------------------------------------------------------------------------- /Solutions/Problem-05.js: -------------------------------------------------------------------------------- 1 | /* 5.Apply Transform Over Each Element in Array : 2 | 3 | Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element. 4 | The returned array should be created such that returnedArray[i] = fn(arr[i], i). 5 | */ 6 | 7 | var map = function(arr, fn) { 8 | return arr.map(fn); 9 | }; -------------------------------------------------------------------------------- /Solutions/Problem-12.js: -------------------------------------------------------------------------------- 1 | /* 12.Sleep : 2 | 3 | Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value. 4 | */ 5 | 6 | 7 | async function sleep(millis) { 8 | function callback(res, rej){ 9 | setTimeout(res, millis); 10 | } 11 | return new Promise(callback); 12 | 13 | 14 | } -------------------------------------------------------------------------------- /Practice Problems/16.duplicates.js: -------------------------------------------------------------------------------- 1 | // 16. Write a function that removes the duplicates from an array : 2 | 3 | 4 | function removeDuplicates(arr) { 5 | const uniqueSet = new Set(arr); 6 | return Array.from(uniqueSet); 7 | } 8 | const numbers = [1, 2, 3, 2, 4, 5, 1, 4]; 9 | const uniqueNumbers = removeDuplicates(numbers); 10 | console.log("Unique numbers:", uniqueNumbers); 11 | 12 | -------------------------------------------------------------------------------- /Practice Problems/04.Factorial.js: -------------------------------------------------------------------------------- 1 | // 4. Write a JavaScript program that calculates the factorial of a number : 2 | 3 | function factorial(n) { 4 | if (n === 0 || n === 1) { 5 | return 1; 6 | } else { 7 | return n * factorial(n - 1); 8 | } 9 | } 10 | const number = 5; 11 | const result = factorial(number); 12 | console.log("Factorial of", number, "is", result); 13 | 14 | -------------------------------------------------------------------------------- /Practice Problems/23.Array5.js: -------------------------------------------------------------------------------- 1 | // 23.Remove falsy Values from an array in JavaScript: 2 | 3 | 4 | function removeFalsyValues(arr) { 5 | const answer = []; 6 | for (let i = 0; i < arr.length; i++) { 7 | if (arr[i]) { 8 | answer[answer.length] = arr[i]; 9 | } 10 | } 11 | return answer; 12 | } 13 | 14 | console.log(removeFalsyValues([0, 5, false, 6, '', 7])); -------------------------------------------------------------------------------- /Solutions/Problem-01.js: -------------------------------------------------------------------------------- 1 | /* 1.Create Hello World Function: 2 | Write a function createHelloWorld. It should return a new function that always returns "Hello World". 3 | */ 4 | 5 | 6 | var createHelloWorld = function() { 7 | return function() { 8 | return "Hello World"; 9 | } 10 | }; 11 | const hello = createHelloWorld(); // hello is now a function 12 | console.log(hello()); -------------------------------------------------------------------------------- /Practice Problems/15.factorial2.js: -------------------------------------------------------------------------------- 1 | // 15. Write a function that finds the factorial of a given number : 2 | 3 | 4 | function factorial(n) { 5 | if (n === 0 || n === 1) { 6 | return 1; 7 | } else { 8 | return n * factorial(n - 1); 9 | } 10 | } 11 | const number = 9; 12 | const result = factorial(number); 13 | console.log("Factorial of " + number + " is " + result); 14 | 15 | -------------------------------------------------------------------------------- /Practice Problems/11.repetitive function.js: -------------------------------------------------------------------------------- 1 | // 11. Write a repetitive function to find a factorial of a given number : 2 | 3 | 4 | function factorial(n) { 5 | if (n === 0 || n === 1) { 6 | return 1; 7 | } else { 8 | return n * factorial(n - 1); 9 | } 10 | } 11 | const number = 5; 12 | const result = factorial(number); 13 | console.log("Factorial of " + number + " is " + result); 14 | 15 | -------------------------------------------------------------------------------- /Practice Problems/27.Vowels.js: -------------------------------------------------------------------------------- 1 | // 27. Count Vowels in a String in JavaScript : 2 | 3 | 4 | function countVowels(str) { 5 | let count = 0; 6 | 7 | const vowels = 'aeiouAEIOU'; 8 | for (let i = 0; i < str.length; i++) { 9 | if (vowels.includes(str[i])) { 10 | count++; 11 | } 12 | } 13 | 14 | return count; 15 | } 16 | 17 | console.log(countVowels("hello bro")); 18 | -------------------------------------------------------------------------------- /Solutions/Problem-02.js: -------------------------------------------------------------------------------- 1 | /* 2.Counter: 2 | Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc). 3 | */ 4 | 5 | 6 | var createCounter = function(n) { 7 | let count=n 8 | return function() { 9 | 10 | return count++; 11 | }; 12 | }; 13 | -------------------------------------------------------------------------------- /Practice Problems/14.SumArray.js: -------------------------------------------------------------------------------- 1 | // 14. Write a program that finds the sum of all the numbers in an array : 2 | 3 | 4 | function sumOfNumbers(arr) { 5 | let sum = 0; 6 | for (let i = 0; i < arr.length; i++) { 7 | sum += arr[i]; 8 | } 9 | return sum; 10 | } 11 | const numbers = [1, 2, 3, 4, 5]; 12 | const result = sumOfNumbers(numbers); 13 | console.log("The sum of the numbers is:", result); 14 | 15 | -------------------------------------------------------------------------------- /Practice Problems/28.String3.js: -------------------------------------------------------------------------------- 1 | // 28. Get Unique Characters from a String in JavaScript : 2 | 3 | 4 | function uniqueCharacters(str) { 5 | const uniqueChars = []; 6 | for (let i = 0; i < str.length; i++) { 7 | if (!uniqueChars.includes(str[i])) { 8 | uniqueChars.push(str[i]); 9 | } 10 | } 11 | return uniqueChars.join(''); 12 | } 13 | 14 | console.log(uniqueCharacters("kartikibhoite")); -------------------------------------------------------------------------------- /Practice Problems/02.Reverse.js: -------------------------------------------------------------------------------- 1 | // 2. Write a JavaScript program to reverse the given string : 2 | 3 | function reverseString(str) { 4 | let reversed = ""; 5 | for (let i = str.length - 1; i >= 0; i--) { 6 | reversed += str[i]; 7 | } 8 | return reversed; 9 | } 10 | const inputString = "hello world"; 11 | const reversedString = reverseString(inputString); 12 | console.log("Reversed string:", reversedString); 13 | -------------------------------------------------------------------------------- /Practice Problems/22.String2.js: -------------------------------------------------------------------------------- 1 | // 22. Find the Longest Word in a String in JavaScript : 2 | 3 | 4 | function longestWord(str) { 5 | 6 | const words = str.split(' '); 7 | let longest = ''; 8 | 9 | for (let word of words) { 10 | if (word.length > longest.length) { 11 | longest = word; 12 | } 13 | } 14 | return longest; 15 | } 16 | 17 | console.log(longestWord('Shubham is great')); 18 | -------------------------------------------------------------------------------- /Solutions/Problem-17.js: -------------------------------------------------------------------------------- 1 | /* 17.Array Prototype Last : 2 | 3 | Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1. 4 | You may assume the array is the output of JSON.parse 5 | 6 | */ 7 | 8 | Array.prototype.last = function() { 9 | return this.length === 0 ? -1 : this[this.length - 1]; 10 | 11 | }; -------------------------------------------------------------------------------- /Solutions/Problem-18.js: -------------------------------------------------------------------------------- 1 | /* 18.Sort By : 2 | Given an array arr and a function fn, return a sorted array sortedArr. You can assume fn only returns numbers and those numbers determine the sort order of sortedArr. sortedArr must be sorted in ascending order by fn output. 3 | 4 | You may assume that fn will never duplicate numbers for a given array. 5 | */ 6 | 7 | 8 | var sortBy = function(arr, fn) { 9 | return arr.sort((a, b) => fn(a) - fn(b)); 10 | }; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode-JavaScript 2 | 3 | ## Solution of LeetCode-JavaScript challenges. 👉👉 [View Here](https://github.com/Shubham-Bhoite/LeetCode-JavaScript/tree/main/Solutions)👈👈 4 | -------------------------------------------------------------------------------- /Practice Problems/26.Array6.js: -------------------------------------------------------------------------------- 1 | // 26. Find the maximum difference between two numbers in an array in JavaScript : 2 | 3 | 4 | function maxDifference(arr) { 5 | let min = arr[0] 6 | let maxDiff = 0; 7 | 8 | for (let i = 1; i < arr.length; i++) { 9 | const diff = arr[i] - min; 10 | maxDiff = Math.max(maxDiff, diff); 11 | min = Math.min(min, arr[i]); 12 | } 13 | return maxDiff; 14 | } 15 | 16 | console.log(maxDifference([1, 2, 90, 10, 110])); 17 | -------------------------------------------------------------------------------- /Practice Problems/17.string.js: -------------------------------------------------------------------------------- 1 | // 17. Write a function that counts the occurrences of each character in the given string : 2 | 3 | 4 | 5 | function countCharacterOccurrences(str) { 6 | const charCount = {}; 7 | for (let char of str) { 8 | charCount[char] = (charCount[char] || 0) + 1; 9 | } 10 | return charCount; 11 | } 12 | const inputString = "hello world"; 13 | const characterCounts = countCharacterOccurrences(inputString); 14 | console.log("Character counts:", characterCounts); 15 | -------------------------------------------------------------------------------- /Practice Problems/09.Palindrome.js: -------------------------------------------------------------------------------- 1 | // 9. Write a JavaScript program to check whether the given string is a palindrome. : 2 | 3 | 4 | function isPalindrome(str) { 5 | const reversedStr = str.split("").reverse().join(""); 6 | return str === reversedStr; 7 | } 8 | const inputString = "racecar"; 9 | const isPalindromeResult = isPalindrome(inputString); 10 | if (isPalindromeResult) { 11 | console.log(inputString, "is a palindrome."); 12 | } else { 13 | console.log(inputString, "is not a palindrome."); 14 | } 15 | -------------------------------------------------------------------------------- /Solutions/Problem-06.js: -------------------------------------------------------------------------------- 1 | /* 6.Filter Elements from Array: 2 | 3 | Given an integer array arr and a filtering function fn, return a filtered array filteredArr. 4 | The fn function takes one or two arguments: 5 | - arr[i] - number from the arr 6 | - i - index of arr[i] 7 | filteredArr should only contain the elements from the arr for which the expression fn(arr[i], i) evaluates to a truthy value. A truthy value is a value where Boolean(value) returns true. 8 | */ 9 | 10 | var filter = function(arr, fn) { 11 | return arr.filter(fn); 12 | }; -------------------------------------------------------------------------------- /Practice Problems/03.Max.js: -------------------------------------------------------------------------------- 1 | // 3. Write a JavaScript function that finds the maximum number in an array : 2 | 3 | function findMax(arr) { 4 | if (arr.length === 0) { 5 | return null; // Handle empty array 6 | } 7 | let max = arr[0]; 8 | for (let i = 1; i < arr.length; i++) { 9 | if (arr[i] > max) { 10 | max = arr[i]; 11 | } 12 | } 13 | return max; 14 | } 15 | const numbers = [10, 5, 25, 8, 15]; 16 | const maxNumber = findMax(numbers); 17 | console.log("The maximum number is:", maxNumber); 18 | 19 | -------------------------------------------------------------------------------- /Practice Problems/06.Array.js: -------------------------------------------------------------------------------- 1 | // 6. Write a JavaScript function that uses an array of numbers and only gives a new array with even numbers : 2 | 3 | 4 | function evenNumbers(numbers) { 5 | const evenArray = []; 6 | for (let i = 0; i < numbers.length; i++) { 7 | if (numbers[i] % 2 === 0) { 8 | evenArray.push(numbers[i]); 9 | } 10 | } 11 | return evenArray; 12 | } 13 | const numbers = [1, 2, 3, 4, 5, 6, 7, 8]; 14 | const evenNumbersArray = evenNumbers(numbers); 15 | console.log("Even numbers:", evenNumbersArray); 16 | 17 | -------------------------------------------------------------------------------- /Solutions/Problem-16.js: -------------------------------------------------------------------------------- 1 | /* 16.Is Object Empty : 2 | 3 | Given an object or an array, return if it is empty. 4 | - An empty object contains no key-value pairs. 5 | - An empty array contains no elements. 6 | You may assume the object or array is the output of JSON.parse. 7 | */ 8 | 9 | var isEmpty = function(obj) { 10 | if (Array.isArray(obj)) { 11 | return obj.length === 0; 12 | } else if (typeof obj === 'object' && obj !== null) { 13 | return Object.keys(obj).length === 0; 14 | } 15 | return false; 16 | 17 | }; -------------------------------------------------------------------------------- /Solutions/Problem-11.js: -------------------------------------------------------------------------------- 1 | /* 11.Add Two Promises : 2 | 3 | Given two promises promise1 and promise2, return a new promise. promise1 and promise2 will both resolve with a number. The returned promise should resolve with the sum of the two numbers. 4 | */ 5 | 6 | 7 | var addTwoPromises = async function(promise1, promise2) { 8 | return new Promise(async (res,rej) => { 9 | const sum= await Promise.all([promise1, promise2]); 10 | 11 | 12 | let ans= sum.reduce((acc, currVal) => acc +currVal); 13 | res (ans); 14 | }) 15 | 16 | }; -------------------------------------------------------------------------------- /Solutions/Problem-08.js: -------------------------------------------------------------------------------- 1 | /* 8.Function Composition : 2 | 3 | Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions. 4 | The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))). 5 | The function composition of an empty list of functions is the identity function f(x) = x. 6 | */ 7 | 8 | var compose = function(functions) { 9 | return function(x) { 10 | for (const fn of functions.reverse()){ 11 | x= fn(x); 12 | } 13 | return x; 14 | } 15 | }; -------------------------------------------------------------------------------- /Solutions/Problem-23.js: -------------------------------------------------------------------------------- 1 | /* 23.Debounce : 2 | 3 | Given a function fn and a time in milliseconds t, return a debounced version of that function. 4 | 5 | A debounced function is a function whose execution is delayed by t milliseconds and whose execution is cancelled if it is called again within that window of time. The debounced function should also receive the passed parameters.*/ 6 | 7 | 8 | var debounce = function(fn, t) { 9 | let timer; 10 | return function(...args) { 11 | clearTimeout(timer); 12 | timer = setTimeout(() => fn(...args), t); 13 | } 14 | }; -------------------------------------------------------------------------------- /Practice Problems/10.FibonacciSequence.js: -------------------------------------------------------------------------------- 1 | // 10. Write a JavaScript function that returns the Fibonacci sequence to a specified number : 2 | 3 | 4 | function fibonacci(n) { 5 | if (n <= 0) { 6 | return []; 7 | } 8 | if (n === 1) { 9 | return [0]; // Return [0] if n is 1 10 | } 11 | const sequence = [0, 1]; 12 | for (let i = 2; i < n; i++) { 13 | sequence.push(sequence[i - 1] + sequence[i - 2]); 14 | } 15 | return sequence; 16 | } 17 | const terms = 10; 18 | const fibonacciSequence = fibonacci(terms); 19 | console.log(fibonacciSequence); 20 | 21 | -------------------------------------------------------------------------------- /Solutions/Problem-10.js: -------------------------------------------------------------------------------- 1 | /* 10.Allow One Function Call : 2 | 3 | Given a function fn, return a new function that is identical to the original function except that it ensures fn is called at most once. 4 | The first time the returned function is called, it should return the same result as fn. 5 | Every subsequent time it is called, it should return undefined. 6 | */ 7 | 8 | 9 | var once = function(fn) { 10 | let firstCall= true; 11 | return function(...args){ 12 | if (firstCall){ 13 | firstCall =false; 14 | return fn(...args); 15 | } 16 | 17 | } 18 | }; -------------------------------------------------------------------------------- /Practice Problems/07.ChangeString.js: -------------------------------------------------------------------------------- 1 | // 7. Write a JavaScript program to change the string to title (first letter of every word should be in upper case) : 2 | 3 | function capitalizeFirstLetterOfEachWord(str) { 4 | const words = str.split(" "); 5 | const capitalizedWords = words.map(word => { 6 | return word.charAt(0).toUpperCase() + word.slice(1); 7 | }); 8 | return capitalizedWords.join(" "); 9 | } 10 | const inputString = "hello world this is a sample string"; 11 | const capitalizedString = capitalizeFirstLetterOfEachWord(inputString); 12 | console.log("Capitalized string:", capitalizedString); 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Solutions/Problem-15.js: -------------------------------------------------------------------------------- 1 | /* 15.Interval Cancellation : 2 | 3 | Given a function fn, an array of arguments args, and an interval time t, return a cancel function cancelFn. 4 | After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked. 5 | setTimeout(cancelFn, cancelTimeMs) 6 | The function fn should be called with args immediately and then called again every t milliseconds until cancelFn is called at cancelTimeMs ms. 7 | */ 8 | 9 | var cancellable = function(fn, args, t) { 10 | fn(...args); 11 | const timer = setInterval(()=>fn(...args), t); 12 | 13 | return () => clearInterval(timer); 14 | 15 | }; -------------------------------------------------------------------------------- /Practice Problems/08.NestedArray.js: -------------------------------------------------------------------------------- 1 | // 8. Write a JavaScript function to find the largest element in the nested array : 2 | 3 | 4 | 5 | function findLargestElement(arr) { 6 | let max = -Infinity; 7 | function helper(nestedArr) { 8 | for (let item of nestedArr) { 9 | if (typeof item === "number") { 10 | max = Math.max(max, item); 11 | } else if (Array.isArray(item)) { 12 | helper(item); 13 | } 14 | } 15 | } 16 | helper(arr); 17 | return max; 18 | } 19 | const nestedArray = [1, [2, 3, [4, 5]], 6, [7, 8]]; 20 | const largestElement = findLargestElement(nestedArray); 21 | console.log("Largest element:", largestElement); 22 | -------------------------------------------------------------------------------- /Practice Problems/20.Array4.js: -------------------------------------------------------------------------------- 1 | // 20. Write a function that takes an array of numbers as input and returns a new array with unique elements only. : 2 | 3 | 4 | function findLargestAndSmallest(arr) { 5 | let largest = arr[0]; 6 | let smallest = arr[0]; 7 | for (let i = 1; i < arr.length; i++) { 8 | if (arr[i] > largest) { 9 | largest = arr[i]; 10 | } else if (arr[i] < smallest) { 11 | smallest = arr[i]; 12 | } 13 | } 14 | return { largest, smallest }; 15 | } 16 | const numbers = [10, 5, 25, 8, 15]; 17 | const result = findLargestAndSmallest(numbers); 18 | console.log("Largest number:", result.largest); 19 | console.log("Smallest number:", result.smallest); 20 | 21 | -------------------------------------------------------------------------------- /Practice Problems/13.Array2.js: -------------------------------------------------------------------------------- 1 | // 13. Write a JavaScript function that uses an array of objects and keys and shows a new array based on the values of the key in ascending order : 2 | 3 | 4 | function sortByKeyValue(arr, key) { 5 | return arr.sort((a, b) => { 6 | if (a[key] < b[key]) { 7 | return -1; 8 | } else if (a[key] > b[key]) { 9 | return 1; 10 | } else { 11 | return 0; 12 | } 13 | }); 14 | } 15 | const data = [ 16 | { name: "Alice", age: 25 }, // Removed the comma after "Alice" 17 | { name: "Bob", age: 30 }, 18 | { name: "Charlie", age: 20 } 19 | ]; 20 | const sortedData = sortByKeyValue(data, "age"); 21 | console.log(sortedData); 22 | 23 | -------------------------------------------------------------------------------- /Practice Problems/19.Array3.js: -------------------------------------------------------------------------------- 1 | // 19. Write a function to find the largest and smallest numbers in the array from the set of a given array of numbers : 2 | 3 | 4 | function findLargestAndSmallest(arr) { 5 | let largest = arr[0]; 6 | let smallest = arr[0]; 7 | for (let i = 1; i < arr.length; i++) { 8 | if (arr[i] > largest) { 9 | largest = arr[i]; 10 | } else if (arr[i] < smallest) { 11 | smallest = arr[i]; 12 | } 13 | } 14 | return { largest, smallest }; 15 | } 16 | const numbers = [10, 5, 25, 8, 15]; 17 | const result = findLargestAndSmallest(numbers); 18 | console.log("Largest number:", result.largest); 19 | console.log("Smallest number:", result.smallest); 20 | 21 | -------------------------------------------------------------------------------- /Solutions/Problem-13.js: -------------------------------------------------------------------------------- 1 | /* 13.Chunk Array: 2 | 3 | Given an array arr and a chunk size size, return a chunked array. 4 | A chunked array contains the original elements in arr, but consists of subarrays each of length size. The length of the last subarray may be less than size if arr.length is not evenly divisible by size. 5 | */ 6 | 7 | var chunk = function(arr, size) { 8 | const res=[]; 9 | let subarr = []; 10 | for (let i=0; i fn(...args), t); 13 | return () => clearTimeout(id); 14 | }; -------------------------------------------------------------------------------- /Solutions/Problem-25.js: -------------------------------------------------------------------------------- 1 | /* 25.Group By : 2 | 3 | Write code that enhances all arrays such that you can call the array.groupBy(fn) method on any array and it will return a grouped version of the array. 4 | 5 | A grouped array is an object where each key is the output of fn(arr[i]) and each value is an array containing all items in the original array which generate that key. 6 | 7 | The provided callback fn will accept an item in the array and return a string key. 8 | The order of each value list should be the order the items appear in the array. Any order of keys is acceptable. 9 | */ 10 | 11 | Array.prototype.groupBy = function(fn) { 12 | return this.reduce((acc, item) => { 13 | const key = fn(item); 14 | if (!acc[key]) { 15 | acc[key] = []; 16 | } 17 | acc[key].push(item); 18 | return acc; 19 | }, {}); 20 | }; -------------------------------------------------------------------------------- /Solutions/Problem-03.js: -------------------------------------------------------------------------------- 1 | /* 3.To Be Or Not To Be: 2 | Write a function expect that helps developers test their code. It should take in any value val and return an object with the following two functions. 3 | 4 | - toBe(val) accepts another value and returns true if the two values === each other. If they are not equal, it should throw an error "Not Equal". 5 | - notToBe(val) accepts another value and returns true if the two values !== each other. If they are equal, it should throw an error "Equal". 6 | */ 7 | 8 | var expect = function(val) { 9 | return { 10 | toBe:(s) =>{ 11 | if (s===val) 12 | return true; 13 | else throw new Error("Not Equal") 14 | }, 15 | notToBe:(s) =>{ 16 | if (s!==val) 17 | return true; 18 | else throw new Error("Equal"); 19 | } 20 | 21 | } 22 | }; -------------------------------------------------------------------------------- /Solutions/Problem-04.js: -------------------------------------------------------------------------------- 1 | /* 4.Counter II : 2 | Write a function createCounter. It should accept an initial integer init. It should return an object with three functions. 3 | 4 | The three functions are: 5 | - increment() increases the current value by 1 and then returns it. 6 | - decrement() reduces the current value by 1 and then returns it. 7 | - reset() sets the current value to init and then returns it. 8 | */ 9 | 10 | var createCounter = function(init) { 11 | let count=init; 12 | 13 | function increment(){ 14 | return ++count; 15 | } 16 | 17 | function decrement(){ 18 | return --count; 19 | } 20 | 21 | function reset(){ 22 | count=init; 23 | return count; 24 | } 25 | return { 26 | increment: increment, 27 | decrement: decrement, 28 | reset:reset 29 | } 30 | 31 | 32 | }; -------------------------------------------------------------------------------- /Practice Problems/25.Anagrams.js: -------------------------------------------------------------------------------- 1 | // 25. Check if Two Strings are Anagrams or not in JavaScript : 2 | 3 | 4 | function areAnagrams(str1, str2) { 5 | if (str1.length !== str2.length) { 6 | return false; 7 | } 8 | 9 | let count1 = {}; 10 | let count2 = {}; 11 | 12 | // Count frequency of each character in str1 13 | for (let i = 0; i < str1.length; i++) { 14 | let char = str1[i]; 15 | count1[char] = (count1[char] || 0) + 1; 16 | } 17 | 18 | // Count frequency of each character in str2 19 | for (let i = 0; i < str2.length; i++) { 20 | let char = str2[i]; 21 | count2[char] = (count2[char] || 0) + 1; 22 | } 23 | 24 | // Compare the two frequency objects 25 | for (let char in count1) { 26 | if (count1[char] !== count2[char]) { 27 | return false; 28 | } 29 | } 30 | 31 | return true; 32 | } 33 | console.log(areAnagrams("listen", "silent")); 34 | -------------------------------------------------------------------------------- /Solutions/Problem-27.js: -------------------------------------------------------------------------------- 1 | /* 27. Compact Object : 2 | 3 | Given an object or array obj, return a compact object. 4 | A compact object is the same as the original object, except with keys containing falsy values removed. This operation applies to the object and any nested objects. 5 | Arrays are considered objects where the indices are keys. A value is considered falsy when Boolean(value) returns false. 6 | 7 | You may assume the obj is the output of JSON.parse. In other words, it is valid JSON. 8 | 9 | */ 10 | 11 | var compactObject = function(obj) { 12 | if (Array.isArray(obj)) { 13 | return obj 14 | .map(compactObject) 15 | .filter(Boolean); 16 | } else if (obj && typeof obj === 'object') { 17 | return Object.fromEntries( 18 | Object.entries(obj) 19 | .map(([k, v]) => [k, compactObject(v)]) 20 | .filter(([_, v]) => Boolean(v)) 21 | ); 22 | } 23 | return obj; 24 | 25 | }; -------------------------------------------------------------------------------- /Solutions/Problem-29.js: -------------------------------------------------------------------------------- 1 | /* 29.Flatten Deeply Nested Array : 2 | 3 | Given a multi-dimensional array arr and a depth n, return a flattened version of that array. 4 | 5 | A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays. 6 | 7 | A flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n. The depth of the elements in the first array are considered to be 0. 8 | */ 9 | 10 | 11 | 12 | var flat = function (arr, n) { 13 | function helper(array, depth) { 14 | let result = []; 15 | for (let el of array) { 16 | if (Array.isArray(el) && depth < n) { 17 | result.push(...helper(el, depth + 1)); 18 | } else { 19 | result.push(el); 20 | } 21 | } 22 | return result; 23 | } 24 | 25 | return helper(arr, 0); 26 | }; -------------------------------------------------------------------------------- /Solutions/Problem-26.js: -------------------------------------------------------------------------------- 1 | /* 26. Join Two Arrays by ID: 2 | 3 | Given two arrays arr1 and arr2, return a new array joinedArray. All the objects in each of the two inputs arrays will contain an id field that has an integer value. 4 | joinedArray is an array formed by merging arr1 and arr2 based on their id key. The length of joinedArray should be the length of unique values of id. The returned array should be sorted in ascending order based on the id key. 5 | If a given id exists in one array but not the other, the single object with that id should be included in the result array without modification. 6 | If two objects share an id, their properties should be merged into a single object: 7 | 8 | If a key only exists in one object, that single key-value pair should be included in the object. 9 | If a key is included in both objects, the value in the object from arr2 should override the value from arr1. 10 | */ 11 | 12 | var join = function(arr1, arr2) { 13 | let map = new Map(); 14 | [...arr1, ...arr2].forEach(obj => map.set(obj.id, { ...map.get(obj.id), ...obj })); 15 | return [...map.values()].sort((a, b) => a.id - b.id); 16 | }; -------------------------------------------------------------------------------- /Solutions/Problem-19.js: -------------------------------------------------------------------------------- 1 | /* 19.Array Wrapper : 2 | 3 | Create a class ArrayWrapper that accepts an array of integers in its constructor. This class should have two features: 4 | 5 | - When two instances of this class are added together with the + operator, the resulting value is the sum of all the elements in both arrays. 6 | - When the String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3]. 7 | */ 8 | 9 | /** 10 | * @param {number[]} nums 11 | * @return {void} 12 | */ 13 | var ArrayWrapper = function(nums) { 14 | this.nums = nums; 15 | }; 16 | 17 | /** 18 | * @return {number} 19 | */ 20 | ArrayWrapper.prototype.valueOf = function() { 21 | return this.nums.reduce((sum, num) => sum + num, 0); 22 | } 23 | 24 | /** 25 | * @return {string} 26 | */ 27 | ArrayWrapper.prototype.toString = function() { 28 | return `[${this.nums.join(",")}]`; 29 | 30 | } 31 | 32 | /** 33 | * const obj1 = new ArrayWrapper([1,2]); 34 | * const obj2 = new ArrayWrapper([3,4]); 35 | * obj1 + obj2; // 10 36 | * String(obj1); // "[1,2]" 37 | * String(obj2); // "[3,4]" 38 | */ -------------------------------------------------------------------------------- /Solutions/Problem-22.js: -------------------------------------------------------------------------------- 1 | /* 22.Promise Time Limit : 2 | 3 | Given an asynchronous function fn and a time t in milliseconds, return a new time limited version of the input function. fn takes arguments provided to the time limited function. 4 | 5 | The time limited function should follow these rules: 6 | If the fn completes within the time limit of t milliseconds, the time limited function should resolve with the result. 7 | If the execution of the fn exceeds the time limit, the time limited function should reject with the string "Time Limit Exceeded". 8 | */ 9 | 10 | var timeLimit = function(fn, t) { 11 | 12 | return async function(...args) { 13 | return new Promise(async (resolve, reject) => { 14 | const timer = setTimeout(() => { 15 | reject("Time Limit Exceeded"); 16 | }, t); 17 | 18 | try { 19 | const result = await fn(...args); 20 | clearTimeout(timer); 21 | resolve(result); 22 | } catch (error) { 23 | clearTimeout(timer); 24 | reject(error); 25 | } 26 | }); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Solutions/Problem-24.js: -------------------------------------------------------------------------------- 1 | /* 24.Execute Asynchronous Functions in Parallel : 2 | 3 | Given an array of asynchronous functions functions, return a new promise promise. Each function in the array accepts no arguments and returns a promise. All the promises should be executed in parallel. 4 | 5 | promise resolves: 6 | When all the promises returned from functions were resolved successfully in parallel. The resolved value of promise should be an array of all the resolved values of promises in the same order as they were in the functions. The promise should resolve when all the asynchronous functions in the array have completed execution in parallel. 7 | 8 | promise rejects: 9 | When any of the promises returned from functions were rejected. promise should also reject with the reason of the first rejection. 10 | */ 11 | 12 | 13 | var promiseAll = function(functions) { 14 | return new Promise((resolve, reject) => { 15 | let results = []; 16 | let count = 0; 17 | functions.forEach((fn, i) => 18 | fn() 19 | .then(res => { 20 | results[i] = res; 21 | if (++count === functions.length) resolve(results); 22 | }) 23 | .catch(reject) 24 | ); 25 | }); 26 | }; 27 | -------------------------------------------------------------------------------- /Solutions/Problem-20.js: -------------------------------------------------------------------------------- 1 | /* 20.Calculator with Method Chaining : 2 | 3 | Design a Calculator class. The class should provide the mathematical operations of addition, subtraction, multiplication, division, and exponentiation. It should also allow consecutive operations to be performed using method chaining. The Calculator class constructor should accept a number which serves as the initial value of result.*/ 4 | class Calculator { 5 | /** 6 | * @param {number} value 7 | */ 8 | constructor(value) { 9 | this.result = value; 10 | } 11 | 12 | /** 13 | * @param {number} value 14 | * @return {Calculator} 15 | */ 16 | add(value) { 17 | this.result += value; 18 | return this; 19 | } 20 | 21 | /** 22 | * @param {number} value 23 | * @return {Calculator} 24 | */ 25 | subtract(value) { 26 | this.result -= value; 27 | return this; 28 | } 29 | 30 | /** 31 | * @param {number} value 32 | * @return {Calculator} 33 | */ 34 | multiply(value) { 35 | this.result *= value; 36 | return this; 37 | } 38 | 39 | /** 40 | * @param {number} value 41 | * @return {Calculator} 42 | */ 43 | divide(value) { 44 | if (value === 0) { 45 | throw new Error("Division by zero is not allowed"); 46 | } 47 | this.result /= value; 48 | return this; 49 | } 50 | 51 | /** 52 | * @param {number} value 53 | * @return {Calculator} 54 | */ 55 | power(value) { 56 | this.result = Math.pow(this.result, value); 57 | return this; 58 | } 59 | 60 | /** 61 | * @return {number} 62 | */ 63 | getResult() { 64 | return this.result; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Solutions/Problem-30.js: -------------------------------------------------------------------------------- 1 | /* 30.Cache With Time Limit : 2 | 3 | Write a class that allows getting and setting key-value pairs, however a time until expiration is associated with each key. 4 | The class has three public methods: 5 | 6 | 1) set(key, value, duration): accepts an integer key, an integer value, and a duration in milliseconds. Once the duration has elapsed, the key should be inaccessible. The method should return true if the same un-expired key already exists and false otherwise. Both the value and duration should be overwritten if the key already exists. 7 | 2) get(key): if an un-expired key exists, it should return the associated value. Otherwise it should return -1. 8 | 3) count(): returns the count of un-expired keys. 9 | 10 | */ 11 | 12 | var TimeLimitedCache = function() { 13 | this.cache = new Map(); 14 | this.currentTime = 0; 15 | }; 16 | 17 | TimeLimitedCache.prototype.setTime = function(time) { 18 | this.currentTime = time; 19 | }; 20 | 21 | TimeLimitedCache.prototype.set = function(key, value, duration) { 22 | const exists = this.cache.has(key) && this.cache.get(key).expiresAt > this.currentTime; 23 | this.cache.set(key, { value, expiresAt: this.currentTime + duration }); 24 | return exists; 25 | }; 26 | 27 | TimeLimitedCache.prototype.get = function(key) { 28 | const entry = this.cache.get(key); 29 | if (!entry || entry.expiresAt <= this.currentTime) { 30 | this.cache.delete(key); 31 | return -1; 32 | } 33 | return entry.value; 34 | }; 35 | 36 | TimeLimitedCache.prototype.count = function() { 37 | let count = 0; 38 | for (const [key, entry] of this.cache) { 39 | if (entry.expiresAt > this.currentTime) { 40 | count++; 41 | } else { 42 | this.cache.delete(key); 43 | } 44 | } 45 | return count; 46 | }; 47 | -------------------------------------------------------------------------------- /Solutions/Problem-28.js: -------------------------------------------------------------------------------- 1 | /* 28. Event Emitter : 2 | 3 | Design an EventEmitter class. This interface is similar (but with some differences) to the one found in Node.js or the Event Target interface of the DOM. The EventEmitter should allow for subscribing to events and emitting them. 4 | Your EventEmitter class should have the following two methods: 5 | 6 | 1.subscribe - This method takes in two arguments: the name of an event as a string and a callback function. This callback function will later be called when the event is emitted. 7 | An event should be able to have multiple listeners for the same event. When emitting an event with multiple callbacks, each should be called in the order in which they were subscribed. An array of results should be returned. You can assume no callbacks passed to subscribe are referentially identical. 8 | The subscribe method should also return an object with an unsubscribe method that enables the user to unsubscribe. When it is called, the callback should be removed from the list of subscriptions and undefined should be returned. 9 | 10 | 2.emit - This method takes in two arguments: the name of an event as a string and an optional array of arguments that will be passed to the callback(s). If there are no callbacks subscribed to the given event, return an empty array. Otherwise, return an array of the results of all callback calls in the order they were subscribed. 11 | 12 | */ 13 | 14 | class EventEmitter { 15 | constructor() { 16 | this.events = {}; 17 | } 18 | 19 | subscribe(eventName, callback) { 20 | if (!this.events[eventName]) this.events[eventName] = []; 21 | this.events[eventName].push(callback); 22 | 23 | return { 24 | unsubscribe: () => { 25 | const i = this.events[eventName].indexOf(callback); 26 | if (i !== -1) this.events[eventName].splice(i, 1); 27 | } 28 | }; 29 | } 30 | 31 | emit(eventName, args = []) { 32 | return this.events[eventName]?.map(fn => fn(...args)) || []; 33 | } 34 | } 35 | --------------------------------------------------------------------------------