From f1e9bb481ae01231b597c321722435ddeb0ccb35 Mon Sep 17 00:00:00 2001 From: Shivang Parmar Date: Sun, 29 Oct 2023 16:23:39 +0530 Subject: [PATCH 01/13] added other method for bubble sort (#127) --- DSA/Arrays/BubbleSortM2.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 DSA/Arrays/BubbleSortM2.js diff --git a/DSA/Arrays/BubbleSortM2.js b/DSA/Arrays/BubbleSortM2.js new file mode 100644 index 0000000..1ee0d53 --- /dev/null +++ b/DSA/Arrays/BubbleSortM2.js @@ -0,0 +1,24 @@ +function bubbleSort(arr) { + const n = arr.length; + let swapped; + + do { + swapped = false; + + for (let i = 0; i < n - 1; i++) { + if (arr[i] > arr[i + 1]) { + // Swap elements arr[i] and arr[i+1] + let temp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = temp; + swapped = true; + } + } + } while (swapped); + + return arr; +} + +const arr = [234, 43, 55, 63, 5, 6, 235, 547]; +const sortedArray = bubbleSort(arr); +console.log(sortedArray); From 3bc02d7048e63ce9b2be6770b6d2eb9be50bed0f Mon Sep 17 00:00:00 2001 From: Dhruv Jaradi <112489039+JDhruv14@users.noreply.github.com> Date: Sun, 29 Oct 2023 16:24:10 +0530 Subject: [PATCH 02/13] Decimal to Roman Conversion Question (#126) --- InterviewQuestions/DecimaltoRoman.js | 53 ++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 InterviewQuestions/DecimaltoRoman.js diff --git a/InterviewQuestions/DecimaltoRoman.js b/InterviewQuestions/DecimaltoRoman.js new file mode 100644 index 0000000..5616166 --- /dev/null +++ b/InterviewQuestions/DecimaltoRoman.js @@ -0,0 +1,53 @@ +// javascript code implementation + +function integerToRoman(num) { + let roman = new Map(); // move outside + roman.set(1, 'I'); + roman.set(5, 'V'); + roman.set(10, 'X'); + roman.set(50, 'L'); + roman.set(100, 'C'); + roman.set(500, 'D'); + roman.set(1000, 'M'); + roman.set(5000, 'G'); + roman.set(10000, 'H'); + + let tmp = Array.from(String(num)); + let numDigits = tmp.length; + + let res = []; + for(let i=0;i= 5) { + res.push(roman.get(5*absolute)); + + let cnt = number-5; + while(cnt--) res.push(roman.get(absolute)); + } + else{ + if (number >= 4) { + res.push(roman.get(absolute)); + res.push(roman.get(5*absolute)); + } + else { + + let cnt = number; + while(cnt--) res.push(roman.get(absolute)); + } + } + } + return res; +} + +let ans = integerToRoman(3549).join(''); +console.log(ans); + +// This code is contributed by Nidhi goel. From 145b4df8be3605a50d4afa98169a1c09ba3065d3 Mon Sep 17 00:00:00 2001 From: Amit vaghela <138572130+Amitkumar-Vaghela@users.noreply.github.com> Date: Sun, 29 Oct 2023 16:24:28 +0530 Subject: [PATCH 03/13] FindTheElementGivenPosition in linkedlist (#125) we can find the data of specific position in linkedlist in DSA --- .../FindTheElementGivenPosition in linklist | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 DSA/BinarySearch/FindTheElementGivenPosition in linklist diff --git a/DSA/BinarySearch/FindTheElementGivenPosition in linklist b/DSA/BinarySearch/FindTheElementGivenPosition in linklist new file mode 100644 index 0000000..a558266 --- /dev/null +++ b/DSA/BinarySearch/FindTheElementGivenPosition in linklist @@ -0,0 +1,60 @@ +class Node { + constructor(data) { + this.data = data; + this.next = null; + } +} + +class LinkedList { + constructor() { + this.head = null; + } + + append(data) { + const newNode = new Node(data); + + if (!this.head) { + this.head = newNode; + } else { + let current = this.head; + while (current.next) { + current = current.next; + } + current.next = newNode; + } + } + + findNodeAtPosition(position) { + if (position < 0 || !this.head) { + return null; // Position is out of bounds or the list is empty + } + + let current = this.head; + let index = 0; + + while (current) { + if (index === position) { + return current; + } + current = current.next; + index++; + } + + return null; + } +} +const linkedList = new LinkedList(); +linkedList.append(10); +linkedList.append(20); +linkedList.append(30); +linkedList.append(40); +linkedList.append(50); + +const positionToFind = 4; +const node = linkedList.findNodeAtPosition(positionToFind); + +if (node) { + console.log(`Node at position ${positionToFind} contains data: ${node.data}`); +} else { + console.log(`Node at position ${positionToFind} not found.`); +} From 50e4f5aa57ef5b3554ebbdd7367350b281f36581 Mon Sep 17 00:00:00 2001 From: Amit vaghela <138572130+Amitkumar-Vaghela@users.noreply.github.com> Date: Sun, 29 Oct 2023 16:30:54 +0530 Subject: [PATCH 04/13] Create Heapsort in DSA (#122) --- DSA/Arrays/Heapsort in DSA | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 DSA/Arrays/Heapsort in DSA diff --git a/DSA/Arrays/Heapsort in DSA b/DSA/Arrays/Heapsort in DSA new file mode 100644 index 0000000..0398788 --- /dev/null +++ b/DSA/Arrays/Heapsort in DSA @@ -0,0 +1,35 @@ +function heapSort(arr) { + buildMaxHeap(arr); + for (let i = arr.length - 1; i > 0; i--) { + [arr[0], arr[i]] = [arr[i], arr[0]]; + maxHeapify(arr, 0, i); + } +} +function buildMaxHeap(arr) { + const n = arr.length; + for (let i = Math.floor(n / 2) - 1; i >= 0; i--) { + maxHeapify(arr, i, n); + } +} +function maxHeapify(arr, i, heapSize) { + const leftChild = 2 * i + 1; + const rightChild = 2 * i + 2; + let largest = i; + + if (leftChild < heapSize && arr[leftChild] > arr[largest]) { + largest = leftChild; + } + + if (rightChild < heapSize && arr[rightChild] > arr[largest]) { + largest = rightChild; + } + + if (largest !== i) { + [arr[i], arr[largest]] = [arr[largest], arr[i]]; // Swap arr[i] and arr[largest] + maxHeapify(arr, largest, heapSize); + } +} +const arr = [12, 11, 13, 5, 6, 7]; +heapSort(arr); + +console.log("Sorted array:", arr); From d1c26d6c3eeec091276d6eae8a07e48bcf5d2046 Mon Sep 17 00:00:00 2001 From: Aakash Bansal <146818230+AAKASHBANSAL96@users.noreply.github.com> Date: Sun, 29 Oct 2023 16:33:13 +0530 Subject: [PATCH 05/13] Kadanes Algorithm (#118) --- DSA/Arrays/KadanesAlgo.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 DSA/Arrays/KadanesAlgo.js diff --git a/DSA/Arrays/KadanesAlgo.js b/DSA/Arrays/KadanesAlgo.js new file mode 100644 index 0000000..8f1f962 --- /dev/null +++ b/DSA/Arrays/KadanesAlgo.js @@ -0,0 +1,31 @@ + +function maxSubarraySum(arr, n) { + let maxi = Number.MIN_SAFE_INTEGER; // maximum sum + let sum = 0; + + for (let i = 0; i < n; i++) { + sum += arr[i]; + + if (sum > maxi) { + maxi = sum; + } + + // If sum < 0: discard the sum calculated + if (sum < 0) { + sum = 0; + } + } + + // To consider the sum of the empty subarray + // uncomment the following check: + + //if (maxi < 0) maxi = 0; + + return maxi; +} + +const arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]; +const n = arr.length; +const maxSum = maxSubarraySum(arr, n); +console.log("The maximum subarray sum is: " + maxSum); + From 0258aa4f2f02548480e195bc1966348f64f37b31 Mon Sep 17 00:00:00 2001 From: Meet Javiya <107299231+meet-javiya0@users.noreply.github.com> Date: Sun, 29 Oct 2023 16:33:44 +0530 Subject: [PATCH 06/13] Update Sqrtx.js (#107) * Update Sqrtx.js * Update twoSum.js --- DSA/BinarySearch/Sqrtx.js | 2 ++ SDE_Sheet/twoSum.js | 31 +++++++++++++++---------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/DSA/BinarySearch/Sqrtx.js b/DSA/BinarySearch/Sqrtx.js index 82db69b..891b069 100644 --- a/DSA/BinarySearch/Sqrtx.js +++ b/DSA/BinarySearch/Sqrtx.js @@ -2,6 +2,8 @@ * @param {number} x * @return {number} */ + +// function to calculate square root of a number using binary search var mySqrt = function(x) { let start = 1; let end = x; diff --git a/SDE_Sheet/twoSum.js b/SDE_Sheet/twoSum.js index 0de5d41..11b4c71 100644 --- a/SDE_Sheet/twoSum.js +++ b/SDE_Sheet/twoSum.js @@ -5,19 +5,18 @@ */ /* A brute-force approach. Traverse the nums array via two pointers i and j and return indexes stored in an array if the total matches the target*/ - var twoSum = function(nums, target) { - let targetResult =[]; - - for(let i =0; i< nums.length; i++){ - for(let j = i+1; j< nums.length; j++){ - - if( nums[i]+ nums[j] === target){ - - targetResult.push(i); - targetResult.push(j); - } - } - } - - return targetResult; - }; \ No newline at end of file +var twoSum = function (nums, target) { + let targetResult = []; + // traverse the array via two pointers + for (let i = 0; i < nums.length; i++) { + for (let j = i + 1; j < nums.length; j++) { + // check if the sum of two numbers is equal to the target + if (nums[i] + nums[j] === target) { + targetResult.push(i); + targetResult.push(j); + } + } + } + // return the array with indexes + return targetResult; +}; \ No newline at end of file From fe62b2fd1dabf165e458924c4f2bfc644e8f7b59 Mon Sep 17 00:00:00 2001 From: KRISH SONI <67964054+krishvsoni@users.noreply.github.com> Date: Sun, 29 Oct 2023 16:34:14 +0530 Subject: [PATCH 07/13] modified SelectionSort.js (#95) * modified SelectionSort.js * added new functions --- DSA/Arrays/SelectionSort.js | 13 ++++---- ...alArrayWithXElementsGreaterThanEqualToX.js | 30 ++++++++++++------- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/DSA/Arrays/SelectionSort.js b/DSA/Arrays/SelectionSort.js index 76f4cbb..b1809bf 100644 --- a/DSA/Arrays/SelectionSort.js +++ b/DSA/Arrays/SelectionSort.js @@ -1,18 +1,17 @@ function selectionSort(arr) { - for (let i = 0; i < arr.length - 1; i++) { let min_index = i; for (let j = i + 1; j < arr.length; j++) { - if (arr[j] > arr[min_index]) { + if (arr[j] < arr[min_index]) { // Changed the comparison to sort in ascending order min_index = j; } } - let temp = arr[min_index] - arr[min_index] = arr[i] + let temp = arr[min_index]; + arr[min_index] = arr[i]; arr[i] = temp; } - return arr + return arr; } -let arr = [4, 12, 10, 15, 2] -console.log(selectionSort(arr)) \ No newline at end of file +let arr = [4, 12, 10, 15, 2]; +console.log(selectionSort(arr)); // Output: [2, 4, 10, 12, 15] diff --git a/DSA/Arrays/SpecialArrayWithXElementsGreaterThanEqualToX.js b/DSA/Arrays/SpecialArrayWithXElementsGreaterThanEqualToX.js index 5e995a2..7f83952 100644 --- a/DSA/Arrays/SpecialArrayWithXElementsGreaterThanEqualToX.js +++ b/DSA/Arrays/SpecialArrayWithXElementsGreaterThanEqualToX.js @@ -2,18 +2,28 @@ * @param {number[]} nums * @return {number} */ - var specialArray = function(nums) { - for(let i=0; i<=nums.length; i++){ +var specialArray = function(nums) { + for (let i = 0; i <= nums.length; i++) { let count = 0; - for(let j=0; j= i){ - count++ + for (let j = 0; j < nums.length; j++) { + if (nums[j] >= i) { + count++; } } - if(count === i){ - return i + if (count === i) { + return i; } } - return -1 - -}; \ No newline at end of file + return -1; +}; + +// Define an additional function to find the maximum value in the array. +function findMaxValue(nums) { + return Math.max(...nums); +} + +// Export the specialArray function and the findMaxValue function. +module.exports = { + specialArray, + findMaxValue +}; From 5ce8ccdb4d4eccde902807509b158793c83c079f Mon Sep 17 00:00:00 2001 From: Kartik Bhatiya <95977507+kartik2433@users.noreply.github.com> Date: Sun, 29 Oct 2023 16:36:05 +0530 Subject: [PATCH 08/13] Added Commments (#115) --- DSA/Arrays/BucketSort.js | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/DSA/Arrays/BucketSort.js b/DSA/Arrays/BucketSort.js index 52ad644..b5e491f 100644 --- a/DSA/Arrays/BucketSort.js +++ b/DSA/Arrays/BucketSort.js @@ -1,12 +1,20 @@ +// Define the input array const arr = [5, 3, 1, 2, 4, 7, 6]; + +// Define the bucketSort function const bucketSort = (arr) => { + // Check if the input array is empty if (arr.length === 0) { - return arr; + return arr; // Return the empty array } + + // Initialize variables for minValue, maxValue, and bucket size let i, minValue = arr[0], maxValue = arr[0], bucketSize = 5; + + // Find the minimum and maximum values in the input array arr.forEach(function (currentVal) { if (currentVal < minValue) { minValue = currentVal; @@ -14,28 +22,46 @@ const bucketSort = (arr) => { maxValue = currentVal; } }); + + // Calculate the number of buckets needed based on the range of values let bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1; + + // Create an array to hold all the buckets let allBuckets = new Array(bucketCount); + + // Initialize each bucket as an empty array for (i = 0; i < allBuckets.length; i++) { allBuckets[i] = []; } + + // Distribute values from the input array into the appropriate buckets arr.forEach(function (currentVal) { allBuckets[Math.floor((currentVal - minValue) / bucketSize)].push( currentVal ); }); + + // Clear the input array to prepare for sorting arr.length = 0; + + // Sort each bucket using insertion sort and merge them back into the input array allBuckets.forEach(function (bucket) { insertion(bucket); bucket.forEach(function (element) { arr.push(element); }); }); + + // Return the sorted array return arr; }; + +// Define the insertion sort function const insertion = (arr) => { let length = arr.length; let i, j; + + // Iterate through the elements in the bucket and perform insertion sort for (i = 1; i < length; i++) { let temp = arr[i]; for (j = i - 1; j >= 0 && arr[j] > temp; j--) { @@ -43,6 +69,9 @@ const insertion = (arr) => { } arr[j + 1] = temp; } - return arr; + + return arr; // Return the sorted bucket }; + +// Call the bucketSort function and print the sorted array console.log(bucketSort(arr)); From 17b70f4534ecf98e2636d862107b6c74dd6fc11a Mon Sep 17 00:00:00 2001 From: Sarthak Shah <92942966+Not-Sarthak@users.noreply.github.com> Date: Mon, 30 Oct 2023 09:22:26 +0530 Subject: [PATCH 09/13] docs: wrote documentation for the ShortestSubstring.js (#98) --- DSA/Strings/ShortestSubstring.js | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/DSA/Strings/ShortestSubstring.js b/DSA/Strings/ShortestSubstring.js index 2335f0e..e141cd7 100644 --- a/DSA/Strings/ShortestSubstring.js +++ b/DSA/Strings/ShortestSubstring.js @@ -1,24 +1,32 @@ +// This function compares two sets 'a' and 'b' to check if they have the same elements. +// It returns true if the sets have the same elements, and false otherwise. const compareSets = (a, b) => a.size === b.size && [...a].every(e => b.has(e)) +// This function, 'shortestSubstring', calculates the length of the shortest substring +// in the input string 's' that contains all unique characters present in the original string. function shortestSubstring(s) { - let len = s.length - let uniqueChars = new Set(Array.from(s)) - let subString = '' - let mLen = len + 1; + let len = s.length; // Get the length of the input string. + let uniqueChars = new Set(Array.from(s)); // Create a set of unique characters from the input string. + let subString = ''; // Initialize an empty substring. + let mLen = len + 1; // Initialize 'mLen' to be greater than the length of the input string. + // Nested loops to find all possible substrings. for (let i = 0; i < len; i++) { for (let j = i; j < len; j++) { - subString = subString + s[j] + subString = subString + s[j]; // Add characters to the current substring. + + // Check if the unique characters of the current substring match the unique characters of the input string. if (compareSets(new Set(subString), uniqueChars)) { if (mLen > subString.length) { - mLen = subString.length + mLen = subString.length; // Update 'mLen' if a shorter valid substring is found. } - break; + break; // Exit the inner loop once a valid substring is found. } } - subString = '' + subString = ''; // Reset the current substring for the next iteration. } - return mLen + + return mLen; // Return the length of the shortest valid substring. } -console.log(shortestSubstring('bcaacbc')) +console.log(shortestSubstring('bcaacbc')); // Example usage of the function. From f10559c47cb7d5dc3b3106065673d1b9647d7db7 Mon Sep 17 00:00:00 2001 From: Mrical Singhal <60258119+mrical@users.noreply.github.com> Date: Fri, 3 Nov 2023 21:14:59 +0530 Subject: [PATCH 10/13] add colorUtils.js to Snippets/Objects/ (#129) --- Snippets/Objects/colorUtils.js | 103 +++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 Snippets/Objects/colorUtils.js diff --git a/Snippets/Objects/colorUtils.js b/Snippets/Objects/colorUtils.js new file mode 100644 index 0000000..13ca9d4 --- /dev/null +++ b/Snippets/Objects/colorUtils.js @@ -0,0 +1,103 @@ +class ColorUtils { + constructor(r, g, b) { + this.r = r; + this.g = g; + this.b = b; + } + + getRGB() { + return `rgb(${this.r}, ${this.g}, ${this.b})`; + } + + getHSL() { + const hsl = this.rgbToHsl(this.r, this.g, this.b); + return `hsl(${hsl[0]}, ${hsl[1]}%, ${hsl[2]}%)`; + } + + getHexCode() { + return `#${this.componentToHex(this.r)}${this.componentToHex( + this.g + )}${this.componentToHex(this.b)}`; + } + + getOppositeColor() { + return new ColorUtils(255 - this.r, 255 - this.g, 255 - this.b); + } + + brightenColor(percent) { + const factor = 1 + percent / 100; + const brightenedR = this.clamp(this.r * factor); + const brightenedG = this.clamp(this.g * factor); + const brightenedB = this.clamp(this.b * factor); + return new ColorUtils(brightenedR, brightenedG, brightenedB); + } + + lightenColor(percent) { + const factor = 1 + percent / 100; + const lightenedR = this.clamp(this.r + (255 - this.r) * (1 - factor)); + const lightenedG = this.clamp(this.g + (255 - this.g) * (1 - factor)); + const lightenedB = this.clamp(this.b + (255 - this.b) * (1 - factor)); + return new ColorUtils(lightenedR, lightenedG, lightenedB); + } + + rgbToHsl(r, g, b) { + r /= 255; + g /= 255; + b /= 255; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + let h, + s, + l = (max + min) / 2; + + if (max === min) { + h = s = 0; // achromatic + } else { + const d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + + h = Math.round(h * 360); + s = Math.round(s * 100); + l = Math.round(l * 100); + + return [h, s, l]; + } + + componentToHex(c) { + const hex = c.toString(16); + return hex.length === 1 ? "0" + hex : hex; + } + + clamp(value) { + return Math.min(255, Math.max(0, value)); + } +} + +// Example usage: +const color = new ColorUtils(100, 150, 200); + +console.log(color.getRGB()); // "rgb(100, 150, 200)" +console.log(color.getHSL()); // "hsl(210, 50%, 60%)" +console.log(color.getHexCode()); // "#6496c8" + +const oppositeColor = color.getOppositeColor(); +console.log(oppositeColor.getRGB()); // "rgb(155, 105, 55)" + +const brightenedColor = color.brightenColor(20); +console.log(brightenedColor.getRGB()); // "rgb(120, 180, 240)" + +const lightenedColor = color.lightenColor(20); +console.log(lightenedColor.getRGB()); // "rgb(124, 172, 216)" From f021f2ef675514c681c7387a480c16c87397dc8a Mon Sep 17 00:00:00 2001 From: JayeshYadav99 Date: Fri, 3 Nov 2023 21:16:09 +0530 Subject: [PATCH 11/13] docs: Enhance explanation of closures in JavaScript (#103) --- NamasteJS/E10 - Closures in JS.md | 99 +++++++++++++------------------ 1 file changed, 41 insertions(+), 58 deletions(-) diff --git a/NamasteJS/E10 - Closures in JS.md b/NamasteJS/E10 - Closures in JS.md index 10ecf2c..e410bfb 100644 --- a/NamasteJS/E10 - Closures in JS.md +++ b/NamasteJS/E10 - Closures in JS.md @@ -1,75 +1,57 @@ -# [Episode 10](https://www.youtube.com/watch?v=lW_erSjyMeM&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=12): Closures in JS 🔥 -* Closure: A function bind together with its lexical environment. -Function along with its lexical scope forms a closure. +--- -Function bundled along with the environment. +# [Episode 10](https://www.youtube.com/watch?v=lW_erSjyMeM&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=12): Closures in JavaScript 🔥 -```js -Example 1 +In JavaScript, closures are a powerful concept that combines a function with its lexical environment, enabling the function to retain access to variables from its parent scope even after the parent function has finished executing. + +## Understanding Closures -function x(){ - var a=7; - function y(){ +Let's delve into a few examples to understand how closures work: + +**Example 1:** +```js +function x() { + var a = 7; + function y() { console.log(a); } return y; } var z = x(); -console.log(z); -z(); +console.log(z); // Output: f y(){ console.log(a); } +z(); // Output: 7 ``` -Output: ->f y(){ - console.log(a); -} ->7 - -### Observation - -Function x() returns a `function y` which prints `variable a` on the console. Here, `a` is not in scope of y() and so the JS engine will search for `a` in its parent's lexical environment. Here, `a` is defined equal to `7`. - -Here after the line `var z = x()` the function x is over and thus it is completely removed from the execution context. - -But now when we call `z()`, given that `x()` is completely gone from the context, what should it print? - -It prints `7`. This means that `x()` didn't return `function y` but a closure. Since closure is a `function` + `its lexical env`, when `z()` is called, it remembers its lexical environment and thus prints `7`. - -Thus, `Closure` is nothing but a function + lexical environment(it has reference of values of vars and funcs). +In this example, the inner function `y` maintains a reference to the variable `a` from its lexical scope. Even though the outer function `x` has completed execution, `z` still prints `7` when invoked, demonstrating how the closure retains the environment. +**Example 2:** ```js -Example 2 - -function x(){ - var a=7; - function y(){ +function x() { + var a = 7; + function y() { console.log(a); } - a=100; + a = 100; return y; } var z = x(); -console.log(z); -z(); +console.log(z); // Output: f y(){ console.log(a); } +z(); // Output: 100 ``` -Output: ->f y(){ - console.log(a); -} ->100 +Here, even after the value of `a` is changed to `100`, the closure retains the updated value when invoked through `z()`. +**Example 3:** ```js -Example 3 -function z(){ +function z() { var b = 900; - function x(){ - var a=7; - function y(){ + function x() { + var a = 7; + function y() { console.log(a, b); } return y; @@ -77,20 +59,21 @@ function z(){ } var t = x(); -t(); +t(); // Output: 7 900 ``` -Output: ->7 900 +This example highlights how closures encapsulate the lexical environments of all parent levels. + +## Applications of Closures + +Closures find application in various programming scenarios: -Above example shows that Closure bundles the lexical environment of all the parent levels. +- **Module Design Pattern**: Closures help create private variables and methods in JavaScript, facilitating the module design pattern. +- **Currying**: Closures enable the creation of curried functions, allowing the transformation of functions with multiple arguments into a sequence of functions with a single argument. +- **Memoization**: Closures can be used to implement memoization, a technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again. +- **Asynchronous State Management**: Closures aid in maintaining state in asynchronous programming, enabling functions to access their lexical environment even after the parent function has completed execution. +- **Timeouts and Iterators**: Closures are instrumental in scenarios such as managing timeouts and creating custom iterators. -### Applications of Closures +Understanding closures is crucial for harnessing the full power of JavaScript and developing efficient and robust applications. -- Module Design Pattern -- Currying -- Functions like `once` -- Memoize -- Maintaining state in `async` world -- Set timeout -- Iterators etc. +--- From 66ac2c7b496fd71f672f47724424aeb69cb3a807 Mon Sep 17 00:00:00 2001 From: Dainik Bheda <107639433+dainik10@users.noreply.github.com> Date: Fri, 3 Nov 2023 21:16:45 +0530 Subject: [PATCH 12/13] Maximum Subarray Updated (#111) * Maximum Subarray Updated * Created Insertion Sort as Insertionsort.js file --- DSA/Arrays/Insertionsort.js | 12 ++++++++++++ DSA/Arrays/Maximumsubarray.js | 30 ++++++++++++++++++------------ 2 files changed, 30 insertions(+), 12 deletions(-) create mode 100644 DSA/Arrays/Insertionsort.js diff --git a/DSA/Arrays/Insertionsort.js b/DSA/Arrays/Insertionsort.js new file mode 100644 index 0000000..6fdfe9d --- /dev/null +++ b/DSA/Arrays/Insertionsort.js @@ -0,0 +1,12 @@ +function insertionSort(arr) { + for (let i = 1; i < arr.length; i++) { + let currentValue = arr[i] + let j + for (j = i - 1; j >= 0 && arr[j] > currentValue; j--) { + arr[j + 1] = arr[j] + } + arr[j + 1] = currentValue + } + return arr +} +console.log(insertionSort([2, 1, 3, 7, 5])) // [1, 2, 3, 5, 7] \ No newline at end of file diff --git a/DSA/Arrays/Maximumsubarray.js b/DSA/Arrays/Maximumsubarray.js index fc2247e..f3a7a8b 100644 --- a/DSA/Arrays/Maximumsubarray.js +++ b/DSA/Arrays/Maximumsubarray.js @@ -1,12 +1,18 @@ -var maxSubArray = function(nums) { - var prev = 0; - var max = -Infinity; - - for (var i = 0; i < nums.length; i++) { - // Compare previous contiguous sum with current number - prev = Math.max(prev + nums[i], nums[i]); - // Check if the current prev is the greatest sum - max = Math.max(max, prev); - } - return max; -}; +const maxSubArray = (nums) => { + // initiate two variable, maxSum for total max, sum for current max + let maxSum = -Infinity + let currentSum = 0 + // iterate through the nums, store sub-problems result + for(let i = 0; i < nums.length; i++){ + //cumulating answers to the top + + //compare currentSum add current number + //with current number and store the maximum value + currentSum = Math.max(nums[i], currentSum + nums[i]) + + //compare maxSum with currentSum and store the greater value + maxSum = Math.max(currentSum, maxSum) + + } + return maxSum +} \ No newline at end of file From e84b5073380555bfe967de95f590c124f65b4f31 Mon Sep 17 00:00:00 2001 From: Manav Gadhiya <94619028+Manav2808@users.noreply.github.com> Date: Fri, 3 Nov 2023 21:21:26 +0530 Subject: [PATCH 13/13] sentence changed in DSA Scripts (#108) --- DSA/Strings/Capitalize.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/DSA/Strings/Capitalize.js b/DSA/Strings/Capitalize.js index 86968fc..0333a33 100644 --- a/DSA/Strings/Capitalize.js +++ b/DSA/Strings/Capitalize.js @@ -1,16 +1,16 @@ // Convert a sentence to title case using Javascript // example: Input: this is a phrase // Output: This Is A Phrase - -const toTitleCase = (sentence) =>{ + +const toTitleCase = (sentence) => { let words = sentence.split(' '); - let capitalizedSentence=''; - words.forEach((word)=>{ + let capitalizedSentence = ''; + words.forEach((word) => { capitalizedSentence += String(word).charAt(0).toUpperCase() + word.slice(1) + ' '; }) - + return capitalizedSentence.trim(); } -const sentence = 'this is a phrase' +const sentence = 'this is a sentence' console.log(toTitleCase(sentence)); \ No newline at end of file