├── .gitignore ├── CONTRIBUTING.md ├── DSA ├── Arrays │ ├── BubbleSort.js │ ├── BucketSort.js │ ├── Maximumsubarray.js │ ├── RadixSort.js │ ├── SelectionSort.js │ └── SpecialArrayWithXElementsGreaterThanEqualToX.js ├── BFS │ └── waterJug.js ├── BinarySearch │ ├── FindFirstAndLastPositionInASortedArray.js │ ├── Sqrtx.js │ ├── findElementInRotatedSortedArray.js │ ├── firstBadVersion.js │ ├── guessNumber.js │ ├── minimumDifferenceElementInSortedArray.js │ └── searchInsertPosition.js ├── DFS │ ├── BinaryTreePaths.js │ ├── Diameter of Binary Tree │ ├── Find Mode in Binary Search Tree.js │ ├── InvertBinaryTree.js │ ├── KthSmallestElementInABST.js │ ├── LowestCommonAncestorOfABinarySearchTree.js │ ├── SameTree.js │ ├── SymmetricTree.js │ ├── lowest-common-ancestor-of-a-binary-tree.js │ ├── maximumSumDownAMatrix.js │ ├── minimum-distance-between-bst-nodes.js │ └── validateBinaryTree.js ├── Graphs │ ├── DijkstraAlgorithm.js │ ├── Kruskal Algorithm │ ├── Maze.js │ ├── Prim'sAlgorithm.js │ └── Travelling Salesman Problem │ │ ├── AntColonyOptimization.js │ │ ├── BranchAndBound.js │ │ ├── BruteForce.js │ │ ├── ChristofidesAlgorithm.js │ │ ├── DynamicProgramingBitmask.js │ │ ├── Dynamic_programming.js │ │ ├── GeneticAlgorithm.js │ │ ├── HeuristicApproach.js │ │ ├── IntegerLinearProgramming.js │ │ ├── IterativeImprovement(Heuristic).js │ │ ├── Lin-Kernighan.js │ │ ├── NearestNeighborAlgorithm.js │ │ ├── README.md │ │ └── SimulatedAnnealing.js ├── Miscelleneous │ ├── SmallestCommonMultiple.js │ └── mark_and_sweep.js └── Strings │ ├── Capitalize.js │ └── ShortestSubstring.js ├── EloquentJS ├── Notes │ └── HOF.md └── Snippets │ └── HOF │ ├── everything.js │ ├── flattenArray.js │ ├── hofFromScratch.js │ └── yourOwnLoop.js ├── InterviewQuestions ├── README.md ├── customBind.js ├── customList.js ├── debounce.js ├── findSecondLargestElementInArray.js ├── flattenArray.js ├── sumFunction.js └── throttle.js ├── JavaScript Challenges └── Javascript 30 │ ├── Day01 │ ├── bg.jpg │ ├── index.html │ └── sounds │ │ └── claps.wav │ ├── Day02 │ └── index.html │ ├── Day03 │ ├── index.html │ └── paris.jpg │ ├── Day04 │ └── index.html │ ├── Day05 │ └── index.html │ ├── Day06 │ └── index.html │ ├── Day07 │ └── index.js │ ├── Day08 │ └── index.html │ ├── Day09 │ └── index.html │ ├── Day10 │ └── index.html │ ├── Day11 │ ├── index.html │ ├── index.js │ ├── style.css │ └── vid.mp4 │ ├── Day12 │ └── index.html │ ├── Day13 │ └── index.html │ ├── Day14 │ └── index.html │ ├── Day15 │ ├── bg.jpeg │ ├── index.html │ ├── style.css │ └── try.html │ ├── Day16 │ └── index.html │ ├── Day17 │ └── index.html │ ├── Day18 │ └── index.html │ ├── Day19 │ ├── index.html │ ├── scripts.js │ ├── snap.mp3 │ └── style.css │ ├── Day20 │ └── index.html │ ├── Day21 │ ├── index.html │ ├── package-lock.json │ └── package.json │ ├── Day22 │ └── index.html │ ├── Day23 │ └── index.html │ ├── Day24 │ └── index.html │ ├── Day25 │ └── index.html │ ├── Day26 │ ├── index.html │ └── logo.jpg │ ├── Day27 │ ├── index.html │ └── style.css │ ├── Day28 │ └── index.html │ ├── Day29 │ ├── index.html │ ├── script.js │ └── style.css │ ├── Day30 │ ├── dirt.svg │ ├── index.html │ ├── mole.svg │ ├── script.js │ └── styles.css │ ├── Day31 │ └── index.html │ └── readme.md ├── NamasteJS ├── E01 - How JavaScript Works & Execution Context.md ├── E02 - How is JavaScript Code executed & What is Call Stack.md ├── E03 - Hoisting in JavaScript (variables & functions).md ├── E04 - How functions work in JS & Variable Environment.md ├── E05 - SHORTEST JS Program - window & this keyword.md ├── E06 - undefined vs not defined in JS.md ├── E07 - The Scope Chain, Scope & Lexical Environment.md ├── E08 - let & const in JS - Temporal Dead Zone.md ├── E09 - BLOCK SCOPE & Shadowing in JS.md ├── E10 - Closures in JS.md ├── E11 - setTimeout + Closures Interview Question.md ├── E12 - CRAZY JS INTERVIEW - ft. Closures.md ├── E13 - FIRST CLASS FUNCTIONS - ft. Anonymous Functions.md ├── E14 - Callback Functions in JS ft. Event Listeners.md ├── E15 - Asynchronous JavaScript & EVENT LOOP from scratch.md ├── E16 - JS Engine EXPOSED - Google's V8 Architecture.md ├── E17 - TRUST ISSUES with setTimeout().md └── README.md ├── README.md ├── ReferenceBooks ├── (You Don't Know JS) Kyle Simpson - You Don't Know JS_ Async & Performance-O'Reilly Media (2015).pdf ├── (You Don't Know JS) Kyle Simpson - You Don't Know JS_ Scope & Closures-O'Reilly Media (2014).pdf ├── Daniel_Parker-JavaScript_with_Promises-EN.pdf ├── Eloquent JavaScript.pdf ├── JavaScript-The-Definitive-Guide-Master-The-Worlds-Most-Used-Programming-Language-7th-Edition.pdf ├── Kyle Simpson - You Don't Know JS_ Types & Grammar-O'Reilly Media (2015).pdf ├── Kyle Simpson - You Don't Know JS_ Up & Going-O'Reilly Media (2015).pdf ├── Kyle Simpson - You Don't Know JS_ this & Object Prototypes-O'Reilly Media (2014).pdf ├── web-dev-handbook.pdf └── you_dont_know_js_es6_beyond__PDFDrive_.pdf ├── SDE_Sheet ├── IntersectionOfTwoLinkedLists.js ├── LongestSubstringWithoutRepeatingCharacters.js ├── MiddleOfTheLinkedList.js ├── ReverseLinkedList.js ├── findDuplicate.js ├── mergeIntervals.js ├── mergeTwoSortedArrays.js ├── nextPermutation.js ├── pascalTriangle.js ├── setMatrixZeros.js ├── sortColors.js ├── stocksBuyAndSell.js └── twoSum.js └── Snippets ├── Arrays ├── arraySubset.js ├── atPolyfill.js ├── checkItemPresentInArray.js ├── checkItemPresentInArrayUsingMethod.js ├── checkPositionOfElementInArray.js ├── convertArrayToString.js ├── filterPolyfill.js ├── flattenADeeplyNestedArray.js ├── groupBy.js ├── mapPolyfill.js ├── pushPolyfill.js ├── reducePolyfill.js ├── removeDuplicates.js └── unshiftPolyfill.js ├── Async ├── Thanos.js ├── printAfterDelay.js └── setInterval.js ├── Closures ├── armyOfFunctions.js ├── filterThroughFunction.js ├── makeCounter.js └── sortByFields.js ├── Currying ├── advancedCurryImplementation.js └── sumOfNNumbers.js ├── DataTypes └── methodsOfPrimitives.js ├── FunctionalProgramming ├── General │ ├── arrayLength.js │ ├── charAt.js │ ├── findMax.js │ ├── findMin.js │ ├── hexagonArea.js │ ├── indexOf.js │ ├── mergeArray.js │ ├── minDate.js │ ├── power.js │ ├── replace.js │ ├── reverseWords.js │ ├── secretCode.js │ ├── toSentenceCase.js │ ├── triangleType.js │ └── wordCounter.js └── HigherOrderFunctions │ ├── README.md │ └── TheOne.js ├── Functions ├── bind.js ├── bindAll.js ├── boundFunctionMethod.js ├── call.js ├── customSetInterval.js ├── debounceDecorator.js ├── delayDecorator.js ├── fixFunctionThis.js ├── globalPartialFunctions.js ├── makeCounter.js ├── memoizeOne.js ├── multiArgumentCaching.js ├── namedFunctionExpression.js ├── nestedSetTimeout.js ├── newFunctionSyntax.js ├── outputEverySecond.js ├── partialFunctions.js ├── partialLogin.js ├── polymorphism.js ├── properties.js ├── secondBind.js ├── setInterval.js ├── setTimeout.js ├── spyDecorator.js ├── sumWithArbitaryAmountOfBrackets.js ├── throttleDecorator.js ├── timeBomb.js └── transparentCaching.js ├── Objects ├── accumulator.js ├── bindPolyFill.js ├── calculator.js ├── cloneObject.js ├── computedProperties.js ├── deepCopy.js ├── immediatelyCalledConstructorFunction.js ├── isEmpty.js ├── ladder.js ├── methodsAndthis.js ├── multiplyNumeric.js ├── objectToPrimitiveConversion.js ├── orderedLikeObject.js ├── propertyDescriptors.js ├── propertyGetterSetter.js ├── reference.js └── restAndspread.js ├── Polyfill ├── bind-polyfill.js ├── filter-polyfill.js ├── forEach-polyfill.js ├── map-polyfill.js ├── promiseAll-polyfill.js └── reduce-polyfill.js ├── Promises ├── asyncAwait.js ├── callAsyncFromNonAsync.js ├── microtask.js ├── noNeedToReturnPromiseInThenChain.js ├── promiseAPI.js ├── promiseAll.js ├── promiseAllSettled.js ├── promiseAny.js ├── promiseRace.js ├── resolveVsReturn.js ├── retryNTimes.js ├── throwingErrorOutsidePromiseChain.js └── tryCatch.js ├── Prototype ├── basic.js ├── forInLoop.js ├── getAndset.js ├── nativePrototypes.js ├── prototype.js ├── searchingAlgorithm.js ├── this.js └── whyAreBothHamstersFull.js ├── Recursion ├── factorial.js ├── fibonacci.js ├── linkedList.js ├── power.js ├── recursiveTraversal.js └── sumTo.js └── Strings ├── charCount.js ├── lowerCaseConverter.js ├── removeSpaces.js ├── repeat.js ├── replaceString.js ├── search.js ├── substrings.js ├── trim.js └── upperCaseConverter.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ -------------------------------------------------------------------------------- /DSA/Arrays/BubbleSort.js: -------------------------------------------------------------------------------- 1 | // Bubble sort Implementation using Javascript 2 | 3 | function bblSort(arr){ 4 | 5 | // loop through array 6 | for(var i = 0; i < arr.length; i++){ 7 | 8 | for(var j = 0; j < ( arr.length - i -1 ); j++){ 9 | 10 | if(arr[j] > arr[j+1]){ 11 | 12 | // creates a temp array 13 | var temp = arr[j] 14 | arr[j] = arr[j + 1] 15 | arr[j+1] = temp 16 | } 17 | } 18 | } 19 | console.log(arr); 20 | } 21 | 22 | var arr = [234, 43, 55, 63, 5, 6, 235, 547]; 23 | 24 | // call the function 25 | bblSort(arr); -------------------------------------------------------------------------------- /DSA/Arrays/BucketSort.js: -------------------------------------------------------------------------------- 1 | const arr = [5, 3, 1, 2, 4, 7, 6]; 2 | const bucketSort = (arr) => { 3 | if (arr.length === 0) { 4 | return arr; 5 | } 6 | let i, 7 | minValue = arr[0], 8 | maxValue = arr[0], 9 | bucketSize = 5; 10 | arr.forEach(function (currentVal) { 11 | if (currentVal < minValue) { 12 | minValue = currentVal; 13 | } else if (currentVal > maxValue) { 14 | maxValue = currentVal; 15 | } 16 | }); 17 | let bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1; 18 | let allBuckets = new Array(bucketCount); 19 | for (i = 0; i < allBuckets.length; i++) { 20 | allBuckets[i] = []; 21 | } 22 | arr.forEach(function (currentVal) { 23 | allBuckets[Math.floor((currentVal - minValue) / bucketSize)].push( 24 | currentVal 25 | ); 26 | }); 27 | arr.length = 0; 28 | allBuckets.forEach(function (bucket) { 29 | insertion(bucket); 30 | bucket.forEach(function (element) { 31 | arr.push(element); 32 | }); 33 | }); 34 | return arr; 35 | }; 36 | const insertion = (arr) => { 37 | let length = arr.length; 38 | let i, j; 39 | for (i = 1; i < length; i++) { 40 | let temp = arr[i]; 41 | for (j = i - 1; j >= 0 && arr[j] > temp; j--) { 42 | arr[j + 1] = arr[j]; 43 | } 44 | arr[j + 1] = temp; 45 | } 46 | return arr; 47 | }; 48 | console.log(bucketSort(arr)); 49 | -------------------------------------------------------------------------------- /DSA/Arrays/Maximumsubarray.js: -------------------------------------------------------------------------------- 1 | var maxSubArray = function(nums) { 2 | var prev = 0; 3 | var max = -Infinity; 4 | 5 | for (var i = 0; i < nums.length; i++) { 6 | // Compare previous contiguous sum with current number 7 | prev = Math.max(prev + nums[i], nums[i]); 8 | // Check if the current prev is the greatest sum 9 | max = Math.max(max, prev); 10 | } 11 | return max; 12 | }; 13 | -------------------------------------------------------------------------------- /DSA/Arrays/RadixSort.js: -------------------------------------------------------------------------------- 1 | const arr = [121, 432, 564, 23, 1, 45, 788]; 2 | const countingSort = (arr, size, place) => { 3 | 4 | let output = new Array(size + 1).fill(0); 5 | let max = Math.max(...arr); 6 | 7 | let freq = new Array(max + 1).fill(0); 8 | 9 | 10 | for (let i = 0; i < size; i++){ 11 | const num = Math.floor(arr[i] / place) % 10; 12 | freq[num]++; 13 | } 14 | 15 | 16 | for (let i = 1; i < 10; i++){ 17 | freq[i] += freq[i - 1]; 18 | } 19 | 20 | 21 | for (let i = size - 1; i >= 0; i--) { 22 | const num = Math.floor(arr[i] / place) % 10; 23 | output[freq[num] - 1] = arr[i]; 24 | freq[num]--; 25 | } 26 | 27 | 28 | for (let i = 0; i < size; i++){ 29 | arr[i] = output[i]; 30 | } 31 | } 32 | 33 | const radixSort = (arr, size = arr.length) => { 34 | 35 | let max = Math.max(...arr); 36 | 37 | 38 | for(let i = 1; parseInt(max / i) > 0; i *= 10){ 39 | countingSort(arr, size, i); 40 | } 41 | } 42 | radixSort(arr); 43 | console.log(arr); -------------------------------------------------------------------------------- /DSA/Arrays/SelectionSort.js: -------------------------------------------------------------------------------- 1 | function selectionSort(arr) { 2 | 3 | for (let i = 0; i < arr.length - 1; i++) { 4 | let min_index = i; 5 | for (let j = i + 1; j < arr.length; j++) { 6 | if (arr[j] > arr[min_index]) { 7 | min_index = j; 8 | } 9 | } 10 | let temp = arr[min_index] 11 | arr[min_index] = arr[i] 12 | arr[i] = temp; 13 | } 14 | return arr 15 | } 16 | 17 | let arr = [4, 12, 10, 15, 2] 18 | console.log(selectionSort(arr)) -------------------------------------------------------------------------------- /DSA/Arrays/SpecialArrayWithXElementsGreaterThanEqualToX.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var specialArray = function(nums) { 6 | for(let i=0; i<=nums.length; i++){ 7 | let count = 0; 8 | for(let j=0; j= i){ 10 | count++ 11 | } 12 | } 13 | if(count === i){ 14 | return i 15 | } 16 | } 17 | return -1 18 | 19 | }; -------------------------------------------------------------------------------- /DSA/BinarySearch/FindFirstAndLastPositionInASortedArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number[]} 5 | */ 6 | var searchRange = function(arr, target) { 7 | let firstPosition = -1; 8 | let lastPosition = -1; 9 | 10 | let start = 0; 11 | let end = arr.length - 1; 12 | let mid; 13 | 14 | while(start <= end){ 15 | mid = end - parseInt((end - start)/2) 16 | if(arr[mid] === target){ 17 | firstPosition = mid; 18 | end = mid - 1 19 | }else if (arr[mid] < target){ 20 | start = mid + 1 21 | }else{ 22 | end = mid - 1 23 | } 24 | } 25 | start = 0; 26 | end = arr.length - 1; 27 | 28 | while(start <= end){ 29 | mid = end - parseInt((end - start)/2) 30 | if(arr[mid] === target){ 31 | lastPosition = mid; 32 | start = mid + 1 33 | }else if (arr[mid] < target){ 34 | start = mid + 1 35 | }else{ 36 | end = mid - 1 37 | } 38 | } 39 | return [firstPosition, lastPosition] 40 | 41 | }; -------------------------------------------------------------------------------- /DSA/BinarySearch/Sqrtx.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} x 3 | * @return {number} 4 | */ 5 | var mySqrt = function(x) { 6 | let start = 1; 7 | let end = x; 8 | let mid; 9 | let res = 0 10 | 11 | while(start <= end){ 12 | mid = end - parseInt((end - start)/2) 13 | console.log(mid) 14 | if(mid*mid <= x){ 15 | res = mid; 16 | start = mid + 1 17 | }else{ 18 | end = mid - 1; 19 | } 20 | } 21 | return res 22 | 23 | 24 | }; -------------------------------------------------------------------------------- /DSA/BinarySearch/findElementInRotatedSortedArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number} 5 | */ 6 | var search = function(nums, target) { 7 | function binarySearch(arr, start, end, target){ 8 | let mid; 9 | while(start <= end){ 10 | mid = end - parseInt((end - start)/2) 11 | if(arr[mid] === target){ 12 | return mid; 13 | }else if(arr[mid] < target){ 14 | start = mid + 1 15 | }else{ 16 | end = mid - 1 17 | } 18 | } 19 | return -1 20 | } 21 | function findMin(arr){ 22 | let start = 0; 23 | let end = arr.length-1 24 | let N = arr.length; 25 | let res = -1; 26 | 27 | while(start <= end){ 28 | if(arr[start] <= arr[end]){ 29 | return start; 30 | } 31 | mid = end - parseInt((end-start)/2) 32 | if(arr[mid] <= arr[(mid+1) % N] && arr[mid] <= arr[(mid+ N -1)%N]) { 33 | res = mid; 34 | break; 35 | } 36 | if(arr[mid] >= arr[start]){ 37 | start = mid + 1 38 | } else if (arr[mid] <= arr[end]){ 39 | end = mid - 1 40 | } 41 | } 42 | return res 43 | } 44 | 45 | let minimumIndex = findMin(nums); 46 | 47 | 48 | let res1 = binarySearch(nums, minimumIndex, nums.length, target); 49 | let res2 = binarySearch(nums, 0, minimumIndex - 1, target); 50 | 51 | if(res1 !== -1){ 52 | return res1; 53 | } 54 | return res2 55 | }; 56 | 57 | // cool stuff -------------------------------------------------------------------------------- /DSA/BinarySearch/firstBadVersion.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for isBadVersion() 3 | * 4 | * @param {integer} version number 5 | * @return {boolean} whether the version is bad 6 | * isBadVersion = function(version) { 7 | * ... 8 | * }; 9 | */ 10 | 11 | /** 12 | * @param {function} isBadVersion() 13 | * @return {function} 14 | */ 15 | var solution = function(isBadVersion) { 16 | /** 17 | * @param {integer} n Total versions 18 | * @return {integer} The first bad version 19 | */ 20 | return function(n) { 21 | let start = 1; 22 | let end = n; 23 | let mid; 24 | let res = -1; 25 | while(start <= end){ 26 | mid = end - parseInt((end - start)/2) 27 | if(isBadVersion(mid)){ 28 | res = mid; 29 | end = mid - 1; 30 | }else{ 31 | start = mid + 1; 32 | } 33 | } 34 | return res 35 | }; 36 | }; -------------------------------------------------------------------------------- /DSA/BinarySearch/guessNumber.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Forward declaration of guess API. 3 | * @param {number} num your guess 4 | * @return -1 if num is lower than the guess number 5 | * 1 if num is higher than the guess number 6 | * otherwise return 0 7 | * var guess = function(num) {} 8 | */ 9 | 10 | /** 11 | * @param {number} n 12 | * @return {number} 13 | */ 14 | var guessNumber = function(n) { 15 | let start = 1; 16 | let end = n; 17 | let mid; 18 | 19 | while(start <= end){ 20 | mid = end - parseInt((end - start)/2) 21 | if(guess(mid) === 0){ 22 | return mid 23 | }else if(guess(mid) === -1){ 24 | end = mid - 1; 25 | }else{ 26 | start = mid + 1 27 | } 28 | } 29 | }; -------------------------------------------------------------------------------- /DSA/BinarySearch/minimumDifferenceElementInSortedArray.js: -------------------------------------------------------------------------------- 1 | function minimumDifference(arr, target){ 2 | let start = 0; 3 | let end = arr.length - 1; 4 | let mid; 5 | while(start <= end){ 6 | mid = end - parseInt((end-start)/2) 7 | if(arr[mid] === target){ 8 | return arr[mid]; 9 | } 10 | else if(arr[mid] < target){ 11 | start = mid + 1 12 | }else{ 13 | end = mid - 1 14 | } 15 | } 16 | return Math.min(Math.abs(arr[start] - target), Math.abs(arr[end] - target)) 17 | } -------------------------------------------------------------------------------- /DSA/BinarySearch/searchInsertPosition.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number} 5 | */ 6 | var searchInsert = function(nums, target) { 7 | let start = 0; 8 | let end = nums.length - 1; 9 | let mid; 10 | let res = nums.length; 11 | while(start <= end){ 12 | mid = end - parseInt((end - start)/2) 13 | if(nums[mid] === target){ 14 | return mid 15 | }else if(nums[mid] > target){ 16 | res = mid; 17 | end = mid - 1; 18 | }else{ 19 | start = mid + 1; 20 | } 21 | } 22 | return res; 23 | 24 | }; -------------------------------------------------------------------------------- /DSA/DFS/BinaryTreePaths.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | var binaryTreePaths = function(root) { 10 | let allAr = []; 11 | getPath(root); 12 | function getPath(node,arr=[]){ 13 | (!node.left && !node.right) &&allAr.push([...arr, node.val]); 14 | node.left && getPath(node.left, [...arr,node.val]); 15 | node.right && getPath(node.right, [...arr,node.val]); 16 | } 17 | return allAr.map((a)=>a.join('->')); 18 | }; 19 | -------------------------------------------------------------------------------- /DSA/DFS/Diameter of Binary Tree: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | var diameterOfBinaryTree = function(root) { 10 | let result = 0; 11 | helper(root); 12 | return result 13 | 14 | function helper(root){ 15 | if(!root)return 0; 16 | 17 | let left = helper(root.left); 18 | let right = helper(root.right); 19 | 20 | result = Math.max(left + right , result); 21 | 22 | return 1 + Math.max(left, right) 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /DSA/DFS/Find Mode in Binary Search Tree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | var findMode = function(r) { 10 | const map = new Map() 11 | const maxMap = new Map() 12 | let max = -Infinity 13 | 14 | function dfs(root){ 15 | if(!root) return 16 | map.set(root.val, (map.get(root.val) || 0) + 1) 17 | if(map.get(root.val) >= max){ 18 | max = map.get(root.val) 19 | if(!maxMap.get(max)) maxMap.set(max, new Set()) 20 | maxMap.get(max).add(root.val) 21 | } 22 | dfs(root.left) 23 | dfs(root.right) 24 | } 25 | 26 | dfs(r) 27 | return [...maxMap.get(max)] 28 | }; 29 | -------------------------------------------------------------------------------- /DSA/DFS/InvertBinaryTree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | 10 | var invertTree = function(root) { 11 | if(!root) { 12 | return null; 13 | } 14 | [root.left, root.right] = [invertTree(root.right), invertTree(root.left)]; 15 | return root; 16 | }; 17 | -------------------------------------------------------------------------------- /DSA/DFS/KthSmallestElementInABST.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | var kthSmallest = function(root, k) { 10 | let arrayOfElements = [] 11 | 12 | function dfs(node) { 13 | if(!node) return; 14 | 15 | dfs(node.left); 16 | arrayOfElements.push(node.val); 17 | dfs(node.right); 18 | } 19 | dfs(root); 20 | return arrayOfElements[k - 1]; 21 | }; 22 | -------------------------------------------------------------------------------- /DSA/DFS/LowestCommonAncestorOfABinarySearchTree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val) { 4 | * this.val = val; 5 | * this.left = this.right = null; 6 | * } 7 | */ 8 | var lowestCommonAncestor = function(root, p, q) { 9 | 10 | let ansNode = null 11 | if(p.val == root.val || q.val == root.val){ 12 | return root 13 | } 14 | function traverse(node){ 15 | if((p.val < node.val && q.val > node.val) || (p.val > node.val && q.val < node.val)){ 16 | ansNode = node 17 | return 18 | } 19 | else if(p.val == node.val || q.val == node.val){ 20 | ansNode = node 21 | return 22 | } 23 | if(node.left) 24 | traverse(node.left) 25 | if(node.right) 26 | traverse(node.right) 27 | } 28 | 29 | if((p.val < root.val && q.val > root.val) || (p.val > root.val && q.val < root.val)) 30 | return root 31 | else if(p.val > root.val && q.val > root.val) 32 | traverse(root.right) 33 | else if(p.val < root.val && q.val < root.val) 34 | traverse(root.left) 35 | 36 | return ansNode 37 | }; 38 | -------------------------------------------------------------------------------- /DSA/DFS/SameTree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | var isSameTree = function(p, q) { 10 | return is_tree_equal(p, q); 11 | function is_tree_equal(tree1, tree2){ 12 | if (tree1 === null && tree2 === null) return true; 13 | if (tree1 === null || tree2 === null) return false; 14 | if (tree1.val !== tree2.val) return false; 15 | 16 | const is_left_tree_equal = is_tree_equal(tree1.left, tree2.left) 17 | const is_right_tree_equal = is_tree_equal(tree1.right, tree2.right) 18 | return is_left_tree_equal && is_right_tree_equal 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /DSA/DFS/SymmetricTree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | var isSymmetric = function(root) { 10 | if(!root.left && !root.right) 11 | return true 12 | if((root.left && !root.right) || (!root.left && root.right)) 13 | return false 14 | let ans = true 15 | function traverse(nodeL,nodeR){ 16 | if(nodeL.val != nodeR.val) 17 | ans = false 18 | if(nodeL.left && nodeR.right) 19 | traverse(nodeL.left,nodeR.right) 20 | else if((!nodeL.left && nodeR.right) || (nodeL.left && !nodeR.right)) 21 | ans = false 22 | if(nodeL.right && nodeR.left) 23 | traverse(nodeL.right, nodeR.left) 24 | else if((!nodeL.right && nodeR.left) || (nodeL.right && !nodeR.left)) 25 | ans = false 26 | } 27 | traverse(root.left,root.right) 28 | return ans 29 | }; 30 | -------------------------------------------------------------------------------- /DSA/DFS/lowest-common-ancestor-of-a-binary-tree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val) { 4 | * this.val = val; 5 | * this.left = this.right = null; 6 | * } 7 | */ 8 | var lowestCommonAncestor = function(root, p, q) { 9 | if(!root) { 10 | return null; 11 | } 12 | const left = lowestCommonAncestor(root.left, p, q), 13 | right = lowestCommonAncestor(root.right, p, q); 14 | if((left && right) || root.val === p.val || root.val === q.val) { 15 | return root; 16 | } 17 | else if(left) { 18 | return left; 19 | } 20 | else if(right) { 21 | return right; 22 | } 23 | return null; 24 | }; 25 | -------------------------------------------------------------------------------- /DSA/DFS/minimum-distance-between-bst-nodes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * function TreeNode(val, left, right) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.left = (left===undefined ? null : left) 6 | * this.right = (right===undefined ? null : right) 7 | * } 8 | */ 9 | var minDiffInBST = function(root) { 10 | let min = Number.MAX_VALUE 11 | let arr = [] 12 | function traverse(node){ 13 | if(node.left) 14 | traverse(node.left) 15 | arr.push(node.val) 16 | if(node.right) 17 | traverse(node.right) 18 | } 19 | traverse(root) 20 | for(let i = arr.length - 1 ; i > 0 ; i--){ 21 | if(arr[i] - arr[i-1] < min){ 22 | min = arr[i] - arr[i-1] 23 | } 24 | } 25 | return min 26 | }; 27 | -------------------------------------------------------------------------------- /DSA/DFS/validateBinaryTree.js: -------------------------------------------------------------------------------- 1 | var isValidBST = function (root) { 2 | 3 | 4 | function helper(node, min, max) { 5 | if (!node) return true; 6 | 7 | if (node.val <= min || node.val >= max) return false; 8 | 9 | let left = helper(node.left, min, node.val); 10 | let right = helper(node.right, node.val, max) 11 | 12 | return left && right 13 | 14 | } 15 | 16 | return helper(root, -Infinity, Infinity) 17 | }; -------------------------------------------------------------------------------- /DSA/Graphs/DijkstraAlgorithm.js: -------------------------------------------------------------------------------- 1 | const graphInfo = { 2 | source: {A: 4, B: 1}, 3 | A: {C: 3, D: 5}, 4 | B: {A: 7, D: 2}, 5 | C: {D: 4, destination: 3}, 6 | D: {destination: 2}, 7 | destination: {} 8 | }; 9 | 10 | // primary function 11 | const dijkstra = (graph) => { 12 | 13 | // shortest distance to each vertex 14 | const distance = Object.assign( 15 | {destination: Infinity}, graph.source); 16 | 17 | // display path 18 | const parentArray = {destination: null}; 19 | for (let child in graph.source) { 20 | parentArray[child] = 'source'; 21 | } 22 | 23 | // track vertexs that are marked 24 | const marked = []; 25 | 26 | let vertex = minimumDistancevertex(distance, marked); 27 | 28 | while (vertex) { 29 | let cost = distance[vertex]; 30 | let children = graph[vertex]; 31 | for (let n in children) { 32 | let latestDistance = cost + children[n]; 33 | if (!distance[n]) { 34 | distance[n] = latestDistance; 35 | parentArray[n] = vertex; 36 | } 37 | if (distance[n] > latestDistance) { 38 | distance[n] = latestDistance; 39 | parentArray[n] = vertex; 40 | } 41 | } 42 | marked.push(vertex); 43 | vertex = minimumDistancevertex(distance, marked); 44 | } 45 | 46 | let shortestPath = ['destination']; 47 | let parent = parentArray.destination; 48 | while (parent) { 49 | shortestPath.push(parent); 50 | parent = parentArray[parent]; 51 | } 52 | shortestPath.reverse(); 53 | 54 | const result = { 55 | distance: distance.destination, 56 | path: shortestPath 57 | }; 58 | 59 | return result; 60 | }; 61 | 62 | const minimumDistancevertex = (distance, marked) => { 63 | return Object.keys(distance).reduce((lowest, vertex) => { 64 | if (lowest === null || distance[vertex] < distance[lowest]) { 65 | if (!marked.includes(vertex)) { 66 | lowest = vertex; 67 | } 68 | } 69 | return lowest; 70 | }, null); 71 | }; 72 | 73 | console.log(dijkstra(graphInfo)); -------------------------------------------------------------------------------- /DSA/Graphs/Kruskal Algorithm: -------------------------------------------------------------------------------- 1 | class UnionFind { 2 | constructor(elements) { 3 | // Number of disconnected components 4 | this.count = elements.length; 5 | 6 | // Keep Track of connected components 7 | this.parent = {}; 8 | 9 | // Initialize the data structure such that all 10 | // elements have themselves as parents 11 | elements.forEach(e => (this.parent[e] = e)); 12 | } 13 | 14 | union(a, b) { 15 | let rootA = this.find(a); 16 | let rootB = this.find(b); 17 | 18 | // Roots are same so these are already connected. 19 | if (rootA === rootB) return; 20 | 21 | // Always make the element with smaller root the parent. 22 | if (rootA < rootB) { 23 | if (this.parent[b] != b) this.union(this.parent[b], a); 24 | this.parent[b] = this.parent[a]; 25 | } else { 26 | if (this.parent[a] != a) this.union(this.parent[a], b); 27 | this.parent[a] = this.parent[b]; 28 | } 29 | } 30 | 31 | // Returns final parent of a node 32 | find(a) { 33 | while (this.parent[a] !== a) { 34 | a = this.parent[a]; 35 | } 36 | return a; 37 | } 38 | 39 | // Checks connectivity of the 2 nodes 40 | connected(a, b) { 41 | return this.find(a) === this.find(b); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /DSA/Graphs/Prim'sAlgorithm.js: -------------------------------------------------------------------------------- 1 | primsMST() { 2 | // Initialize graph that'll contain the MST 3 | const MST = new Graph(); 4 | if (this.nodes.length === 0) { 5 | return MST; 6 | } 7 | 8 | 9 | // Select first node as starting node 10 | let s = this.nodes[0]; 11 | 12 | 13 | // Create a Priority Queue and explored set 14 | let edgeQueue = new PriorityQueue(this.nodes.length * this.nodes.length); 15 | let explored = new Set(); 16 | explored.add(s); 17 | MST.addNode(s); 18 | 19 | 20 | // Add all edges from this starting node to the PQ taking weights as priority 21 | this.edges[s].forEach(edge => { 22 | edgeQueue.enqueue([s, edge.node], edge.weight); 23 | }); 24 | 25 | 26 | // Take the smallest edge and add that to the new graph 27 | let currentMinEdge = edgeQueue.dequeue(); 28 | while (!edgeQueue.isEmpty()) { 29 | 30 | 31 | // Continue removing edges till we get an edge with an unexplored node 32 | while (!edgeQueue.isEmpty() && explored.has(currentMinEdge.data[1])) { 33 | currentMinEdge = edgeQueue.dequeue(); 34 | } 35 | let nextNode = currentMinEdge.data[1]; 36 | 37 | 38 | // Check again as queue might get empty without giving back unexplored element 39 | if (!explored.has(nextNode)) { 40 | MST.addNode(nextNode); 41 | MST.addEdge(currentMinEdge.data[0], nextNode, currentMinEdge.priority); 42 | // Again add all edges to the PQ 43 | this.edges[nextNode].forEach(edge => { 44 | edgeQueue.enqueue([nextNode, edge.node], edge.weight); 45 | }); 46 | 47 | 48 | // Mark this node as explored explored.add(nextNode); 49 | s = nextNode; 50 | } 51 | } 52 | return MST; 53 | } 54 | -------------------------------------------------------------------------------- /DSA/Graphs/Travelling Salesman Problem/BranchAndBound.js: -------------------------------------------------------------------------------- 1 | function tspBranchAndBound(cities, distances) { 2 | const n = cities.length; 3 | const visited = new Array(n).fill(false); 4 | visited[0] = true; 5 | const initialPath = [0]; 6 | const { order, distance } = branchAndBoundHelper(0, initialPath, 0, Infinity); 7 | 8 | function branchAndBoundHelper(currentCity, path, currentDistance, bestDistance) { 9 | if (path.length === n) { 10 | return { order: path, distance: currentDistance + distances[currentCity][0] }; 11 | } 12 | 13 | let minDistance = bestDistance; 14 | let minOrder = []; 15 | 16 | for (let nextCity = 0; nextCity < n; nextCity++) { 17 | if (!visited[nextCity]) { 18 | visited[nextCity] = true; 19 | const newPath = [...path, nextCity]; 20 | const newDistance = currentDistance + distances[currentCity][nextCity]; 21 | 22 | if (newDistance < minDistance) { 23 | const result = branchAndBoundHelper(nextCity, newPath, newDistance, minDistance); 24 | if (result.distance < minDistance) { 25 | minDistance = result.distance; 26 | minOrder = result.order; 27 | } 28 | } 29 | 30 | visited[nextCity] = false; 31 | } 32 | } 33 | 34 | return { order: minOrder, distance: minDistance }; 35 | } 36 | 37 | return { order, distance }; 38 | } 39 | 40 | // Test case 41 | const cities = ["A", "B", "C"]; 42 | const distances = [ 43 | [0, 10, 15], 44 | [10, 0, 20], 45 | [15, 20, 0], 46 | ]; 47 | 48 | const result = tspBranchAndBound(cities, distances); 49 | console.log("Branch and Bound Optimal Order:", result.order.map((idx) => cities[idx]).join(" -> ")); 50 | console.log("Branch and Bound Optimal Distance:", result.distance); 51 | -------------------------------------------------------------------------------- /DSA/Graphs/Travelling Salesman Problem/BruteForce.js: -------------------------------------------------------------------------------- 1 | function permute(arr) { 2 | if (arr.length === 0) return [[]]; 3 | const [first, ...rest] = arr; 4 | const permutationsWithoutFirst = permute(rest); 5 | return permutationsWithoutFirst.flatMap((perm) => 6 | perm.map((_, idx) => [...perm.slice(0, idx), first, ...perm.slice(idx)]) 7 | ); 8 | } 9 | 10 | function calculateTotalDistance(order, distances) { 11 | let totalDistance = 0; 12 | for (let i = 0; i < order.length - 1; i++) { 13 | totalDistance += distances[order[i]][order[i + 1]]; 14 | } 15 | return totalDistance; 16 | } 17 | 18 | function bruteForceTSP(cities, distances) { 19 | const cityIndices = Array.from({ length: cities.length }, (_, i) => i); 20 | const permutations = permute(cityIndices); 21 | let minDistance = Infinity; 22 | let bestOrder = []; 23 | 24 | for (const perm of permutations) { 25 | const distance = calculateTotalDistance(perm, distances); 26 | if (distance < minDistance) { 27 | minDistance = distance; 28 | bestOrder = perm; 29 | } 30 | } 31 | 32 | return { order: bestOrder, distance: minDistance }; 33 | } 34 | 35 | // Test case 36 | const cities = ["A", "B", "C"]; 37 | const distances = [ 38 | [0, 10, 15], 39 | [10, 0, 20], 40 | [15, 20, 0], 41 | ]; 42 | 43 | const result = bruteForceTSP(cities, distances); 44 | console.log("Optimal Order:", result.order.map((idx) => cities[idx]).join(" -> ")); 45 | console.log("Optimal Distance:", result.distance); -------------------------------------------------------------------------------- /DSA/Graphs/Travelling Salesman Problem/DynamicProgramingBitmask.js: -------------------------------------------------------------------------------- 1 | function tspDynamicProgrammingBitmask(cities, distances) { 2 | const n = cities.length; 3 | const memo = new Array(n).fill(null).map(() => new Array(1 << n).fill(null)); 4 | 5 | function dp(node, bitmask) { 6 | if (bitmask === (1 << n) - 1) { 7 | return distances[node][0]; 8 | } 9 | 10 | if (memo[node][bitmask] !== null) { 11 | return memo[node][bitmask]; 12 | } 13 | 14 | let minDistance = Infinity; 15 | for (let nextNode = 0; nextNode < n; nextNode++) { 16 | if ((bitmask & (1 << nextNode)) === 0) { 17 | const newDistance = distances[node][nextNode] + dp(nextNode, bitmask | (1 << nextNode)); 18 | minDistance = Math.min(minDistance, newDistance); 19 | } 20 | } 21 | 22 | memo[node][bitmask] = minDistance; 23 | return minDistance; 24 | } 25 | 26 | const initialBitmask = 1; // Start from city 0 27 | const minDistance = dp(0, initialBitmask); 28 | return minDistance; 29 | } 30 | 31 | // Test case 32 | const cities = ["A", "B", "C"]; 33 | const distances = [ 34 | [0, 10, 15], 35 | [10, 0, 20], 36 | [15, 20, 0], 37 | ]; 38 | 39 | const result = tspDynamicProgrammingBitmask(cities, distances); 40 | console.log("Dynamic Programming (Bitmask) Optimal Distance:", result); 41 | -------------------------------------------------------------------------------- /DSA/Graphs/Travelling Salesman Problem/Dynamic_programming.js: -------------------------------------------------------------------------------- 1 | function dynamicProgrammingTSP(cities, distances) { 2 | const numCities = cities.length; 3 | const numStates = 1 << numCities; // 2^n states to represent subsets of cities 4 | const memo = Array(numCities) 5 | .fill(null) 6 | .map(() => Array(numStates).fill(null)); 7 | 8 | function tspDP(currentCity, state) { 9 | if (state === (1 << numCities) - 1) { 10 | // All cities visited, return to the starting city 11 | return distances[currentCity][0]; 12 | } 13 | 14 | if (memo[currentCity][state] !== null) { 15 | return memo[currentCity][state]; 16 | } 17 | 18 | let minDistance = Infinity; 19 | for (let nextCity = 0; nextCity < numCities; nextCity++) { 20 | if ((state & (1 << nextCity)) === 0) { 21 | // Next city not visited 22 | const newDistance = distances[currentCity][nextCity] + tspDP(nextCity, state | (1 << nextCity)); 23 | minDistance = Math.min(minDistance, newDistance); 24 | } 25 | } 26 | 27 | memo[currentCity][state] = minDistance; 28 | return minDistance; 29 | } 30 | 31 | const optimalDistance = tspDP(0, 1); // Start from city 0 (the first city), with only city 0 visited 32 | return optimalDistance; 33 | } 34 | 35 | // Test case 36 | const cities = ["A", "B", "C"]; 37 | const distances = [ 38 | [0, 10, 15], 39 | [10, 0, 20], 40 | [15, 20, 0], 41 | ]; 42 | 43 | const result = dynamicProgrammingTSP(cities, distances); 44 | console.log("Dynamic Programming Optimal Distance:", result); 45 | -------------------------------------------------------------------------------- /DSA/Graphs/Travelling Salesman Problem/HeuristicApproach.js: -------------------------------------------------------------------------------- 1 | function solveILPHeuristic() { 2 | const coefficients = [2, 3, 5]; // Coefficients of the objective function 3 | const constraintCoefficients = [ 4 | [1, 2, 1], // Coefficients of the constraints 5 | ]; 6 | const constraintLimits = [0]; // Right-hand side of the constraints 7 | 8 | const numVariables = coefficients.length; 9 | const numConstraints = constraintCoefficients.length; 10 | 11 | const solution = Array(numVariables).fill(0); 12 | let objectiveValue = 0; 13 | 14 | for (let i = 0; i < numVariables; i++) { 15 | // Calculate the marginal contribution of variable i to the objective function 16 | const marginalContribution = coefficients[i]; 17 | 18 | // Check if adding variable i to the solution violates any constraints 19 | let isFeasible = true; 20 | for (let j = 0; j < numConstraints; j++) { 21 | let constraintValue = 0; 22 | for (let k = 0; k < numVariables; k++) { 23 | constraintValue += solution[k] * constraintCoefficients[j][k]; 24 | } 25 | if (constraintValue + constraintCoefficients[j][i] > constraintLimits[j]) { 26 | isFeasible = false; 27 | break; 28 | } 29 | } 30 | 31 | // If adding variable i is feasible and improves the objective, include it in the solution 32 | if (isFeasible && marginalContribution > 0) { 33 | solution[i] = 1; 34 | objectiveValue += marginalContribution; 35 | } 36 | } 37 | 38 | return { solution, objectiveValue }; 39 | } 40 | 41 | // Test the heuristic approach for ILP 42 | const result = solveILPHeuristic(); 43 | console.log('Solution:', result.solution); 44 | console.log('Objective Value (approximate):', result.objectiveValue); 45 | -------------------------------------------------------------------------------- /DSA/Graphs/Travelling Salesman Problem/IntegerLinearProgramming.js: -------------------------------------------------------------------------------- 1 | function solveILP() { 2 | const coefficients = [2, 3, 5]; // Coefficients of the objective function 3 | const constraintCoefficients = [ 4 | [1, 2, 1], // Coefficients of the constraints 5 | ]; 6 | const constraintLimits = [0]; // Right-hand side of the constraints 7 | 8 | const numVariables = coefficients.length; 9 | const numConstraints = constraintCoefficients.length; 10 | 11 | let bestObjectiveValue = -Infinity; 12 | let bestSolution = Array(numVariables).fill(0); 13 | 14 | // Generate all possible binary combinations for the variables 15 | for (let i = 0; i < Math.pow(2, numVariables); i++) { 16 | const binary = (i >>> 0).toString(2).padStart(numVariables, '0').split('').map(Number); 17 | let isFeasible = true; 18 | 19 | // Check if the binary combination satisfies the constraints 20 | for (let j = 0; j < numConstraints; j++) { 21 | let constraintValue = 0; 22 | for (let k = 0; k < numVariables; k++) { 23 | constraintValue += binary[k] * constraintCoefficients[j][k]; 24 | } 25 | if (constraintValue > constraintLimits[j]) { 26 | isFeasible = false; 27 | break; 28 | } 29 | } 30 | 31 | if (isFeasible) { 32 | // Calculate the objective value for this combination 33 | let objectiveValue = 0; 34 | for (let k = 0; k < numVariables; k++) { 35 | objectiveValue += binary[k] * coefficients[k]; 36 | } 37 | 38 | // Update the best solution if this combination has a better objective value 39 | if (objectiveValue > bestObjectiveValue) { 40 | bestObjectiveValue = objectiveValue; 41 | bestSolution = [...binary]; 42 | } 43 | } 44 | } 45 | 46 | return { solution: bestSolution, objectiveValue: bestObjectiveValue }; 47 | } 48 | 49 | // Test the ILP solver 50 | const result = solveILP(); 51 | console.log('Solution:', result.solution); 52 | console.log('Optimal Objective Value:', result.objectiveValue); 53 | -------------------------------------------------------------------------------- /DSA/Graphs/Travelling Salesman Problem/IterativeImprovement(Heuristic).js: -------------------------------------------------------------------------------- 1 | function iterativeImprovementTSP(cities, distances) { 2 | const numCities = cities.length; 3 | let currentOrder = generateRandomOrder(numCities); 4 | let currentDistance = calculateTotalDistance(currentOrder, distances); 5 | let improvement = true; 6 | 7 | while (improvement) { 8 | improvement = false; 9 | 10 | for (let i = 0; i < numCities - 1; i++) { 11 | for (let j = i + 1; j < numCities; j++) { 12 | const newOrder = twoOptSwap(currentOrder, i, j); 13 | const newDistance = calculateTotalDistance(newOrder, distances); 14 | 15 | if (newDistance < currentDistance) { 16 | currentOrder = newOrder; 17 | currentDistance = newDistance; 18 | improvement = true; 19 | } 20 | } 21 | } 22 | } 23 | 24 | return { order: currentOrder, distance: currentDistance }; 25 | } 26 | 27 | function twoOptSwap(order, i, j) { 28 | const newOrder = [...order]; 29 | while (i < j) { 30 | [newOrder[i], newOrder[j]] = [newOrder[j], newOrder[i]]; 31 | i++; 32 | j--; 33 | } 34 | return newOrder; 35 | } 36 | 37 | // Test case 38 | const cities = ["A", "B", "C", "D"]; 39 | const distances = [ 40 | [0, 10, 15, 20], 41 | [10, 0, 35, 25], 42 | [15, 35, 0, 30], 43 | [20, 25, 30, 0], 44 | ]; 45 | 46 | const result = iterativeImprovementTSP(cities, distances); 47 | console.log("Iterative Improvement Order:", result.order.map((idx) => cities[idx]).join(" -> ")); 48 | console.log("Iterative Improvement Distance:", result.distance); 49 | -------------------------------------------------------------------------------- /DSA/Graphs/Travelling Salesman Problem/Lin-Kernighan.js: -------------------------------------------------------------------------------- 1 | function linKernighanTSP(cities, distances) { 2 | const n = cities.length; 3 | let bestTour = []; 4 | let bestCost = Infinity; 5 | 6 | function calculateTourCost(tour) { 7 | let cost = 0; 8 | for (let i = 0; i < n - 1; i++) { 9 | const from = tour[i]; 10 | const to = tour[i + 1]; 11 | cost += distances[from][to]; 12 | } 13 | cost += distances[tour[n - 1]][tour[0]]; // Return to the starting city 14 | return cost; 15 | } 16 | 17 | function reverseSubtour(tour, i, j) { 18 | while (i < j) { 19 | const temp = tour[i]; 20 | tour[i] = tour[j]; 21 | tour[j] = temp; 22 | i++; 23 | j--; 24 | } 25 | } 26 | 27 | function explore(k, tour, gain, canRemove) { 28 | if (k === n) { 29 | const tourCost = calculateTourCost(tour); 30 | if (tourCost < bestCost) { 31 | bestTour = [...tour]; 32 | bestCost = tourCost; 33 | } 34 | } else { 35 | for (let i = k; i < n; i++) { 36 | if (canRemove[tour[i]]) { 37 | for (let j = 0; j < n; j++) { 38 | if (!canRemove[tour[j]]) { 39 | const nextTour = [...tour]; 40 | reverseSubtour(nextTour, k, i); 41 | nextTour[k] = tour[i]; 42 | const newGain = gain - distances[tour[k - 1]][tour[k]] + distances[tour[i]][tour[i + 1]]; 43 | 44 | if (newGain < 0) { 45 | explore(k + 1, nextTour, newGain, canRemove); 46 | } 47 | } 48 | } 49 | } 50 | } 51 | } 52 | } 53 | 54 | const initialTour = Array.from({ length: n }, (_, i) => i); 55 | const canRemove = Array(n).fill(true); 56 | canRemove[0] = false; // Starting city cannot be removed 57 | explore(1, initialTour, 0, canRemove); 58 | 59 | return { order: bestTour.map((idx) => cities[idx]), distance: bestCost }; 60 | } 61 | 62 | // Test case 63 | const cities = ["A", "B", "C", "D"]; 64 | const distances = [ 65 | [0, 10, 15, 20], 66 | [10, 0, 35, 25], 67 | [15, 35, 0, 30], 68 | [20, 25, 30, 0], 69 | ]; 70 | 71 | const result = linKernighanTSP(cities, distances); 72 | console.log("Lin-Kernighan Algorithm Order:", result.order.join(" -> ")); 73 | console.log("Lin-Kernighan Algorithm Distance:", result.distance); 74 | -------------------------------------------------------------------------------- /DSA/Graphs/Travelling Salesman Problem/NearestNeighborAlgorithm.js: -------------------------------------------------------------------------------- 1 | function nearestNeighborTSP(cities, distances) { 2 | const n = cities.length; 3 | const visited = Array(n).fill(false); 4 | const order = [0]; // Start from the first city (index 0) 5 | let totalDistance = 0; 6 | 7 | visited[0] = true; 8 | for (let i = 1; i < n; i++) { 9 | let nearestIdx = -1; 10 | let minDistance = Infinity; 11 | 12 | for (let j = 0; j < n; j++) { 13 | if (!visited[j] && distances[order[i - 1]][j] < minDistance) { 14 | nearestIdx = j; 15 | minDistance = distances[order[i - 1]][j]; 16 | } 17 | } 18 | 19 | order.push(nearestIdx); 20 | visited[nearestIdx] = true; 21 | totalDistance += minDistance; 22 | } 23 | 24 | totalDistance += distances[order[n - 1]][order[0]]; // Return to the starting city 25 | return { order, distance: totalDistance }; 26 | } 27 | 28 | // Test case 29 | const cities = ["A", "B", "C"]; 30 | const distances = [ 31 | [0, 10, 15], 32 | [10, 0, 20], 33 | [15, 20, 0], 34 | ]; 35 | 36 | const result = nearestNeighborTSP(cities, distances); 37 | console.log("Approximate Order:", result.order.map((idx) => cities[idx]).join(" -> ")); 38 | console.log("Approximate Distance:", result.distance); 39 | -------------------------------------------------------------------------------- /DSA/Graphs/Travelling Salesman Problem/SimulatedAnnealing.js: -------------------------------------------------------------------------------- 1 | function simulatedAnnealingTSP(cities, distances, temperature, coolingRate) { 2 | let currentOrder = generateRandomOrder(cities.length); 3 | let currentDistance = calculateTotalDistance(currentOrder, distances); 4 | let bestOrder = currentOrder.slice(); 5 | let minDistance = currentDistance; 6 | 7 | while (temperature > 1) { 8 | const i = Math.floor(Math.random() * cities.length); 9 | const j = Math.floor(Math.random() * cities.length); 10 | const newOrder = currentOrder.slice(); 11 | [newOrder[i], newOrder[j]] = [newOrder[j], newOrder[i]]; // Swap two cities 12 | const newDistance = calculateTotalDistance(newOrder, distances); 13 | 14 | const delta = newDistance - currentDistance; 15 | if (delta < 0 || Math.random() < Math.exp(-delta / temperature)) { 16 | currentOrder = newOrder; 17 | currentDistance = newDistance; 18 | if (currentDistance < minDistance) { 19 | bestOrder = currentOrder.slice(); 20 | minDistance = currentDistance; 21 | } 22 | } 23 | 24 | temperature *= coolingRate; 25 | } 26 | 27 | return { order: bestOrder, distance: minDistance }; 28 | } 29 | 30 | // Test case 31 | const cities = ["A", "B", "C", "D"]; 32 | const distances = [ 33 | [0, 10, 15, 20], 34 | [10, 0, 35, 25], 35 | [15, 35, 0, 30], 36 | [20, 25, 30, 0], 37 | ]; 38 | 39 | const result = simulatedAnnealingTSP(cities, distances, 1000, 0.99); 40 | console.log("Simulated Annealing Order:", result.order.map((idx) => cities[idx]).join(" -> ")); 41 | console.log("Simulated Annealing Distance:", result.distance); 42 | -------------------------------------------------------------------------------- /DSA/Miscelleneous/SmallestCommonMultiple.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by 4 | all sequential numbers in the range between these parameters. 5 | 6 | The range will be an array of two numbers that will not necessarily be in numerical order. 7 | 8 | For example, if given 1 and 3, find the smallest common multiple of both 1 and 3 that is also evenly divisible 9 | by all numbers between 1 and 3. The answer here would be 6. 10 | 11 | */ 12 | 13 | function smallestCommons(arr) { 14 | var range = []; 15 | for (var i = Math.max(arr[0], arr[1]); i >= Math.min(arr[0], arr[1]); i--) { 16 | range.push(i); 17 | } 18 | 19 | // could use reduce() in place of this block 20 | var lcm = range[0]; 21 | for (i = 1; i < range.length; i++) { 22 | var GCD = gcd(lcm, range[i]); 23 | lcm = (lcm * range[i]) / GCD; 24 | } 25 | return lcm; 26 | 27 | function gcd(x, y) { 28 | if (y === 0) 29 | return x; 30 | else 31 | return gcd(y, x%y); 32 | } 33 | } 34 | 35 | // test here 36 | smallestCommons([1,5]); 37 | -------------------------------------------------------------------------------- /DSA/Strings/Capitalize.js: -------------------------------------------------------------------------------- 1 | // Convert a sentence to title case using Javascript 2 | // example: Input: this is a phrase 3 | // Output: This Is A Phrase 4 | 5 | const toTitleCase = (sentence) =>{ 6 | let words = sentence.split(' '); 7 | let capitalizedSentence=''; 8 | words.forEach((word)=>{ 9 | capitalizedSentence += String(word).charAt(0).toUpperCase() + word.slice(1) + ' '; 10 | }) 11 | 12 | return capitalizedSentence.trim(); 13 | } 14 | const sentence = 'this is a phrase' 15 | 16 | console.log(toTitleCase(sentence)); -------------------------------------------------------------------------------- /DSA/Strings/ShortestSubstring.js: -------------------------------------------------------------------------------- 1 | const compareSets = (a, b) => a.size === b.size && [...a].every(e => b.has(e)) 2 | 3 | function shortestSubstring(s) { 4 | let len = s.length 5 | let uniqueChars = new Set(Array.from(s)) 6 | let subString = '' 7 | let mLen = len + 1; 8 | 9 | for (let i = 0; i < len; i++) { 10 | for (let j = i; j < len; j++) { 11 | subString = subString + s[j] 12 | if (compareSets(new Set(subString), uniqueChars)) { 13 | if (mLen > subString.length) { 14 | mLen = subString.length 15 | } 16 | break; 17 | } 18 | } 19 | subString = '' 20 | } 21 | return mLen 22 | } 23 | 24 | console.log(shortestSubstring('bcaacbc')) 25 | -------------------------------------------------------------------------------- /EloquentJS/Snippets/HOF/everything.js: -------------------------------------------------------------------------------- 1 | function every(array, test){ 2 | for(let i of array){ 3 | if(!test(i)){ 4 | return false 5 | } 6 | } 7 | return true 8 | } 9 | 10 | console.log(every([1, 3, 5], n => n < 10)); 11 | // → true 12 | console.log(every([2, 4, 16], n => n < 10)); 13 | // → false 14 | console.log(every([], n => n < 10)); 15 | // → true -------------------------------------------------------------------------------- /EloquentJS/Snippets/HOF/flattenArray.js: -------------------------------------------------------------------------------- 1 | let arr = [[1,2,3],[1,2],[1,2,4]] 2 | 3 | arr.reduce((a,b) => a.concat(b)); 4 | 5 | // OR 6 | 7 | function flatten(arrOfArr){ 8 | return arrOfArr.reduce(function(resArr, nthArr){ 9 | return resArr.concat(nthArr); 10 | }, []); 11 | } -------------------------------------------------------------------------------- /EloquentJS/Snippets/HOF/hofFromScratch.js: -------------------------------------------------------------------------------- 1 | // Map 2 | 3 | function map(array, transform) { 4 | let mapped = []; 5 | for (let element of array) { 6 | mapped.push(transform(element)); 7 | } 8 | return mapped; 9 | } 10 | 11 | 12 | // Filter 13 | 14 | function filter(array, test) { 15 | let passed = []; 16 | for (let element of array) { 17 | if (test(element)) { 18 | passed.push(element); 19 | } 20 | } 21 | return passed; 22 | } 23 | 24 | 25 | // Reduce 26 | 27 | function reduce(array, combine, start) { 28 | let current = start; 29 | for (let element of array) { 30 | current = combine(current, element); 31 | } 32 | return current; 33 | } -------------------------------------------------------------------------------- /EloquentJS/Snippets/HOF/yourOwnLoop.js: -------------------------------------------------------------------------------- 1 | function loop(num, test, update, body){ 2 | for(let n= num; test(n); n = update(n)){ 3 | body(n); 4 | } 5 | } 6 | 7 | loop(3, n => n > 0, n => n - 1, console.log); -------------------------------------------------------------------------------- /InterviewQuestions/README.md: -------------------------------------------------------------------------------- 1 | # JS Interview Questions Practice Resources 2 | 3 | ### Interview Questions Blogs 4 | - https://javascript.plainenglish.io/some-of-the-javascript-interview-questions-i-have-experienced-ce802e4e107d 5 | - https://levelup.gitconnected.com/7-common-frontend-interview-questions-c8dddd3a9382 6 | - https://www.freecodecamp.org/news/3-questions-to-watch-out-for-in-a-javascript-interview-725012834ccb/ 7 | - https://blog.usejournal.com/most-frequently-asked-topics-in-the-javascript-interview-part-ii-ac9468970d5d 8 | - What would you ask in FE interview: https://www.quora.com/What-would-you-ask-in-a-JavaScript-frontend-interview 9 | - http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/ 10 | 11 | ### Concepts and Topics Resources 12 | - Many Good JS Interview Practice Topics: https://skilled.dev/course 13 | - Pub Sub Architecture by Gaurav Sen: https://www.youtube.com/watch?v=FMhbR_kQeHw 14 | - Pub Sub Architecture by Hussain: https://www.youtube.com/watch?v=O1PgqUqZKTA 15 | - RabbitMQ: https://www.youtube.com/watch?v=Cie5v59mrTg&t=44s 16 | - REST API: https://www.youtube.com/watch?v=M3XQ6yEC51Q&list=PLQnljOFTspQXNP6mQchJVP3S-3oKGEuw9&index=1 17 | - Build a JavaScript Promise: https://skilled.dev/course/build-a-javascript-promise 18 | - Essential Design Patterns: https://addyosmani.com/resources/essentialjsdesignpatterns/book/ -------------------------------------------------------------------------------- /InterviewQuestions/customBind.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/InterviewQuestions/customBind.js -------------------------------------------------------------------------------- /InterviewQuestions/customList.js: -------------------------------------------------------------------------------- 1 | function list() { 2 | console.log(arguments); 3 | return Array.prototype.slice.call(arguments); 4 | } 5 | 6 | const lis = list(1,2,3) 7 | console.log(lis) -------------------------------------------------------------------------------- /InterviewQuestions/debounce.js: -------------------------------------------------------------------------------- 1 | // Implementation 1 2 | const getData = () => { 3 | console.log("Fetching Data..."); 4 | }; 5 | 6 | const debounce = (fn, delay) => { 7 | // returns a function that calls getData() only when x ms delay is observed 8 | let timer; 9 | return function () { 10 | // call getData after some interval x 11 | let context = this; 12 | args = arguments; 13 | clearTimeout(timer); 14 | timer = setTimeout(() => { 15 | fn(); 16 | }, delay); 17 | }; 18 | }; 19 | 20 | const debounceFunction = debounce(getData, 1000); 21 | 22 | // Implementation 2 23 | 24 | function debounce(delay, func){ 25 | let timeoutID = null; 26 | 27 | return function(...args){ 28 | if(timeoutID){ 29 | clearTimeout(timeoutID); 30 | } 31 | 32 | timeoutID = setTimeout(() => func(...args), delay); 33 | } 34 | } -------------------------------------------------------------------------------- /InterviewQuestions/findSecondLargestElementInArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem statement: Find second largest element in the array. Consider the case wherein duplicates can exist 3 | * arr = [12, 35, 1, 10, 34, 35, 35] - Here 35 occurs 3 times, but second largest element should be 34 4 | */ 5 | function findSecondLargestElementInArray(arr) { 6 | let largest = -1, 7 | secondLargest = -1; 8 | 9 | for (let i = 0; i <= arr.length - 1; i++) { 10 | if (arr[i] > largest) { 11 | secondLargest = largest; 12 | largest = arr[i]; 13 | } else if (arr[i] > secondLargest && arr[i] != largest) { 14 | secondLargest = arr[i]; 15 | } 16 | } 17 | console.log(secondLargest); 18 | } 19 | let arr = [12, 35, 1, 10, 34, 35, 35]; 20 | findSecondLargestElementInArray(arr); 21 | -------------------------------------------------------------------------------- /InterviewQuestions/flattenArray.js: -------------------------------------------------------------------------------- 1 | const arr = [[1,2,3], 2,5,4,56, [4,5,[45,6,7]]]; 2 | 3 | const customFlat = function (arr, level, resArr=[]){ 4 | if(level === 0 ) return arr; 5 | 6 | for(let item of arr){ 7 | if(Array.isArray(item)){ 8 | resArr.push(...item); 9 | }else{ 10 | resArr.push(item); 11 | } 12 | } 13 | resArr = customFlat(resArr, --level); 14 | 15 | return resArr; 16 | } 17 | 18 | const flatArr = customFlat(arr, 5); 19 | console.log(flatArr); 20 | 21 | -------------------------------------------------------------------------------- /InterviewQuestions/sumFunction.js: -------------------------------------------------------------------------------- 1 | let sum = function(a){ 2 | return function(b){ 3 | if(b === undefined){ 4 | return a; 5 | } 6 | return sum(a+b); 7 | } 8 | } 9 | 10 | console.log(sum(1)(2)(10)(5)()) -------------------------------------------------------------------------------- /InterviewQuestions/throttle.js: -------------------------------------------------------------------------------- 1 | // Implementation 1 2 | const getData = () => { 3 | console.log("Fetching Data..."); 4 | }; 5 | 6 | const throttle = (func, limit) => { 7 | let flag = true 8 | return function(){ 9 | let context = this; 10 | let args = arguments; 11 | if(flag){ 12 | func.apply(context, args); 13 | flag = false; 14 | setTimeout(() => { 15 | flag=true; 16 | }, limit); 17 | } 18 | 19 | } 20 | } 21 | 22 | // Implementation 2 23 | 24 | const throttle2 = (func, limit) => { 25 | let last = new Date().getTime(); 26 | return function(){ 27 | let curr = new Date().getTime(); 28 | if(curr - last < limit){ 29 | return 30 | } 31 | last = current; 32 | return func(...args); 33 | } 34 | } 35 | 36 | const betterThrottle = throttle(getData, 300); -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day01/bg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/JavaScript Challenges/Javascript 30/Day01/bg.jpg -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day01/sounds/claps.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/JavaScript Challenges/Javascript 30/Day01/sounds/claps.wav -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day03/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | CSS variables 7 | 40 | 41 | 42 | 43 |

Updating CSS Variables with JS

44 |
45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 |
56 | 57 | Paris 58 | 59 | 73 | 74 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day03/paris.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/JavaScript Challenges/Javascript 30/Day03/paris.jpg -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day07/index.js: -------------------------------------------------------------------------------- 1 | 2 | const people = [ 3 | { name: 'Wes', year: 1988 }, 4 | { name: 'Kait', year: 1986 }, 5 | { name: 'Irv', year: 1970 }, 6 | { name: 'Lux', year: 2015 } 7 | ]; 8 | 9 | const comments = [ 10 | { text: 'Love this!', id: 523423 }, 11 | { text: 'Super good', id: 823423 }, 12 | { text: 'You are the best', id: 2039842 }, 13 | { text: 'Ramen is my fav food ever', id: 123523 }, 14 | { text: 'Nice Nice Nice!', id: 542328 } 15 | ]; 16 | 17 | // Some and Every Checks 18 | // Array.prototype.some() // is at least one person 19 or older? 19 | 20 | const isAdult = people.some(person => ((new Date()).getFullYear()) - person.year >= 19); 21 | console.log(isAdult); //true 22 | 23 | // Array.prototype.every() // is everyone 19 or older? 24 | const allAdults = people.every(person => ((new Date()).getFullYear()) - person.year >= 19); 25 | console.log(allAdults); //false 26 | 27 | // Array.prototype.find() 28 | // Find is like filter, but instead returns just the one you are looking for 29 | // find the comment with the ID of 823423 30 | let comment = comments.find(comment => comment.id === 823423) 31 | console.log(comment); 32 | 33 | // Array.prototype.findIndex() 34 | // Find the comment with this ID 35 | let index = comments.findIndex(comment => comment.id === 823423); 36 | console.log(index); 37 | 38 | // delete the comment with the ID of 823423 39 | comments.splice(index, 1); 40 | 41 | // alternative 42 | const newComments = [ 43 | ...comments.slice(0, index), 44 | ...comments.slice(index + 1) 45 | ]; -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day08/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Day 8 - HTML Canvas 7 | 12 | 13 | 14 | 15 | 16 | 79 | 80 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day09/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Console Tricks! 6 | 7 | 8 | 9 |

×BREAK×DOWN×

10 | 11 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day11/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Day 11 - Html Video Player 7 | 8 | 9 | 10 |
11 | 12 | 13 |
14 |
15 |
16 |
17 | 18 | 19 | 20 | 21 | 22 |
23 |
24 | 25 | 26 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day11/index.js: -------------------------------------------------------------------------------- 1 | const player = document.querySelector('.player') 2 | const video = player.querySelector('video'); 3 | const progress = player.querySelector('.progress'); 4 | const progressBar = player.querySelector('.progress_filled'); 5 | const toggle = player.querySelector('.toggle'); 6 | const skipButtons = player.querySelectorAll('[data-skip]'); 7 | const ranges = player.querySelectorAll('.player_slider'); 8 | 9 | // functions 10 | function togglePlay() 11 | { 12 | if(video.paused) 13 | { 14 | video.play(); 15 | 16 | } 17 | else 18 | { 19 | video.pause(); 20 | } 21 | } 22 | 23 | function updateButton(){ 24 | // const icon = this.paused ? '►' : '❚ ❚'; 25 | // toggle.textContent = icon; 26 | const icon = this.paused ? '►' : '||'; 27 | toggle.innerHTML = icon; 28 | } 29 | 30 | function skip(){ 31 | video.currentTime += parseFloat(this.dataset.skip); 32 | } 33 | 34 | function handleRangeUpdate(){ 35 | video[this.name] = this.value; 36 | console.log(this); 37 | } 38 | 39 | function handleProgress(){ 40 | const percent = ( video.currentTime / video.duration ) * 100; 41 | progressBar.style.flexBasis = `${percent}%`; 42 | } 43 | 44 | function scrub(e){ 45 | let scrubTime = ( e.offsetX / progress.offsetWidth ) * video.duration ; 46 | video.currentTime = scrubTime; 47 | console.log(e); 48 | } 49 | 50 | 51 | 52 | // eventListeners 53 | 54 | // 1.play/pause button 55 | video.addEventListener('click', togglePlay); 56 | video.addEventListener('play', updateButton); 57 | video.addEventListener('pause', updateButton); 58 | 59 | window.addEventListener('keydown', (e) => { 60 | if(e.key === " ") 61 | { 62 | togglePlay(); 63 | updateButton(); 64 | } 65 | }); 66 | 67 | toggle.addEventListener('click', togglePlay); 68 | 69 | // skip buttons 70 | skipButtons.forEach(button => button.addEventListener('click', skip)); 71 | 72 | window.addEventListener('keydown',(e) => { 73 | if(e.key === "ArrowLeft") 74 | { 75 | skipButtons[0].click(); 76 | } 77 | if(e.key === "ArrowRight") 78 | { 79 | skipButtons[1].click(); 80 | } 81 | }) 82 | 83 | // range inputs 84 | ranges.forEach(range => range.addEventListener('change', handleRangeUpdate)) 85 | 86 | // progressBar 87 | video.addEventListener('timeupdate', handleProgress) 88 | 89 | let mousedown = false; 90 | progress.addEventListener('click', scrub) 91 | progress.addEventListener('mousemove', (e) => mousedown && scrub(e) ); 92 | progress.addEventListener('mousedown', () => mousedown = true ); 93 | progress.addEventListener('mouseup', () => mousedown = false ); 94 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day11/vid.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/JavaScript Challenges/Javascript 30/Day11/vid.mp4 -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day12/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Day12 - Key Detection 7 | 8 | 9 | 24 | 25 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day14/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Day14 - JS Reference vs Copy 6 | 7 | 8 | 9 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day15/bg.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/JavaScript Challenges/Javascript 30/Day15/bg.jpeg -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day15/style.css: -------------------------------------------------------------------------------- 1 | html{ 2 | box-sizing: border-box; 3 | background: url('bg.jpeg') center no-repeat; 4 | background-size: cover; 5 | min-height: 100vh; 6 | display: flex; 7 | justify-content: center; 8 | /* align-items: center; */ 9 | text-align: center; 10 | font-family: Futura, "Trebuchet MS", Arial, sans-serif; 11 | } 12 | 13 | 14 | *, *:before, *:after { 15 | box-sizing: inherit; 16 | } 17 | 18 | svg { 19 | fill: white; 20 | background: rgba(0, 0, 0, 0.4); 21 | padding: 20px; 22 | border-radius: 50%; 23 | width: 200px; 24 | margin-bottom: 50px; 25 | } 26 | 27 | .wrapper{ 28 | padding: 20px; 29 | max-width: 350px; 30 | background-color: rgba(255,255,255,0.95); 31 | box-shadow: 0 0 0 10px rgba(0, 0, 0, 0.3); 32 | } 33 | 34 | h2{ 35 | text-align: center; 36 | margin: 0; 37 | font-weight: 200; 38 | } 39 | 40 | .plates { 41 | margin: 0; 42 | padding: 0; 43 | text-align: left; 44 | list-style: none; 45 | } 46 | 47 | .plates li{ 48 | border-bottom: 1px solid rgba(0, 0, 0, 0.2); 49 | padding: 10px 0; 50 | font-weight: 100; 51 | display: flex; 52 | } 53 | 54 | .plates label { 55 | flex: 1; 56 | cursor: pointer; 57 | } 58 | 59 | .plates input { 60 | display: none; 61 | } 62 | 63 | .plates input + label::before { 64 | content: "⬜"; 65 | margin-right: 10px; 66 | } 67 | 68 | .plates input:checked + label::before { 69 | content: "🍔"; 70 | } 71 | 72 | .add-items { 73 | margin-top: 20px; 74 | } 75 | 76 | .add-items input { 77 | padding: 10px; 78 | outline: 0; 79 | border: 1px solid rgba(0, 0, 0, 0.1); 80 | } 81 | 82 | .add-items input[type="submit"]{ 83 | background-color: grey; 84 | color: black; 85 | border: 2px solid balck; 86 | border-radius: 7px; 87 | font-weight: 400; 88 | font-size: 15px; 89 | } 90 | 91 | .add-items input[type="submit"]:hover{ 92 | background-color: black; 93 | color: white; 94 | } -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day16/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Day 16 - MouseMove 7 | 27 | 28 | 29 |
30 |

🔥WOAH!

31 |
32 | 33 | 66 | 67 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day17/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Day - 17 7 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 64 | 65 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day19/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Day 19 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 |
16 | 17 |
18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 | 32 |
33 |
34 | 35 | 36 | 37 | 38 | 39 | 40 |
41 |
42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day19/snap.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/JavaScript Challenges/Javascript 30/Day19/snap.mp3 -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day19/style.css: -------------------------------------------------------------------------------- 1 | html { 2 | box-sizing: border-box; 3 | font-size: 10px; 4 | background-color: #ffc600; 5 | } 6 | *,*::before,*::after{ 7 | box-sizing: inherit; 8 | } 9 | 10 | .photobooth{ 11 | background-color: white; 12 | max-width: 150rem; 13 | margin: 2rem auto; 14 | border-radius: 2px; 15 | } 16 | .photobooth:after { 17 | content: ''; 18 | display: block; 19 | clear: both; 20 | } 21 | 22 | .controls{ 23 | position: absolute; 24 | right: 0; 25 | width: 80%; 26 | height: 150px; 27 | } 28 | 29 | .controls button{ 30 | background-color: black; 31 | border: 2px solid black; 32 | color: white; 33 | border-radius: 4px; 34 | padding: 1rem; 35 | } 36 | 37 | .controls button:hover{ 38 | background-color: white; 39 | color: black; 40 | } 41 | 42 | .controls .rgb{ 43 | display: inline-block; 44 | margin: 1rem 15rem; 45 | font-size: 16px; 46 | } 47 | 48 | .photo { 49 | width: 95%; 50 | height: 50vw; 51 | float: left; 52 | margin-top: 20rem; 53 | margin-left: 3rem; 54 | border-radius: 20px; 55 | } 56 | 57 | .player { 58 | border-radius: 50%; 59 | position: absolute; 60 | top: 30px; 61 | left: 20px; 62 | width:200px; 63 | } 64 | 65 | .strip { 66 | background-color: white; 67 | width: 100%; 68 | height: auto; 69 | border-radius: 10px; 70 | padding: 2rem; 71 | } 72 | 73 | .strip img { 74 | width: 100px; 75 | overflow-x: scroll; 76 | padding: 0.8rem 0.8rem 2.5rem 0.8rem; 77 | box-shadow: 0 0 3px rgba(0,0,0,0.2); 78 | background: white; 79 | } 80 | 81 | .strip a:nth-child(5n+1) img { transform: rotate(10deg); } 82 | .strip a:nth-child(5n+2) img { transform: rotate(-2deg); } 83 | .strip a:nth-child(5n+3) img { transform: rotate(8deg); } 84 | .strip a:nth-child(5n+4) img { transform: rotate(-11deg); } 85 | .strip a:nth-child(5n+5) img { transform: rotate(12deg); } -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day20/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Day 20 - Speech Detection 7 | 43 | 44 | 45 |
46 |
47 | 48 | 81 | 82 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day21/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "gum", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "scripts.js", 6 | "scripts": { 7 | "start": "browser-sync start --directory --server --files \"*.css, *.html, *.js\" --https" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "browser-sync": "^2.26.13" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day25/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Day 25 7 | 31 | 32 | 33 |
34 |
35 |
36 |
37 |
38 | 39 | 79 | 80 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day26/logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/JavaScript Challenges/Javascript 30/Day26/logo.jpg -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day27/style.css: -------------------------------------------------------------------------------- 1 | html { 2 | box-sizing: border-box; 3 | background: url('https://source.unsplash.com/NFs6dRTBgaM/2000x2000') fixed; 4 | background-size: cover; 5 | } 6 | 7 | *, *:before, *:after { 8 | box-sizing: inherit; 9 | } 10 | 11 | body { 12 | min-height: 100vh; 13 | display: flex; 14 | justify-content: center; 15 | align-items: center; 16 | font-family: sans-serif; 17 | font-size: 20px; 18 | margin: 0; 19 | } 20 | 21 | .items { 22 | height: 600px; 23 | padding: 100px; 24 | width: 100%; 25 | border: 1px solid white; 26 | overflow-x: scroll; 27 | overflow-y: hidden; 28 | white-space: nowrap; 29 | user-select: none; 30 | cursor: pointer; 31 | transition: all 0.2s; 32 | transform: scale(0.98); 33 | will-change: transform; 34 | position: relative; 35 | background: rgba(255,255,255,0.1); 36 | font-size: 0; 37 | perspective: 500px; 38 | } 39 | 40 | .items.active { 41 | background: rgba(255,255,255,0.3); 42 | cursor: grabbing; 43 | cursor: -webkit-grabbing; 44 | transform: scale(1); 45 | } 46 | 47 | .item { 48 | width: 200px; 49 | height: calc(100% - 40px); 50 | display: inline-flex; 51 | align-items: center; 52 | justify-content: center; 53 | font-size: 80px; 54 | font-weight: 100; 55 | color: rgba(0,0,0,0.15); 56 | box-shadow: inset 0 0 0 10px rgba(0,0,0,0.15); 57 | /* overflow: hidden; */ 58 | } 59 | 60 | .item img{ 61 | width: 200px; 62 | height: calc(100% - 40px); 63 | } 64 | 65 | .item:nth-child(9n+1) { background: dodgerblue;} 66 | .item:nth-child(9n+2) { background: goldenrod;} 67 | .item:nth-child(9n+3) { background: paleturquoise;} 68 | .item:nth-child(9n+4) { background: gold;} 69 | .item:nth-child(9n+5) { background: cadetblue;} 70 | .item:nth-child(9n+6) { background: tomato;} 71 | .item:nth-child(9n+7) { background: lightcoral;} 72 | .item:nth-child(9n+8) { background: darkslateblue;} 73 | .item:nth-child(9n+9) { background: rebeccapurple;} 74 | 75 | .item:nth-child(even) { transform: scaleX(1.31) rotateY(40deg); } 76 | .item:nth-child(odd) { transform: scaleX(1.31) rotateY(-40deg); } 77 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day29/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Day 29 7 | 8 | 9 | 10 | 11 |
12 |
13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |
21 |
22 |
23 |

24 |

25 |
26 |
27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day29/script.js: -------------------------------------------------------------------------------- 1 | let countdown; 2 | const timerDisplay = document.querySelector('.display__time-left'); 3 | const endTime = document.querySelector('.display__end-time'); 4 | const buttons = document.querySelectorAll('[data-time]'); 5 | const playPause = document.querySelector('#start-stop'); 6 | let secondsLeft; 7 | let timerStart = false; 8 | 9 | function timer(seconds) 10 | { 11 | clearInterval(countdown);//clear all previous timers 12 | timerStart = true; 13 | const now = Date.now() ; // milliseconds 14 | const then = (seconds * 1000) + now ; 15 | 16 | displayTimeLeft(seconds); 17 | displayEndTime(then); 18 | 19 | countdown = setInterval(()=>{ 20 | secondsLeft = Math.round((then - Date.now()) / 1000); 21 | 22 | if(secondsLeft < 0) 23 | { 24 | timerStart = false; 25 | clearInterval(countdown); 26 | return; 27 | } 28 | 29 | displayTimeLeft(secondsLeft); 30 | 31 | },1000) 32 | 33 | } 34 | 35 | function displayTimeLeft(seconds) 36 | { 37 | const hours = Math.floor(seconds / 3600) ; 38 | seconds = seconds % 3600; 39 | const minutes = Math.floor(seconds / 60) ; 40 | const remainerSeconds = seconds % 60; 41 | 42 | const displayTime = `${hours<10&&hours>0?'0':''}${hours>0?hours+':':''}${minutes<10 ? '0' : ''}${minutes}:${remainerSeconds<10 ? '0' : ''}${remainerSeconds}`; 43 | document.title = displayTime; 44 | timerDisplay.textContent = displayTime; 45 | } 46 | 47 | function displayEndTime(timestamp) 48 | { 49 | const end = new Date(timestamp); 50 | const hours = end.getHours(); 51 | const minutes = end.getMinutes(); 52 | endTime.textContent = `Be back at ${hours > 12 ? hours-12 : hours}:${minutes<10 ? '0': ''}${minutes}`; 53 | } 54 | 55 | function startTimer() 56 | { 57 | const seconds = parseInt(this.dataset.time); 58 | timer(seconds); 59 | } 60 | 61 | buttons.forEach(button => button.addEventListener('click', startTimer) ) 62 | document.customForm.addEventListener('submit', function(e){ 63 | e.preventDefault(); 64 | const mins = this.minutes.value; 65 | timer(mins*60); 66 | this.reset(); 67 | }) 68 | 69 | 70 | playPause.addEventListener('click', (e)=> { 71 | if(timerStart) 72 | { 73 | clearInterval(countdown); 74 | timerStart = false; 75 | } 76 | else 77 | { 78 | timer(secondsLeft) 79 | } 80 | }) 81 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day29/style.css: -------------------------------------------------------------------------------- 1 | html { 2 | box-sizing: border-box; 3 | font-size: 10px; 4 | background: #8E24AA; 5 | background: linear-gradient(45deg, #42a5f5 0%,#478ed1 50%,#0d47a1 100%); 6 | } 7 | 8 | *, *:before, *:after { 9 | box-sizing: inherit; 10 | } 11 | 12 | body { 13 | margin: 0; 14 | text-align: center; 15 | font-family: 'Inconsolata', monospace; 16 | } 17 | 18 | .display__time-left { 19 | font-weight: 100; 20 | font-size: 20rem; 21 | margin: 0; 22 | color: white; 23 | text-shadow: 4px 4px 0 rgba(0,0,0,0.05); 24 | } 25 | 26 | .timer { 27 | display: flex; 28 | min-height: 100vh; 29 | flex-direction: column; 30 | } 31 | 32 | .timer__controls { 33 | display: flex; 34 | } 35 | 36 | .timer__controls > * { 37 | flex: 1; 38 | } 39 | 40 | .timer__controls form { 41 | flex: 1; 42 | display: flex; 43 | } 44 | 45 | .timer__controls input { 46 | flex: 1; 47 | border: 0; 48 | padding: 2rem; 49 | } 50 | 51 | .timer__button { 52 | background: none; 53 | border: 0; 54 | cursor: pointer; 55 | color: white; 56 | font-size: 2rem; 57 | text-transform: uppercase; 58 | background: rgba(0,0,0,0.1); 59 | border-bottom: 3px solid rgba(0,0,0,0.2); 60 | border-right: 1px solid rgba(0,0,0,0.2); 61 | padding: 1rem; 62 | font-family: 'Inconsolata', monospace; 63 | } 64 | 65 | .timer__button:hover, 66 | .timer__button:focus { 67 | background: rgba(0,0,0,0.2); 68 | outline: 0; 69 | } 70 | 71 | 72 | .display { 73 | flex: 1; 74 | display: flex; 75 | flex-direction: column; 76 | align-items: center; 77 | justify-content: center; 78 | } 79 | 80 | 81 | .display__end-time { 82 | font-size: 4rem; 83 | color: white; 84 | } -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day30/script.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/JavaScript Challenges/Javascript 30/Day30/script.js -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day30/styles.css: -------------------------------------------------------------------------------- 1 | html { 2 | box-sizing: border-box; 3 | font-size: 10px; 4 | background: #ffc600; 5 | } 6 | 7 | *, 8 | *:before, 9 | *:after { 10 | box-sizing: inherit; 11 | } 12 | 13 | body { 14 | padding: 0; 15 | margin: 0; 16 | font-family: cursive; 17 | } 18 | 19 | h1 { 20 | text-align: center; 21 | font-size: 10rem; 22 | line-height: 1; 23 | margin-bottom: 0; 24 | } 25 | 26 | .start{ 27 | padding: 1.5rem; 28 | background: transparent; 29 | border: 2px solid rgba(0, 0, 0, 0.5); 30 | font-size: 2rem; 31 | width: 10rem; 32 | margin: 10px auto; 33 | display: block; 34 | } 35 | 36 | .start:hover{ 37 | background-color: rgb(0, 0, 0); 38 | color: #ffc600; 39 | } 40 | 41 | .score { 42 | background: rgba(255, 255, 255, 0.2); 43 | padding: 0 3rem; 44 | line-height: 1; 45 | border-radius: 1rem; 46 | } 47 | 48 | .game { 49 | width: 600px; 50 | height: 400px; 51 | display: flex; 52 | flex-wrap: wrap; 53 | margin: 0 auto; 54 | } 55 | 56 | .hole { 57 | flex: 1 0 33.33%; 58 | overflow: hidden; 59 | position: relative; 60 | } 61 | 62 | .hole:after { 63 | display: block; 64 | background: url(dirt.svg) bottom center no-repeat; 65 | background-size: contain; 66 | content: ""; 67 | width: 100%; 68 | height: 70px; 69 | position: absolute; 70 | z-index: 2; 71 | bottom: -30px; 72 | } 73 | 74 | .mole { 75 | background: url("mole.svg") bottom center no-repeat; 76 | background-size: 60%; 77 | position: absolute; 78 | top: 100%; 79 | width: 100%; 80 | height: 100%; 81 | transition: all 0.4s; 82 | } 83 | 84 | .hole.up .mole { 85 | top: 0; 86 | } 87 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/Day31/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 40 | 41 | 42 |
43 |
44 |
45 | 46 | 47 | 48 | 49 | 50 | 51 |
52 | 53 |
54 |
55 | 56 | 83 | 84 | -------------------------------------------------------------------------------- /JavaScript Challenges/Javascript 30/readme.md: -------------------------------------------------------------------------------- 1 | Complete code for JavaScript 30 Challenge. 2 | Each day brings a new and intresting concept of JavaScript. 3 | -------------------------------------------------------------------------------- /NamasteJS/E01 - How JavaScript Works & Execution Context.md: -------------------------------------------------------------------------------- 1 | # [Episode 1](https://www.youtube.com/watch?v=iLWTnMzWtj4&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=2): How JavaScript Works 🔥& Execution Context 2 | 3 | > *Everything in JavaScript happens inside an "Execution Context"* 4 | 5 | * Execution Context is like a big box. It has two components in it. 6 | 7 | 1. Memory Component: Here variables and functions are stored as Key:Value Pair. 8 | It is also known as "Variable Environment". 9 | 10 | 2. Code Component: Here code is executed one line at a time. Also known as "Thread of Execution". 11 | 12 | * *JavaScript is a Synchronous single-threaded language* 13 | 14 | * Single Threaded: Can execute one command at a time. 15 | * Synchronous: In a specific order. 16 | * Synchronous Single Threaded: One command at a time in a specific order. 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /NamasteJS/E03 - Hoisting in JavaScript (variables & functions).md: -------------------------------------------------------------------------------- 1 | # [Episode 3](https://www.youtube.com/watch?v=Fnlnw8uY6jo&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=4): Hoisting in JavaScript 🔥(variables & functions) 2 | 3 | Let us understand the concept by the following examples. 4 | 5 | ```js 6 | // code example 1 7 | 8 | var x = 7; 9 | function getName(){ 10 | console.log("Namaste JavaScript"); 11 | } 12 | 13 | getName(); 14 | console.log(x); 15 | ``` 16 | 17 | Output: 18 | 19 | > Namaste JavaScript 20 | 21 | > 7 22 | 23 | ```js 24 | // code example 2 25 | 26 | getName(); 27 | console.log(x); 28 | 29 | var x = 7; 30 | function getName(){ 31 | console.log("Namaste JavaScript"); 32 | } 33 | ``` 34 | 35 | Output: 36 | > Namaste JavaScript 37 | 38 | > undefined 39 | 40 | ```js 41 | // code example 3 42 | 43 | getName(); 44 | console.log(x); 45 | 46 | function getName(){ 47 | console.log("Namaste JavaScript"); 48 | } 49 | ``` 50 | 51 | Output: 52 | 53 | > Namaste JavaScript 54 | 55 | > Error: x is not defined 56 | 57 | __Hoisting__ is a concept which enables us to extract values of variables and functions even before defining them. 58 | 59 | ```js 60 | // code example 4 61 | 62 | function getName(){ 63 | console.log("Namaste JavaScript"); 64 | } 65 | 66 | console.log(getName) 67 | ``` 68 | 69 | Output: 70 | 71 | > f getName(){ 72 | console.log("Namaste JavaScript); 73 | } 74 | 75 | 76 | ```js 77 | // code example 5 78 | 79 | getName(); 80 | console.log(x); 81 | console.log(getName) 82 | 83 | function getName(){ 84 | console.log("Namaste JavaScript"); 85 | } 86 | ``` 87 | 88 | Output: 89 | > Namaste JavaScript 90 | 91 | > undefined 92 | 93 | > f getName(){ 94 | console.log("Namaste JavaScript); 95 | } 96 | 97 | ```js 98 | // code example 6 99 | 100 | console.log(getName) 101 | 102 | var getName = function () { 103 | console.log("Namaste JavaScript"); 104 | } 105 | 106 | var getName = () => { 107 | console.log("Namaste JavaScript"); 108 | } 109 | ``` 110 | 111 | Output: 112 | 113 | > undefined 114 | 115 | 116 | --- 117 | 118 | __REASON OF WEIRDNESS__ 119 | 120 | * The answer lies in the Global Exection Context. In the memory phase, the variables will be initialized as *undefined* and functions will get the whole function code in their memory. 121 | 122 | * This is the reason why we are getting these outputs. 123 | -------------------------------------------------------------------------------- /NamasteJS/E04 - How functions work in JS & Variable Environment.md: -------------------------------------------------------------------------------- 1 | # [Episode 4](https://www.youtube.com/watch?v=gSDncyuGw0s&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=5): How functions work in JS ❤️ & Variable Environment 2 | 3 | Let us understand the execution of the functions in JS by the simple example. 4 | 5 | ```js 6 | // code example 7 | 8 | var x=1; 9 | a(); 10 | b(); 11 | console.log(x); 12 | 13 | function a(){ 14 | var x=10; 15 | console.log(x); 16 | } 17 | 18 | function b(){ 19 | var x=100; 20 | console.log(x); 21 | } 22 | ``` 23 | 24 | Outputs: 25 | 26 | > 10 27 | 28 | > 100 29 | 30 | > 1 31 | 32 | --- 33 | 34 | __EXPLANATION OF THE CODE FLOW__ 35 | 36 | 37 | 1. The Global execution context is created. It is pushed into a call stack. 38 | 39 | call_stack = [GEC] 40 | 41 | 2. The GEC in its memory phase initializes variables with undefined and the functions with the code itself. 42 | 43 | 3. In the execution phase, when a function is called, a whole new execution context is created. So, in our case, after x=1; function a() is called. 44 | 45 | So call_stack = [GEC, a()] 46 | 47 | 4. Now the whole new execution context of a is initialized and the code is run. It logs the value of x; *which is initialized in a*. Remember, x here refers to the present exection stack as JS engine searches in that first. It console logs x=10. 48 | 49 | 5. Once a() is completed, it is popped from the call_stack and control goes to GEC again. 50 | 51 | 6. Now b() is encountered and same process is repeated. 52 | 53 | call_stack = [GEC, b()] 54 | 55 | 7. Once b() is completed, control goes again to GEC and the program continues. It console logs x=100. 56 | 57 | 8. In the end, GEC is popped out of call_stack and the program terminates. 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /NamasteJS/E05 - SHORTEST JS Program - window & this keyword.md: -------------------------------------------------------------------------------- 1 | # [Episode 5](https://www.youtube.com/watch?v=QCRpVw2KXf8&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=6): SHORTEST JS Program 🔥window & this keyword 2 | 3 | __FUNDAMENTALS__ 4 | 5 | * Shortest JS program is nothing but an Empty js file. 6 | 7 | * But there is a lot of things done by JS Engine when it is executed. 8 | 9 | * It creates GEC and also it creates "window" and *this* variable. 10 | 11 | * Window is a big global object that has a lot of functions and variables. 12 | 13 | * We can access these functions anywhere inside our JS program, and this is provided by our JS Engine itself. 14 | 15 | * *this* variable points to *window*. 16 | 17 | * Whenever a GEC is created, a *this* is created along with it. Here the Global object provided by the browser engine is *window*, so *this* points to *window*. 18 | 19 | --- 20 | 21 | __GLOBAL SPACE__ 22 | 23 | * It is anything that is not inside any function. In global space variables and functions can be present. 24 | 25 | * Whenever in a JS file, we create a global variable or a function, it gets attached with the *window* object and can be accessed through it. 26 | 27 | ```js 28 | // code example 1 29 | 30 | a=10; 31 | console.log(window.a); 32 | console.log(a); 33 | console.log(this.a); 34 | ``` 35 | 36 | Outputs: 37 | > 10 38 | 39 | > 10 40 | 41 | > 10 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /NamasteJS/E06 - undefined vs not defined in JS.md: -------------------------------------------------------------------------------- 1 | # [Episode 6](https://www.youtube.com/watch?v=B7iF6G3EyIk&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=7): undefined vs not defined in JS 🤔 2 | 3 | __IMPORTANT POINTS__ 4 | 5 | * When JS is in memory allocation phase, it allocates each variable to a placehold. That placeholder is known as *undefined*. 6 | 7 | * *undefined* is like allocating memory but not provided value yet. 8 | 9 | * If a JS variable/object is not even found in memory allocation phase, it is never assigned as *undefined* also. So if tried to accessed, it shows *error: NOT DEFINED* as it is never allocated. 10 | 11 | * *undefined* is not empty; it takes up memory. It stays undefined until it gets a value assigned to it. 12 | 13 | * JavaScript is a *loosely-typed*/*weakly-typed* language. 14 | 15 | * One can assign a number to it initially and can change whenever required to string, boolean etc. 16 | 17 | * __NEVER__ assign *undefined* to any variable. Let it be used for its purpose only! -------------------------------------------------------------------------------- /NamasteJS/E10 - Closures in JS.md: -------------------------------------------------------------------------------- 1 | # [Episode 10](https://www.youtube.com/watch?v=lW_erSjyMeM&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=12): Closures in JS 🔥 2 | 3 | * Closure: A function bind together with its lexical environment. 4 | 5 | Function along with its lexical scope forms a closure. 6 | 7 | Function bundled along with the environment. 8 | 9 | ```js 10 | Example 1 11 | 12 | function x(){ 13 | var a=7; 14 | function y(){ 15 | console.log(a); 16 | } 17 | return y; 18 | } 19 | 20 | var z = x(); 21 | console.log(z); 22 | z(); 23 | ``` 24 | 25 | Output: 26 | >f y(){ 27 | console.log(a); 28 | } 29 | >7 30 | 31 | ### Observation 32 | 33 | 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`. 34 | 35 | Here after the line `var z = x()` the function x is over and thus it is completely removed from the execution context. 36 | 37 | But now when we call `z()`, given that `x()` is completely gone from the context, what should it print? 38 | 39 | 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`. 40 | 41 | Thus, `Closure` is nothing but a function + lexical environment(it has reference of values of vars and funcs). 42 | 43 | ```js 44 | Example 2 45 | 46 | function x(){ 47 | var a=7; 48 | function y(){ 49 | console.log(a); 50 | } 51 | a=100; 52 | return y; 53 | } 54 | 55 | var z = x(); 56 | console.log(z); 57 | z(); 58 | ``` 59 | 60 | Output: 61 | >f y(){ 62 | console.log(a); 63 | } 64 | >100 65 | 66 | ```js 67 | Example 3 68 | function z(){ 69 | var b = 900; 70 | function x(){ 71 | var a=7; 72 | function y(){ 73 | console.log(a, b); 74 | } 75 | return y; 76 | } 77 | } 78 | 79 | var t = x(); 80 | t(); 81 | ``` 82 | 83 | Output: 84 | >7 900 85 | 86 | Above example shows that Closure bundles the lexical environment of all the parent levels. 87 | 88 | ### Applications of Closures 89 | 90 | - Module Design Pattern 91 | - Currying 92 | - Functions like `once` 93 | - Memoize 94 | - Maintaining state in `async` world 95 | - Set timeout 96 | - Iterators etc. 97 | -------------------------------------------------------------------------------- /NamasteJS/E11 - setTimeout + Closures Interview Question.md: -------------------------------------------------------------------------------- 1 | # [Episode 11](https://www.youtube.com/watch?v=lW_erSjyMeM&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=13): setTimeout + Closures Interview Question 🔥 2 | 3 | Let us understand by a simple example. 4 | 5 | ```js 6 | function x(){ 7 | for(var i=0; i<=5; i++){ 8 | setTimeout(function (){ 9 | console.log(i); 10 | }, i*1000); 11 | } 12 | console.log("Namaste JS"); 13 | } 14 | x(); 15 | ``` 16 | 17 | Expected: 18 | >Namaste JS 19 | > 1 (after 1s) 20 | > 2 (after 2s) 21 | > 3 (after 3s) 22 | > 4 (after 4s) 23 | > 5 (after 5s) 24 | > 6 (after 6s) 25 | 26 | Output: 27 | >Namaste JS 28 | >6 29 | >6 30 | >6 31 | >6 32 | >6 33 | >6 34 | 35 | **What happens BTS?** 36 | When the JS compiler sees the `setTimeout` it puts it in Async Queue. It sees it 5 times, and fills the queue with a total of 5 `setTimeout` funcs. 37 | 38 | Since `setTimeout` is async function, it is pushed into queue and the main thread of JS continues and it prints `Namaste JS` first and meanwhile the reference `i = 6` after incrementing from the `for` loop. 39 | 40 | After the sync thread is executed and `call stack` is empty, the async queue is started being emptied. 41 | 42 | Here, all the `setTimeout`s are closures, and thus they have reference of lexical env; and here in lexical env, `i=6` and thus `6` is printed without delay. 43 | 44 | ### How to solve this? 45 | 46 | ```js 47 | function x(){ 48 | for(let i=0; i<=5; i++){ 49 | setTimeout(function (){ 50 | console.log(i); 51 | }, i*1000); 52 | } 53 | console.log("Namaste JS"); 54 | } 55 | x(); 56 | ``` 57 | 58 | Output: 59 | >Namaste JS 60 | > 1 (after 1s) 61 | > 2 (after 2s) 62 | > 3 (after 3s) 63 | > 4 (after 4s) 64 | > 5 (after 5s) 65 | > 6 (after 6s) 66 | 67 | **Why this works?** 68 | 69 | We know that `let` has block scope. And thus for every block, a new value of `i` is created for each clossure. 70 | 71 | And so, in async queue, all `setTimeout` has unique value of `i` at a different memory location. 72 | 73 | ### How to solve this without using `let`? 74 | 75 | ```js 76 | function x(){ 77 | for(var i=0; i<=5; i++){ 78 | function close(x){ 79 | setTimeout(function (){ 80 | console.log(i); 81 | }, x*1000); 82 | } 83 | close(i); 84 | } 85 | console.log("Namaste JS"); 86 | } 87 | x(); 88 | ``` 89 | 90 | **Why this works?** 91 | 92 | We enclose the `setTimeout` inside a `close()` function. And everytime in a loop, we call `close(i)` which passes a unique value of `i` to each time `setTimeout` is called as `x` is already inside the lexical environment. 93 | 94 | In this way the problem is tackled. 95 | -------------------------------------------------------------------------------- /NamasteJS/E13 - FIRST CLASS FUNCTIONS - ft. Anonymous Functions.md: -------------------------------------------------------------------------------- 1 | # [Episode 13](https://www.youtube.com/watch?v=lW_erSjyMeM&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=15): FIRST CLASS FUNCTIONS 🔥ft. Anonymous Functions 🔥 2 | 3 | ### Function Statement or Function Declaration 4 | 5 | ```js 6 | function a(){ 7 | console.log("a") 8 | } 9 | a(); 10 | ``` 11 | 12 | ### Function Expression 13 | 14 | ```js 15 | var b = function (){ 16 | console.log("b"); 17 | } 18 | b(); 19 | ``` 20 | 21 | ### Anonymous Function 22 | 23 | ```js 24 | function () { 25 | 26 | } 27 | ``` 28 | 29 | Can only be used with function expression. 30 | It is unnamed function. 31 | 32 | ### Named Function Expression 33 | 34 | ```js 35 | var b = function xyz(){ 36 | console.log(xyz); 37 | } 38 | 39 | b(); 40 | ``` 41 | 42 | We can also name functions in JS func expressions. 43 | 44 | ### Parameters vs. Arguments 45 | 46 | Parameters: Labels/placeholders inside a function. 47 | 48 | Arguments: The variables, entities that we pass in a function call. 49 | 50 | ### First Class Functions 51 | 52 | Functions are first class citizens in JS. They can be passed as an argument, returned or stored as a value. 53 | -------------------------------------------------------------------------------- /NamasteJS/E14 - Callback Functions in JS ft. Event Listeners.md: -------------------------------------------------------------------------------- 1 | # [Episode 14](https://www.youtube.com/watch?v=lW_erSjyMeM&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=16): Callback Functions in JS ft. Event Listeners 🔥 2 | 3 | 4 | ### Callback Function in JS 5 | 6 | ```js 7 | setTimeout(function (){ 8 | console.log("timer"); 9 | },5000); 10 | 11 | function x(y){ 12 | console.log("x"); 13 | 14 | } 15 | x(function y(){ 16 | console.log("y"); 17 | }); 18 | ``` 19 | 20 | Output: 21 | >x 22 | >undefined 23 | >Timer 24 | 25 | **Explanation** 26 | Here y is never logged out...ur passing y as arg. in x but never using it 27 | 28 | Settimeout is an async function; it takes a function and executes after x miliseconds. 29 | 30 | The JS thread continues to execute other code and the call stack is filled and emptied. 31 | 32 | Once the call stack is empty, it checks if the async queue is filled; then it executes those functions in the queue. 33 | 34 | Thus output is x, undefined and then timer. 35 | 36 | JS is single threaded synchronous language. 37 | 38 | ### Important Interview Question 39 | 40 | ```js 41 | function attachEventListeners(){ 42 | let count=0; 43 | document.getElementById("clickMe").addEventListener("click", console.log("Button", ++count)); 44 | } 45 | 46 | attachEventListeners(); 47 | ``` 48 | 49 | ### removeEventListeners 50 | 51 | Event Listeners are memory-heavy. Thus we must use removeEventListeners. 52 | 53 | ### Let us Understand callbacks in a more cleaner way with an example 54 | 55 | ```js 56 | function add(a, b, callback){ 57 | console.log(`The Sum of ${a} and ${b} is ${a+b}`); 58 | callback(); 59 | } 60 | add(2, 3, function disp(){ 61 | console.log("Print the line after addition"): 62 | }); 63 | ``` 64 | -------------------------------------------------------------------------------- /NamasteJS/E15 - Asynchronous JavaScript & EVENT LOOP from scratch.md: -------------------------------------------------------------------------------- 1 | # [Episode 15](https://www.youtube.com/watch?v=lW_erSjyMeM&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=17): Asynchronous JavaScript & EVENT LOOP from scratch 🔥 2 | 3 | ### JavaScript Behind the Scenes 4 | 5 | Browser = JS Engine + Web APIs + Event Loop + Callback Queue + Microtask Queue + other stuff 6 | 7 | JS Engine: It has a call stack. When a JS code is executed, all execution happens via Call Stack. Whatever is popped off the call-stack, is executed. 8 | 9 | Web APIs: Web APIs are provided by Browser to do certain tasks. Such as: Timer (setTimeout() function), DOM APIs, fetch(), console(), localStorage etc. things. All are attached with Window object. 10 | 11 | Callback Queue: In this all the async functions are lined up. Async Functions are pulled out of call stack when encountered; does processing and once the work is done, they are pushed inside the queue. 12 | 13 | All the web APIs etc. are pushed in this. 14 | 15 | Microtask Queue: This is of higher priority than the Callback Queue. It does same thing as Callback Queue. It contains the Callbacks relating to those of "Promises" and Mutations. 16 | 17 | Event Loop: It is a Gate keeper. It keeps check that: 18 | 19 | ```js 20 | if(Call Stack === Empty && Callback Queue !== Empty){ 21 | x = Callback Queue.pop() 22 | Call Stack.push(x); 23 | } 24 | else{ 25 | wait(till Call Stack is not empty) 26 | } 27 | ``` 28 | -------------------------------------------------------------------------------- /NamasteJS/E16 - JS Engine EXPOSED - Google's V8 Architecture.md: -------------------------------------------------------------------------------- 1 | # [Episode 16](https://www.youtube.com/watch?v=lW_erSjyMeM&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=18): JS Engine EXPOSED 🔥 Google's V8 Architecture 🚀 2 | 3 | ### JavaScript Runtime Environment 4 | 5 | JRE: JS Engine + Web APIs + Callback Queues + Microtask Queues + Event Loop and more interesting things. 6 | 7 | There are various JREs. Most common is the Browser. 8 | 9 | Node.js is the Runtime Environment that has everything required as a runtime and can be ran outside the browser as well. 10 | 11 | ### Various JS Engines: 12 | 13 | First JS engine developed was SpiderMonkey. SpiderMonkey is the engine used by Mozilla Firefox. 14 | 15 | Fastest JS Engine currently is V8. V8 is used by chrome, Node.js and Deno as well. 16 | 17 | Other engines are Chakra, Tamarin etc. 18 | 19 | ### JS Engine: 20 | 21 | JS Engine is the heart of JRE. 22 | 23 | It executes JS code. 24 | 25 | It majorly contains two things: Call Stack and Memory Heap. 26 | 27 | It executes the JS code in 3 steps. 28 | 29 | 1. Parsing: First the JS engine converts the JS code into tokens. Then it converts it into "Abstract Syntax Tree" known as AST. It is basically a syntax parser. Refer [this](https://astexplorer.net/) 30 | 31 | 2. Compilation: JavaScript has JIT Compilation i.e. Just In Time Compilation. It uses both Interpreter and Compiler for compilation of the code. All JS Engines have own algorithms of compilations. All these JS engine's job is to optimize the code as much as it can. 32 | 33 | 3. Execution: Memory Heap is space where functions and vars are assigned memory and works in sync with the Call stack. Mark and Sweep Algorithm is famous garbage collector algorithm. Inlining, Copy Elision, Inline Caching etc. are imp compiler concepts. 34 | 35 | ### V8 Engine 36 | 37 | V8 Interpreter: Ignition -> Byte Code 38 | V8 compiler: TurboFan -> Creates Optimized Machine Code -> Byte code 39 | 40 | Compiler Optimizes and Interpreter executes. 41 | 42 | Garbage collector: Orinoco, Oilpan 43 | -------------------------------------------------------------------------------- /NamasteJS/E17 - TRUST ISSUES with setTimeout().md: -------------------------------------------------------------------------------- 1 | # [Episode 16](https://www.youtube.com/watch?v=lW_erSjyMeM&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=18): TRUST ISSUES with setTimeout() 2 | 3 | ### setTimeout() doesn't guarantee that it will exactly wait for X seconds 4 | 5 | * Why? Because suppose you have a timer of 5000ms. And after that the callback must be executed. 6 | 7 | * So, the Callback will go in the Web API waiting window. 8 | 9 | * Since JS waits for none, it continues its execution and call stack is filled with the other code. 10 | 11 | * Suppose we have a million lines of code in the program. 12 | 13 | * The Main Thread will be blocked for executing those million lines. 14 | 15 | * Suppose those million lines take 10s to execute. Our callback has already completed the timeout of 5s and is waiting inside the Callback Queue. 16 | 17 | * But we know that ONLY after the Call Stack is empty, the Callback queue can be emptied. And thus the Call Stack is being emptied after 10s. 18 | 19 | * Our expected waiting time was 5s in the time out but since the code takes 10s, it will execute the setTimeout() callback after the 10s only. 20 | 21 | * Thus it is not necessary that it will take exactly Xs that is defined in the setTimeout. 22 | 23 | * But it is certain that it will take ATLEAST 5s for the callback to execute and will wait there. 24 | 25 | ### setTimeout(cb,0) 26 | 27 | * What happens when the delay = 0? 28 | * Will it behave synchronously? No. 29 | * The setTimeout() is async Web API function and thus has to go through process of the Callback Queue and thus it will ONLY execute after the Main thread is executed and callback is empty. 30 | * It can be used to defer the code; i.e. if we want some code to execute at last of the code, we can use settimeout with 0s delay. 31 | -------------------------------------------------------------------------------- /NamasteJS/README.md: -------------------------------------------------------------------------------- 1 | ### __Resources📚__: 2 | 3 | * [NamasteJavaScript](https://www.youtube.com/playlist?list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP) by [Akshay Saini](https://www.linkedin.com/in/akshaymarch7/?originalSubdomain=in) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # < JavaScriptONLY />👨‍💻 🙏 2 | 3 | ### Its an attempt to provide high quality, well-written set of notes and code-snippets for anyone who wants to learn and refer JavaScript concepts in deep. 4 | 5 | --- 6 | 7 | #### This repository will be your go-to place when you feel to write better and cleaner code for your project, want to debug without frustration and cursing JS or to praise the beauty of this language in real sense. 8 | 9 | --- 10 | 11 | > JavaScript is Beautiful ♥. But it takes the eyes of the coder to admire ~ *anonymous*✨ 12 | 13 | --- 14 | 15 | ### **We love Contributions💖**: 16 | 17 | Feel free to create an issue about what topic you want to add explanations or code snippets that covers core JS concepts in a better and lucid way. Link a PR with it and we are ready to accept your contributions! Refer [this](https://github.com/sohamsshah/JavaScriptONLY/blob/master/CONTRIBUTING.md) for more insights. 18 | 19 | ### How can I contribute? 20 | 21 | - If you are into Data Structures and Algorithms ft. JavaScript, contribute by adding your favourite ones to [here](/DSA) 22 | - Following Striver's [SDE-Sheet](https://docs.google.com/document/d/1SM92efk8oDl8nyVw8NHPnbGexTS9W-1gmTEYfEurLWQ/edit)? We believe that it is a good resource to prepare for DSA rounds. Contribute your JS Solutions from the sheet [here](/SDE_Sheet)! 23 | - If you are practicing JavaScript Interview Questions, share your approach and learnings [here](/InterviewQuestions) 24 | - Have got Code Snippets in JavaScript? Dump them in [here](/Snippets) 25 | - Love taking Notes? We are looking for contributions to [NamasteJS](/NamasteJS) and [EloquentJS](/EloquentJS) currently! 26 | - Into Documentation? Presently, a lot of code isn't well documented. We need to maintain a README.md for each sections! Help will be appreciated there. 27 | - Feel Free to Raise Issues and create PRs :) 28 | 29 | --- 30 | 31 | ### Contributors💻: 32 | 33 | As always, thanks to our amazing contributors who are making the world fall in love with JavaScript 💛! 34 | 35 | 36 | 37 | 38 | 39 | --- 40 | -------------------------------------------------------------------------------- /ReferenceBooks/(You Don't Know JS) Kyle Simpson - You Don't Know JS_ Async & Performance-O'Reilly Media (2015).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/ReferenceBooks/(You Don't Know JS) Kyle Simpson - You Don't Know JS_ Async & Performance-O'Reilly Media (2015).pdf -------------------------------------------------------------------------------- /ReferenceBooks/(You Don't Know JS) Kyle Simpson - You Don't Know JS_ Scope & Closures-O'Reilly Media (2014).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/ReferenceBooks/(You Don't Know JS) Kyle Simpson - You Don't Know JS_ Scope & Closures-O'Reilly Media (2014).pdf -------------------------------------------------------------------------------- /ReferenceBooks/Daniel_Parker-JavaScript_with_Promises-EN.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/ReferenceBooks/Daniel_Parker-JavaScript_with_Promises-EN.pdf -------------------------------------------------------------------------------- /ReferenceBooks/Eloquent JavaScript.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/ReferenceBooks/Eloquent JavaScript.pdf -------------------------------------------------------------------------------- /ReferenceBooks/JavaScript-The-Definitive-Guide-Master-The-Worlds-Most-Used-Programming-Language-7th-Edition.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/ReferenceBooks/JavaScript-The-Definitive-Guide-Master-The-Worlds-Most-Used-Programming-Language-7th-Edition.pdf -------------------------------------------------------------------------------- /ReferenceBooks/Kyle Simpson - You Don't Know JS_ Types & Grammar-O'Reilly Media (2015).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/ReferenceBooks/Kyle Simpson - You Don't Know JS_ Types & Grammar-O'Reilly Media (2015).pdf -------------------------------------------------------------------------------- /ReferenceBooks/Kyle Simpson - You Don't Know JS_ Up & Going-O'Reilly Media (2015).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/ReferenceBooks/Kyle Simpson - You Don't Know JS_ Up & Going-O'Reilly Media (2015).pdf -------------------------------------------------------------------------------- /ReferenceBooks/Kyle Simpson - You Don't Know JS_ this & Object Prototypes-O'Reilly Media (2014).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/ReferenceBooks/Kyle Simpson - You Don't Know JS_ this & Object Prototypes-O'Reilly Media (2014).pdf -------------------------------------------------------------------------------- /ReferenceBooks/web-dev-handbook.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/ReferenceBooks/web-dev-handbook.pdf -------------------------------------------------------------------------------- /ReferenceBooks/you_dont_know_js_es6_beyond__PDFDrive_.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/ReferenceBooks/you_dont_know_js_es6_beyond__PDFDrive_.pdf -------------------------------------------------------------------------------- /SDE_Sheet/IntersectionOfTwoLinkedLists.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val) { 4 | * this.val = val; 5 | * this.next = null; 6 | * } 7 | */ 8 | 9 | /** 10 | * @param {ListNode} headA 11 | * @param {ListNode} headB 12 | * @return {ListNode} 13 | */ 14 | var getIntersectionNode = function(headA, headB) { 15 | 16 | let shortList 17 | let longList 18 | let sizeA = headA 19 | let sizeB = headB 20 | let lengthA = 0 21 | let lengthB = 0 22 | while (sizeA!==null || sizeB!==null){ 23 | if(sizeA !== null) { 24 | sizeA = sizeA.next 25 | lengthA ++ 26 | } 27 | if(sizeB !==null) { 28 | sizeB = sizeB.next 29 | lengthB ++ 30 | } 31 | } 32 | //starts the longest list index, to the starting point of short list 33 | //the idea is that an intersection of a node will ALWAYS be at the end. 34 | //therefore, SAME SIZE lists will reach the intersection value at the same time 35 | let sizeDiff = Math.abs(lengthA - lengthB) 36 | 37 | if(lengthB > lengthA) { 38 | shortList = headA 39 | longList = headB 40 | } else { 41 | shortList = headB 42 | longList = headA 43 | } 44 | 45 | while(shortList.next !== null || longList.next !== null){ 46 | if(sizeDiff<1){ 47 | if(shortList === longList) return shortList 48 | shortList = shortList.next 49 | } 50 | longList = longList.next 51 | sizeDiff-- 52 | } 53 | //catch any 1 length lists 54 | if(shortList === longList) return shortList 55 | return shortList.next 56 | }; 57 | -------------------------------------------------------------------------------- /SDE_Sheet/LongestSubstringWithoutRepeatingCharacters.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLongestSubstring(String s) { 3 | int maxl = 0; 4 | Map charIdxMap = new HashMap(); //O(1) space 5 | 6 | char c; 7 | int startIdx = 0; 8 | int i; 9 | for(i=0; i= startIdx){ 12 | maxl = Math.max(maxl, i-startIdx); 13 | startIdx = charIdxMap.get(c) + 1; 14 | } 15 | 16 | charIdxMap.put(c, i); 17 | } 18 | 19 | maxl = Math.max(maxl, i-startIdx); 20 | 21 | return maxl; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /SDE_Sheet/MiddleOfTheLinkedList.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode middleNode(ListNode head) { 13 | ListNode slow = head; 14 | ListNode fast = head; 15 | 16 | while(fast != null && fast.next != null){ 17 | fast = fast.next.next; 18 | slow = slow.next; 19 | } 20 | return slow; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /SDE_Sheet/ReverseLinkedList.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode reverseList(ListNode head) { 13 | Stack stack =new Stack(); 14 | while(head!=null) 15 | { 16 | stack.push(head); 17 | head = head.next; 18 | } 19 | ListNode dummy = new ListNode(-1); 20 | head=dummy; 21 | while(!stack.isEmpty()) 22 | { 23 | ListNode current= stack.pop(); 24 | head.next=new ListNode(current.val); 25 | head=head.next; 26 | } 27 | return dummy.next; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /SDE_Sheet/findDuplicate.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var findDuplicate = function(arr) { 6 | var slow = arr[0] 7 | var fast = arr[0] 8 | 9 | do{ 10 | slow = arr[slow] 11 | fast = arr[arr[fast]] 12 | }while(slow !== fast) 13 | 14 | fast = arr[0] 15 | while(slow != fast){ 16 | fast = arr[fast] 17 | slow = arr[slow] 18 | } 19 | return fast 20 | 21 | }; -------------------------------------------------------------------------------- /SDE_Sheet/mergeIntervals.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} intervals 3 | * @return {number[][]} 4 | */ 5 | var merge = function(intervals) { 6 | intervals.sort((a,b) => a[0]-b[0]) 7 | var res = [] 8 | 9 | var tempInterval = intervals[0] 10 | for(let i=0; i < intervals.length; i++){ 11 | if(tempInterval[1] >= intervals[i][0]){ 12 | tempInterval[1] = Math.max(intervals[i][1], tempInterval[1]) 13 | } else{ 14 | res.push(tempInterval) 15 | tempInterval = intervals[i] 16 | } 17 | } 18 | res.push(tempInterval) 19 | return res 20 | }; -------------------------------------------------------------------------------- /SDE_Sheet/mergeTwoSortedArrays.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | //Function to merge the arrays. 4 | merge(arr1, arr2, n, m) { 5 | function updateArr(arr){ 6 | for(let i = 1; i < arr.length; i++){ 7 | if(arr[i] < arr[i-1]){ 8 | [arr[i], arr[i-1]] = [arr[i-1], arr[i]] 9 | } 10 | } 11 | return arr 12 | } 13 | 14 | 15 | for(let i=0; i < arr1.length; i++){ 16 | if(arr1[i] > arr2[0]){ 17 | [arr1[i], arr2[0]] = [arr2[0], arr1[i]] 18 | arr2 = updateArr(arr2); 19 | } 20 | } 21 | 22 | } 23 | } -------------------------------------------------------------------------------- /SDE_Sheet/nextPermutation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {void} Do not return anything, modify nums in-place instead. 4 | */ 5 | var nextPermutation = function(nums) { 6 | let index_1 = -1; 7 | let index_2 = -1; 8 | for(let i=nums.length-2; i>=0; i--){ 9 | if(nums[i] < nums[i+1]){ 10 | index_1 = i; 11 | break; 12 | } 13 | } 14 | for(let i=nums.length-1; i>=0; i--){ 15 | if(nums[i] > nums[index_1]){ 16 | index_2 = i; 17 | break; 18 | } 19 | } 20 | // swap 21 | [nums[index_1], nums[index_2]] = [nums[index_2], nums[index_1]] 22 | 23 | // reverse the latter half 24 | let x = index_1 + 1; 25 | let y = nums.length - 1 26 | 27 | while (x < y){ 28 | [nums[x], nums[y]] = [nums[y], nums[x]] 29 | x++; 30 | y--; 31 | } 32 | 33 | }; -------------------------------------------------------------------------------- /SDE_Sheet/pascalTriangle.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} numRows 3 | * @return {number[][]} 4 | */ 5 | var generate = function(numRows) { 6 | let firstCol = [1]; 7 | let secondCol = [1,1] 8 | 9 | if(numRows === 1){ 10 | return [firstCol]; 11 | } 12 | if(numRows === 2){ 13 | return [firstCol,secondCol] 14 | } 15 | 16 | let res = [firstCol, secondCol]; 17 | 18 | for(let i=0; i < numRows - 2; i++){ 19 | let temp = [...res].pop() 20 | let col = [] 21 | for(let j=0; j < temp.length-1; j++){ 22 | col.push(temp[j]+temp[j+1]) 23 | } 24 | res.push([1, ...col, 1]) 25 | } 26 | return (res); 27 | 28 | }; -------------------------------------------------------------------------------- /SDE_Sheet/setMatrixZeros.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {void} Do not return anything, modify matrix in-place instead. 4 | */ 5 | var setZeroes = function(matrix) { 6 | let col0 = 1; 7 | let rows = matrix.length; 8 | let cols = matrix[0].length; 9 | 10 | for(let i=0; i < rows; i++){ 11 | if(matrix[i][0] === 0){ 12 | col0 = 0; 13 | } 14 | for(let j=1; j < cols; j++){ 15 | if(matrix[i][j] === 0){ 16 | matrix[i][0] = 0; 17 | matrix[0][j] = 0; 18 | } 19 | } 20 | } 21 | 22 | for(let i=rows-1; i >= 0; i--){ 23 | for(let j=cols-1; j>=1; j--){ 24 | if(matrix[i][0] === 0 || matrix[0][j] == 0){ 25 | matrix[i][j] = 0; 26 | } 27 | } 28 | if(col0 === 0){ 29 | matrix[i][0] = 0; 30 | } 31 | } 32 | 33 | }; -------------------------------------------------------------------------------- /SDE_Sheet/sortColors.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {void} Do not return anything, modify nums in-place instead. 4 | */ 5 | var sortColors = function(nums) { 6 | low = 0; 7 | mid = 0; 8 | high = nums.length -1 9 | 10 | while(mid <= high){ 11 | if(nums[mid] === 0){ 12 | [nums[mid], nums[low]] = [nums[low], nums[mid]] 13 | mid++ 14 | low++ 15 | } else if(nums[mid] === 1){ 16 | mid++ 17 | } else if(nums[mid] === 2){ 18 | [nums[mid], nums[high]] = [nums[high], nums[mid]] 19 | high-- 20 | } 21 | } 22 | 23 | }; -------------------------------------------------------------------------------- /SDE_Sheet/stocksBuyAndSell.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} prices 3 | * @return {number} 4 | */ 5 | var maxProfit = function(prices) { 6 | let maxProfit = 0; 7 | let minPrice = Number.POSITIVE_INFINITY; 8 | for(let x in prices){ 9 | minPrice = Math.min(minPrice, prices[x]); 10 | maxProfit = Math.max(maxProfit, prices[x] - minPrice); 11 | } 12 | 13 | 14 | return maxProfit 15 | 16 | }; -------------------------------------------------------------------------------- /SDE_Sheet/twoSum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} target 4 | * @return {number[]} 5 | */ 6 | /* A brute-force approach. Traverse the nums array via two pointers i and j and return 7 | indexes stored in an array if the total matches the target*/ 8 | var twoSum = function(nums, target) { 9 | let targetResult =[]; 10 | 11 | for(let i =0; i< nums.length; i++){ 12 | for(let j = i+1; j< nums.length; j++){ 13 | 14 | if( nums[i]+ nums[j] === target){ 15 | 16 | targetResult.push(i); 17 | targetResult.push(j); 18 | } 19 | } 20 | } 21 | 22 | return targetResult; 23 | }; -------------------------------------------------------------------------------- /Snippets/Arrays/arraySubset.js: -------------------------------------------------------------------------------- 1 | const arr1 = [2, 3, 4, 5, 6, 88, 9]; 2 | const arr2 = [3, 3, 3, 5, 100]; 3 | 4 | function isSubset(arr1, arr2) { 5 | const arr1Set = []; 6 | const arr2Set = []; 7 | 8 | arr1.forEach((item) => { 9 | if (!arr1Set.includes(item)) { 10 | arr1Set.push(item); 11 | } 12 | }); 13 | arr2.forEach((item) => { 14 | if (!arr2Set.includes(item)) { 15 | arr2Set.push(item); 16 | } 17 | }); 18 | 19 | const res = arr1Set.reduce((previousValue, currentValue) => { 20 | return previousValue + +arr2Set.includes(currentValue); 21 | }, 0); 22 | return res === arr2Set.length; 23 | } 24 | 25 | console.log(isSubset(arr1, arr2)); 26 | -------------------------------------------------------------------------------- /Snippets/Arrays/atPolyfill.js: -------------------------------------------------------------------------------- 1 | Array.prototype.myAt = myAt; 2 | 3 | function myAt(index) { 4 | if (index >= 0) { 5 | return this[index]; 6 | } 7 | return this[this.length - -index]; 8 | } 9 | 10 | console.log([1, 2, 3].myAt(-4)); 11 | -------------------------------------------------------------------------------- /Snippets/Arrays/checkItemPresentInArray.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Problem: Checks whether the dish you wish to eat is available in the menu 3 | */ 4 | 5 | let polarBearMenu = [ 6 | "Chocolate Fudge", 7 | "Death by chocolate", 8 | "Gudbud", 9 | "Fruit zest", 10 | ]; 11 | 12 | let isYourDishAvailable = false; 13 | let itemYouWishToEat = "Gudbud"; 14 | 15 | for (let itemNumber = 0; itemNumber < polarBearMenu.length; itemNumber++) { 16 | if (polarBearMenu[itemNumber] === itemYouWishToEat) { 17 | console.log("Yay " + itemYouWishToEat + " is there in the menu"); 18 | isYourDishAvailable = true; 19 | break; 20 | } else { 21 | isYourDishAvailable = false; 22 | } 23 | } 24 | 25 | if (!isYourDishAvailable) { 26 | console.log("Oops! " + itemYouWishToEat + " is not available. Try searching at a different place."); 27 | } 28 | -------------------------------------------------------------------------------- /Snippets/Arrays/checkItemPresentInArrayUsingMethod.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: Checks whether pizza is available in the menu 3 | */ 4 | 5 | let polarBearMenu = [ 6 | "Chocolate Fudge", 7 | "Death by chocolate", 8 | "Gudbud", 9 | "Fruit zest", 10 | ]; 11 | 12 | let itemYouWishToEat = "Gudbud"; 13 | 14 | if (polarBearMenu.includes(itemYouWishToEat)) { 15 | console.log(itemYouWishToEat + " is present in the menu "); 16 | } else { 17 | console.log(itemYouWishToEat + " is not present in the menu"); 18 | } -------------------------------------------------------------------------------- /Snippets/Arrays/checkPositionOfElementInArray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Check the position of IPL teams in 2021 3 | */ 4 | 5 | let iplTeams = ["CSK", "KKR", "DC", "RCB", "MI", "PBKS", "RR", "SRH"]; 6 | let iplTeamPositionYouWantToKnow = "MI"; 7 | console.log(iplTeams.indexOf(iplTeamPositionYouWantToKnow) + 1); 8 | -------------------------------------------------------------------------------- /Snippets/Arrays/convertArrayToString.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Convert given array to string 3 | */ 4 | 5 | const numbers = [1, 2, 3, 4, 5]; 6 | console.log(Array.isArray(numbers)); // true since numbers is an array 7 | console.log(numbers.join(",")); // 1,2,3,4,5 8 | console.log(typeof numbers.join(",")); // string 9 | 10 | const names = ["Javascript", "Python", "PHP"]; 11 | console.log(names.join(",")); // 'Javascript', 'Python', 'PHP' 12 | 13 | -------------------------------------------------------------------------------- /Snippets/Arrays/filterPolyfill.js: -------------------------------------------------------------------------------- 1 | Array.prototype.myFilter = myFilter; 2 | 3 | function myFilter(cb) { 4 | const filteredArr = []; 5 | this.forEach((item) => { 6 | if (cb(item)) { 7 | filteredArr.push(item); 8 | } 9 | }); 10 | return filteredArr; 11 | } 12 | 13 | const arr = [1, 2, 3, 4]; 14 | console.log(arr.myFilter((item) => item !== 2)); 15 | -------------------------------------------------------------------------------- /Snippets/Arrays/flattenADeeplyNestedArray.js: -------------------------------------------------------------------------------- 1 | function flattenArray(arr, n = Infinity) { 2 | let res = []; 3 | for (i in arr) { 4 | if (n !== 0 && Array.isArray(arr[i])) { 5 | res.push(...flattenArray(arr[i], n - 1)); 6 | } else { 7 | res.push(arr[i]); 8 | } 9 | } 10 | return res; 11 | } 12 | let input = [ 13 | 1, 14 | 2, 15 | 3, 16 | [4], 17 | [5, 6, [7], [8, [9, [10]]]], 18 | 11, 19 | 12, 20 | 13, 21 | [14, [[[[[15, [16]]]]]]], 22 | 17, 23 | 18, 24 | [19, [20, [21, [22, [23, [24, [[[[[25]]]]]]]]]]], 25 | ]; 26 | 27 | console.log(flattenArray(input, 2)); 28 | -------------------------------------------------------------------------------- /Snippets/Arrays/mapPolyfill.js: -------------------------------------------------------------------------------- 1 | Array.prototype.myMap = myMap; 2 | 3 | function myMap(cb) { 4 | const newArr = []; 5 | for (let i = 0; i < this.length; i++) { 6 | newArr.push(cb(this[i])); 7 | } 8 | return newArr; 9 | } 10 | const arr = [1, 2, 3, 4, 5]; 11 | 12 | console.log(arr.myMap((item) => item + 2)); 13 | -------------------------------------------------------------------------------- /Snippets/Arrays/pushPolyfill.js: -------------------------------------------------------------------------------- 1 | Array.prototype.myPush = myPush; 2 | 3 | function myPush(item) { 4 | this[this.length] = item; 5 | return this; 6 | } 7 | const arr = [1, 2, 3]; 8 | arr.myPush(2).push(2); // chaining possible 9 | console.log(arr); 10 | -------------------------------------------------------------------------------- /Snippets/Arrays/reducePolyfill.js: -------------------------------------------------------------------------------- 1 | Array.prototype.myReduce = myReduce; 2 | 3 | function myReduce(cb, initialValue = this[0]) { 4 | let result = initialValue; 5 | this.forEach((item) => { 6 | result = cb(result, item); 7 | }); 8 | return result; 9 | } 10 | 11 | const array1 = [1, 2, 3, 4]; 12 | const sumWithInitial = array1.myReduce( 13 | (previousValue, currentValue) => previousValue + currentValue, 14 | 0 15 | ); 16 | 17 | console.log(sumWithInitial); 18 | -------------------------------------------------------------------------------- /Snippets/Arrays/removeDuplicates.js: -------------------------------------------------------------------------------- 1 | const arr = [1, 2, 2, 3]; 2 | 3 | const updatedArrWithSet = [...new Set(arr)]; 4 | 5 | const updatedArrWithFilter = arr.filter((c, index) => { 6 | return index !== arr.indexOf(c); 7 | }); 8 | 9 | const updatedArrWithIncludes = []; 10 | arr.forEach((c) => { 11 | if (!updatedArrWithIncludes.includes(c)) { 12 | updatedArrWithIncludes.push(c); 13 | } 14 | }); 15 | 16 | console.log(updatedArrWithIncludes); 17 | -------------------------------------------------------------------------------- /Snippets/Arrays/unshiftPolyfill.js: -------------------------------------------------------------------------------- 1 | Array.prototype.myUnshift = myUnshift; 2 | 3 | function myUnshift(item) { 4 | let prevItem = item; 5 | const originalLength = this.length; 6 | for (let i = 0; i <= originalLength; i++) { 7 | let temp = this[i]; 8 | this[i] = prevItem; 9 | prevItem = temp; 10 | } 11 | return this; 12 | } 13 | 14 | const arr = [1, 2, 3, 4]; 15 | arr 16 | .myUnshift(2) 17 | .myUnshift(100) 18 | .myUnshift(() => console.log("WOW")); 19 | console.log(arr); 20 | -------------------------------------------------------------------------------- /Snippets/Async/Thanos.js: -------------------------------------------------------------------------------- 1 | const willTanosKillMe = (name, Kills, Safe) => { 2 | if(name.length%2 === 0){ 3 | Kills(); 4 | }else{ 5 | Safe() 6 | } 7 | } 8 | 9 | willTanosKillMe("SohamS", () => console.log("DedXD"), () => console.log("Safe")); -------------------------------------------------------------------------------- /Snippets/Async/printAfterDelay.js: -------------------------------------------------------------------------------- 1 | const printAfterDelay = (msg, delay) => { 2 | setTimeout(() => console.log(msg), delay); 3 | } 4 | 5 | printAfterDelay("soham", 5000) -------------------------------------------------------------------------------- /Snippets/Async/setInterval.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/Snippets/Async/setInterval.js -------------------------------------------------------------------------------- /Snippets/Closures/armyOfFunctions.js: -------------------------------------------------------------------------------- 1 | function makeArmy() { 2 | let shooters = []; 3 | 4 | let i = 0; 5 | while (i < 10) { 6 | // we can use for loop with let i to avoid the problem 7 | let a = i; // avoid the closure problem of referencing same variable 8 | let shooter = function () { 9 | // create a shooter function, 10 | console.log(a); // that should show its number 11 | }; 12 | shooters.push(shooter); // and add it to the array 13 | i++; 14 | } 15 | 16 | // ...and return the array of shooters 17 | return shooters; 18 | } 19 | 20 | let army = makeArmy(); 21 | 22 | army[1](); 23 | army[9](); 24 | -------------------------------------------------------------------------------- /Snippets/Closures/filterThroughFunction.js: -------------------------------------------------------------------------------- 1 | const inBetween = (left, right) => { 2 | return function (x) { 3 | return x >= left && x <= right; 4 | }; 5 | }; 6 | 7 | const inArray = (arr) => { 8 | return function (x) { 9 | return arr.includes(x); 10 | }; 11 | }; 12 | 13 | let arr = [1, 2, 3, 4, 5, 6, 7]; 14 | 15 | console.log(arr.filter(inBetween(3, 6))); 16 | // or console.log(arr.filter((item) => inBetween(3, 6)(item))); 17 | 18 | console.log(arr.filter(inArray([1, 2, 10]))); 19 | -------------------------------------------------------------------------------- /Snippets/Closures/makeCounter.js: -------------------------------------------------------------------------------- 1 | function makeCounter() { 2 | let count = 0; 3 | 4 | return function () { 5 | return ++count; 6 | }; 7 | } 8 | 9 | let counter = makeCounter(); 10 | 11 | counter(); 12 | counter(); 13 | counter(); 14 | 15 | const count = counter(); 16 | 17 | console.log(count); 18 | -------------------------------------------------------------------------------- /Snippets/Closures/sortByFields.js: -------------------------------------------------------------------------------- 1 | let users = [ 2 | { name: "John", age: 20, surname: "Johnson" }, 3 | { name: "Pete", age: 18, surname: "Peterson" }, 4 | { name: "Ann", age: 19, surname: "Hathaway" }, 5 | ]; 6 | 7 | // Normal Approach will be 8 | //users.sort((a, b) => (a.name > b.name ? 1 : -1)); 9 | //users.sort((a, b) => (a.age > b.age ? 1 : -1)); 10 | 11 | // cleaner way 12 | const byField = (fieldName) => { 13 | return function (x, y) { 14 | return x[fieldName] > y[fieldName] ? 1 : -1; 15 | }; 16 | }; 17 | 18 | console.log(users.sort(byField("age"))); 19 | -------------------------------------------------------------------------------- /Snippets/Currying/advancedCurryImplementation.js: -------------------------------------------------------------------------------- 1 | function sum(a, b, c) { 2 | return a + b + c; 3 | } 4 | 5 | // function curry(fn) { 6 | // return function curried(...args) { 7 | // if (args.length >= fn.length) { 8 | // return fn.apply(this, args); 9 | // } else { 10 | // return function (...args2) { 11 | // return curried.apply(this, args.concat(args2)); 12 | // }; 13 | // } 14 | // }; 15 | // } 16 | 17 | function curry(func) { 18 | return function curried(...args) { 19 | if (args.length >= func.length) { 20 | return func.apply(this, args); 21 | } else { 22 | return function (...args2) { 23 | return curried.apply(this, args.concat(args2)); 24 | }; 25 | } 26 | }; 27 | } 28 | 29 | let curriedSum = curry(sum); 30 | 31 | console.log(curriedSum(1, 2, 3)); // 6, still callable normally 32 | console.log(curriedSum(1)(2, 3)); // 6, currying of 1st arg 33 | console.log(curriedSum(1)(2)(3)); 34 | -------------------------------------------------------------------------------- /Snippets/Currying/sumOfNNumbers.js: -------------------------------------------------------------------------------- 1 | let sum = function (a) { 2 | return function (b) { 3 | if (b) { 4 | return sum(a + b); 5 | } 6 | return a; 7 | }; 8 | }; 9 | 10 | const total = sum(1)(2)(3)(); 11 | console.log(total); 12 | -------------------------------------------------------------------------------- /Snippets/DataTypes/methodsOfPrimitives.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/Snippets/DataTypes/methodsOfPrimitives.js -------------------------------------------------------------------------------- /Snippets/FunctionalProgramming/General/arrayLength.js: -------------------------------------------------------------------------------- 1 | // finds array length 2 | 3 | function arrayLength(arr){ 4 | let len = 0; 5 | while(arr[len] !== undefined){ 6 | len+=1; 7 | } 8 | return len; 9 | 10 | } 11 | 12 | const array = [1,2,3]; 13 | console.log(arrayLength(array)); -------------------------------------------------------------------------------- /Snippets/FunctionalProgramming/General/charAt.js: -------------------------------------------------------------------------------- 1 | function charAt(string,ind){ 2 | return string[ind]; 3 | } 4 | 5 | console.log(charAt("neoGcamp",4)) -------------------------------------------------------------------------------- /Snippets/FunctionalProgramming/General/findMax.js: -------------------------------------------------------------------------------- 1 | function findMax(...args){ 2 | let max = -Infinity; 3 | for(let i=0; i= max){ 5 | max = args[i] 6 | } 7 | } 8 | return max; 9 | } 10 | 11 | const maximum = findMin(3,2,4,5,-2) 12 | console.log(maximum) -------------------------------------------------------------------------------- /Snippets/FunctionalProgramming/General/findMin.js: -------------------------------------------------------------------------------- 1 | function findMin(...args){ 2 | let min = Infinity; 3 | for(let i=0; i date2Transform)?date2:date1 6 | } 7 | 8 | minDate('02/05/2021', '24/01/2021') -------------------------------------------------------------------------------- /Snippets/FunctionalProgramming/General/power.js: -------------------------------------------------------------------------------- 1 | // returns power of a to n by Divide and Conquer 2 | function power(a,n){ 3 | if(n===0){ 4 | return 1; 5 | } 6 | 7 | if(n > 0){ 8 | if(n%2 === 0){ 9 | return power(a, n/2)*power(a,n/2) 10 | }else{ 11 | return power(a, Math.floor(n/2))*power(a,Math.floor(n/2))*a 12 | } 13 | } 14 | } 15 | 16 | let ans = power(2,10) 17 | console.log(ans) 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Snippets/FunctionalProgramming/General/replace.js: -------------------------------------------------------------------------------- 1 | function replace(arr, n, k){ 2 | for(let i=0;i=0; i--){ 15 | ret.push(arr[i]); 16 | } 17 | return ret; 18 | } 19 | 20 | console.log(reverseCharactersOfAWord("Soham Shah")) -------------------------------------------------------------------------------- /Snippets/FunctionalProgramming/General/secretCode.js: -------------------------------------------------------------------------------- 1 | function secretCode(string,n){ 2 | let temp = string.split(''); 3 | for(let i=0; i< temp.length;i+=1){ 4 | temp[i] = String.fromCharCode((string.charCodeAt(i)+(n%26))) 5 | } 6 | return temp.join(''); 7 | } 8 | 9 | secretCode("neogcamp",2) -------------------------------------------------------------------------------- /Snippets/FunctionalProgramming/General/toSentenceCase.js: -------------------------------------------------------------------------------- 1 | function toSentenceCase(sentence){ 2 | let sentencecaseArr = sentence.split(" "); 3 | for(let i in sentencecaseArr){ 4 | sentencecaseArr[i] = sentencecaseArr[i].split(''); 5 | sentencecaseArr[i][0] = sentencecaseArr[i][0].toUpperCase(); 6 | sentencecaseArr[i] = sentencecaseArr[i].join(''); 7 | } 8 | return sentencecaseArr.join(' '); 9 | } 10 | 11 | console.log(toSentenceCase("Hello world I am Soham")) -------------------------------------------------------------------------------- /Snippets/FunctionalProgramming/General/triangleType.js: -------------------------------------------------------------------------------- 1 | function triangleType(a,b,c){ 2 | if(((a < 180 && a > 0) || (b < 180 && b > 0) || (c < 180 && c > 0)) && (a+b+c === 180)){ 3 | if(a === b && b === c && a === c){ 4 | return "Equilateral" 5 | } 6 | else if((a===b && b !==c && c !== a) || (a!==b && b !==c && c === a) || (a!==b && b ===c && c !== a)){ 7 | return "Isosceles" 8 | } 9 | else{ 10 | return "Scalene" 11 | } 12 | } 13 | return "Not a Triangle" 14 | } 15 | 16 | const triangle = triangleType(140,20,20) 17 | console.log(triangle) -------------------------------------------------------------------------------- /Snippets/FunctionalProgramming/General/wordCounter.js: -------------------------------------------------------------------------------- 1 | function wordCounter(sentence){ 2 | return sentence.split(" ").length; 3 | } 4 | 5 | const words = wordCounter("We are neogrammers"); 6 | console.log(words) -------------------------------------------------------------------------------- /Snippets/FunctionalProgramming/HigherOrderFunctions/README.md: -------------------------------------------------------------------------------- 1 | # The One 2 | 3 | Write a function `compose()` that can take any number of arguments of functions and return a function which will run the given functions in order when called an argument. -------------------------------------------------------------------------------- /Snippets/FunctionalProgramming/HigherOrderFunctions/TheOne.js: -------------------------------------------------------------------------------- 1 | // Composing functions 2 | const increment = (n) => n + 1; 3 | const square = (n) => n * n; 4 | const cube = (n) => n*n*n 5 | 6 | // Compose Util Function 7 | function compose(...args){ 8 | return (num) => args.reduce((acc, cur) => cur(acc), num); 9 | } 10 | 11 | // Main 12 | const incrementThenSquareThenCube = compose(increment, square, cube); 13 | console.log(incrementThenSquareThenCube(5)); -------------------------------------------------------------------------------- /Snippets/Functions/bind.js: -------------------------------------------------------------------------------- 1 | let user = { 2 | firstName: "John", 3 | sayHi() { 4 | alert(`Hello, ${this.firstName}!`); 5 | }, 6 | }; 7 | 8 | let sayHi = user.sayHi.bind(user); // (*) 9 | 10 | // can run it without an object 11 | sayHi(); // Hello, John! 12 | 13 | setTimeout(sayHi, 1000); // Hello, John! 14 | 15 | // even if the value of user changes within 1 second 16 | // sayHi uses the pre-bound value which is reference to the old user object 17 | user = { 18 | sayHi() { 19 | alert("Another user in setTimeout!"); 20 | }, 21 | }; 22 | -------------------------------------------------------------------------------- /Snippets/Functions/bindAll.js: -------------------------------------------------------------------------------- 1 | // If an object has many methods and we plan to actively pass it around, then we could bind them all in a loop 2 | 3 | const user = { 4 | func1() { 5 | console.log("func 1"); 6 | }, 7 | func2() { 8 | console.log("func 2"); 9 | }, 10 | func3() { 11 | console.log("func 3"); 12 | }, 13 | }; 14 | 15 | for (let key in user) { 16 | if (typeof user[key] == "function") { 17 | user[key] = user[key].bind(user); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Snippets/Functions/boundFunctionMethod.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | function f() { 3 | console.log(this); // null 4 | } 5 | 6 | let user = { 7 | g: f.bind(null), 8 | }; 9 | 10 | // f(); 11 | user.g(); 12 | -------------------------------------------------------------------------------- /Snippets/Functions/call.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | let worker = { 3 | someMethod() { 4 | return 1; 5 | }, 6 | slow(x) { 7 | console.log("Called with", x); 8 | return x + this.someMethod(); // need a reference for this 9 | }, 10 | }; 11 | 12 | function cachingDecorator(func) { 13 | const cache = new Map(); 14 | return function (x) { 15 | if (cache.has(x)) { 16 | return cache.get(x); 17 | } 18 | const res = func.call(this, x); 19 | cache.set(x, res); 20 | return res; 21 | }; 22 | } 23 | 24 | worker.slow = cachingDecorator(worker.slow); // now make it caching 25 | 26 | console.log(worker.slow(2)); // works 27 | console.log(worker.slow(2)); // works, doesn't call the original (cached) 28 | -------------------------------------------------------------------------------- /Snippets/Functions/customSetInterval.js: -------------------------------------------------------------------------------- 1 | const mySetInterval = (callback, delay, ...args) => { 2 | let timerId = setTimeout( 3 | function tick(...args) { 4 | callback(...args); 5 | timerId = setTimeout(tick, delay, ...args); 6 | }, 7 | delay, 8 | ...args 9 | ); 10 | }; 11 | 12 | function cb(x, y) { 13 | console.log(x, y); 14 | } 15 | mySetInterval(cb, 2000, 1, 2); 16 | -------------------------------------------------------------------------------- /Snippets/Functions/debounceDecorator.js: -------------------------------------------------------------------------------- 1 | function debounce(func, delay) { 2 | let timeout; 3 | return function (...args) { 4 | if (timeout) { 5 | clearTimeout(timeout); 6 | } 7 | timeout = setTimeout(() => { 8 | func(...args); 9 | // func.apply(this, args) 10 | }, delay); 11 | }; 12 | } 13 | 14 | let f = debounce(console.log, 2000); 15 | 16 | f("a"); 17 | setTimeout(() => f("b"), 200); 18 | setTimeout(() => f("c"), 500); 19 | -------------------------------------------------------------------------------- /Snippets/Functions/delayDecorator.js: -------------------------------------------------------------------------------- 1 | function f(x) { 2 | console.log(x); 3 | } 4 | 5 | function delay(func, delay) { 6 | return function (...args) { 7 | setTimeout(() => { 8 | func.call(this, ...args); 9 | }, delay); 10 | }; 11 | } 12 | 13 | // create wrappers 14 | let f1000 = delay(f, 1000); 15 | let f1500 = delay(f, 1500); 16 | 17 | f1000("test"); // shows "test" after 1000ms 18 | f1500("test"); // shows "test" after 1500ms 19 | -------------------------------------------------------------------------------- /Snippets/Functions/fixFunctionThis.js: -------------------------------------------------------------------------------- 1 | function askPassword(ok, fail) { 2 | let password = "rockstar"; 3 | if (password == "rockstar") ok(); 4 | else fail(); 5 | } 6 | 7 | let user = { 8 | name: "John", 9 | 10 | loginOk() { 11 | console.log(`${this.name} logged in`); 12 | }, 13 | 14 | loginFail() { 15 | console.log(`${this.name} failed to log in`); 16 | }, 17 | }; 18 | 19 | askPassword(user.loginOk.bind(user), user.loginFail.bind(user)); 20 | 21 | // askPassword(() => user.loginOk(), () => user.loginFail()); 22 | -------------------------------------------------------------------------------- /Snippets/Functions/globalPartialFunctions.js: -------------------------------------------------------------------------------- 1 | function partial(func, ...argsBound) { 2 | return function (...args) { 3 | // (*) 4 | return func.call(this, ...argsBound, ...args); 5 | }; 6 | } 7 | 8 | // Usage: 9 | let user = { 10 | firstName: "John", 11 | say(time, phrase) { 12 | alert(`[${time}] ${this.firstName}: ${phrase}!`); 13 | }, 14 | }; 15 | 16 | // add a partial method with fixed time 17 | user.sayNow = partial( 18 | user.say, 19 | new Date().getHours() + ":" + new Date().getMinutes() 20 | ); 21 | 22 | user.sayNow("Hello"); 23 | -------------------------------------------------------------------------------- /Snippets/Functions/makeCounter.js: -------------------------------------------------------------------------------- 1 | const makeCounter = () => { 2 | const counter = () => { 3 | return counter.count++; 4 | }; 5 | counter.set = (val) => { 6 | counter.count = val; 7 | return counter.count; 8 | }; 9 | 10 | counter.decrease = () => { 11 | counter.count--; 12 | return counter.count; 13 | }; 14 | 15 | counter.count = 0; 16 | 17 | return counter; 18 | }; 19 | 20 | const counter = makeCounter(); 21 | 22 | console.log(counter()); 23 | console.log(counter.set(10)); 24 | console.log(counter.decrease()); 25 | -------------------------------------------------------------------------------- /Snippets/Functions/memoizeOne.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Do not change the function name 3 | **/ 4 | 5 | function memoizeOne(fn, isEqual) { 6 | let cache = {}; 7 | 8 | function hasher(args) { 9 | return args.join(","); 10 | } 11 | return function (...args) { 12 | const hash = hasher(args); 13 | if (cache[hash]) { 14 | return cache[hash]; 15 | } 16 | cache = {}; 17 | const res = fn.apply(null, args); 18 | cache[hash] = res; 19 | return res; 20 | }; 21 | } 22 | 23 | function add(a, b) { 24 | console.print("called"); 25 | return a + b; 26 | } 27 | 28 | function isEqual(a, b) { 29 | if (a === b) { 30 | return true; 31 | } 32 | return false; 33 | } 34 | const memoizeAdd = memoizeOne(add, isEqual); 35 | console.print(memoizeAdd(2, 3)); 36 | console.print(memoizeAdd(2, 3)); 37 | console.print(memoizeAdd(3, 4)); 38 | console.print(memoizeAdd(5, 6)); 39 | -------------------------------------------------------------------------------- /Snippets/Functions/multiArgumentCaching.js: -------------------------------------------------------------------------------- 1 | const worker = { 2 | slow(min, max) { 3 | console.log(`Called with ${min},${max}`); 4 | return min + max; 5 | }, 6 | }; 7 | 8 | function cachingDecorator(func, hash) { 9 | const cache = new Map(); 10 | return function (...args) { 11 | let key = hash(args); 12 | if (cache.has(key)) { 13 | return cache.get(key); 14 | } 15 | let res = func.apply(this, args); 16 | // or let res = func.call(this, ...args) 17 | cache.set(key, res); 18 | return res; 19 | }; 20 | } 21 | 22 | function hash(args) { 23 | // [].join.call(arguments) 24 | return args.join(); 25 | } 26 | 27 | worker.slow = cachingDecorator(worker.slow, hash); 28 | 29 | console.log(worker.slow(3, 5)); // works 30 | console.log("Again " + worker.slow(3, 5)); // same (cached) 31 | -------------------------------------------------------------------------------- /Snippets/Functions/namedFunctionExpression.js: -------------------------------------------------------------------------------- 1 | let sayHi = function func(who) { 2 | if (who) { 3 | console.log(`Hello, ${who}`); 4 | } else { 5 | func("Guest"); // Error: sayHi is not a function 6 | } 7 | }; 8 | 9 | let welcome = sayHi; 10 | sayHi = null; 11 | 12 | welcome(); // Error, the nested sayHi call doesn't work any more! 13 | -------------------------------------------------------------------------------- /Snippets/Functions/nestedSetTimeout.js: -------------------------------------------------------------------------------- 1 | let delay = 5000; 2 | 3 | let timerId = setTimeout(function request() { 4 | console.log("Send Request to server", delay); 5 | if (true) { 6 | // request failed due to server overload 7 | // increase the interval to the next run 8 | delay *= 2; 9 | } 10 | 11 | timerId = setTimeout(request, delay); 12 | }, delay); 13 | -------------------------------------------------------------------------------- /Snippets/Functions/newFunctionSyntax.js: -------------------------------------------------------------------------------- 1 | let sum = new Function("a", "b", "return a + b"); 2 | 3 | alert(sum(1, 2)); // 3 4 | 5 | let sayHi = new Function('alert("Hello")'); 6 | 7 | sayHi(); // Hello 8 | -------------------------------------------------------------------------------- /Snippets/Functions/outputEverySecond.js: -------------------------------------------------------------------------------- 1 | function printNumbers(from, to) { 2 | const timerId = setInterval( 3 | function f(to) { 4 | console.log(from); 5 | if (to === from) { 6 | clearInterval(timerId); 7 | } 8 | from = from + 1; 9 | }, 10 | 1000, 11 | to 12 | ); 13 | } 14 | 15 | printNumbers(1, 10); 16 | 17 | // with nested setTimeout 18 | 19 | function printNumbers(from, to) { 20 | let current = from; 21 | 22 | setTimeout(function go() { 23 | alert(current); 24 | if (current < to) { 25 | setTimeout(go, 1000); 26 | } 27 | current++; 28 | }, 1000); 29 | } 30 | 31 | // usage: 32 | printNumbers(5, 10); 33 | 34 | // runs immediately 35 | function printNumbers(from, to) { 36 | let current = from; 37 | 38 | function go() { 39 | alert(current); 40 | if (current == to) { 41 | clearInterval(timerId); 42 | } 43 | current++; 44 | } 45 | 46 | go(); 47 | let timerId = setInterval(go, 1000); 48 | } 49 | 50 | printNumbers(5, 10); 51 | -------------------------------------------------------------------------------- /Snippets/Functions/partialFunctions.js: -------------------------------------------------------------------------------- 1 | function mul(a, b) { 2 | return a * b; 3 | } 4 | 5 | const triple = mul.bind(null, 3); // alternative to this is to curry functions 6 | 7 | console.log(triple(4)); 8 | 9 | const user = { 10 | firstName: "Samyak Shah", 11 | }; 12 | function send(from, text, to) { 13 | return ` 14 | By: ${from} 15 | To: ${to} 16 | Message: 17 | ${text}, ${this.firstName}`; 18 | } 19 | 20 | const sendTo = send.bind(user, "soham@invact.com"); 21 | 22 | console.log(sendTo("Hello World", "samyak@neog.com")); 23 | -------------------------------------------------------------------------------- /Snippets/Functions/partialLogin.js: -------------------------------------------------------------------------------- 1 | function askPassword(ok, fail) { 2 | let password = prompt("Password?", ""); 3 | if (password == "rockstar") ok(); 4 | else fail(); 5 | } 6 | 7 | let user = { 8 | name: "John", 9 | 10 | login(result) { 11 | alert(this.name + (result ? " logged in" : " failed to log in")); 12 | }, 13 | }; 14 | 15 | askPassword(user.login.bind(user, true), user.login.bind(user, false)); // ? 16 | -------------------------------------------------------------------------------- /Snippets/Functions/polymorphism.js: -------------------------------------------------------------------------------- 1 | function ask(question, ...handlers) { 2 | let isYes = confirm(question); 3 | 4 | for (let handler of handlers) { 5 | if (handler.length == 0) { 6 | if (isYes) handler(); 7 | } else { 8 | handler(isYes); 9 | } 10 | } 11 | } 12 | 13 | // for positive answer, both handlers are called 14 | // for negative answer, only the second one 15 | ask( 16 | "Question?", 17 | () => alert("You said yes"), 18 | (result) => alert(result) 19 | ); 20 | -------------------------------------------------------------------------------- /Snippets/Functions/properties.js: -------------------------------------------------------------------------------- 1 | function sayHi() { 2 | console.log("Hi"); 3 | } 4 | 5 | console.log(sayHi.name); 6 | console.log(function () {}.name); // empty string 7 | 8 | function f1(a) {} 9 | function f2(a, b) {} 10 | function many(a, b, ...more) {} 11 | 12 | console.log(f1.length); // 1 13 | console.log(f2.length); // 2 14 | console.log(many.length); // 2 15 | 16 | // custom property 17 | 18 | function sayHi() { 19 | console.log("Hi"); 20 | 21 | // let's count how many times we run 22 | sayHi.counter++; 23 | } 24 | sayHi.counter = 0; // initial value 25 | 26 | sayHi(); // Hi 27 | sayHi(); // Hi 28 | 29 | console.log(`Called ${sayHi.counter} times`); // Called 2 times 30 | 31 | // counter with custom property 32 | 33 | function makeCounter() { 34 | // instead of: 35 | // let count = 0 36 | 37 | function counter() { 38 | return counter.count++; 39 | } 40 | 41 | counter.count = 0; 42 | 43 | return counter; 44 | } 45 | 46 | let counter = makeCounter(); 47 | alert(counter()); // 0 48 | alert(counter()); // 1 49 | -------------------------------------------------------------------------------- /Snippets/Functions/secondBind.js: -------------------------------------------------------------------------------- 1 | // A function cannot be re-bound 2 | function f() { 3 | console.log(this.name); 4 | } 5 | 6 | f = f.bind({ name: "John" }); 7 | z = f.bind({ name: "Ann" }); 8 | 9 | f(); // John 10 | z(); // John 11 | -------------------------------------------------------------------------------- /Snippets/Functions/setInterval.js: -------------------------------------------------------------------------------- 1 | // let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) 2 | 3 | // repeat with the interval of 2 seconds 4 | let timerId = setInterval(() => alert("tick"), 2000); 5 | -------------------------------------------------------------------------------- /Snippets/Functions/setTimeout.js: -------------------------------------------------------------------------------- 1 | // let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...) 2 | 3 | function sayHi(phrase, who) { 4 | alert(phrase + ", " + who); 5 | } 6 | 7 | setTimeout(sayHi, 1000, "Hello", "John"); // Hello, John 8 | 9 | // string also works 10 | setTimeout("alert('Hello')", 1000); 11 | 12 | // recommended 13 | setTimeout(() => alert("Hello"), 1000); 14 | 15 | // wrong! 16 | setTimeout(sayHi(), 1000); 17 | 18 | // clear timeout 19 | let timerId = setTimeout(() => alert("Hi")); 20 | clearTimeout(timerId); 21 | -------------------------------------------------------------------------------- /Snippets/Functions/spyDecorator.js: -------------------------------------------------------------------------------- 1 | function work(a, b) { 2 | console.log(a + b); // work is an arbitrary function or method 3 | } 4 | 5 | function spy(func) { 6 | wrapper.calls = []; 7 | function wrapper(...args) { 8 | const key = hash(args); 9 | func.call(this, ...args); 10 | wrapper.calls.push(key); 11 | } 12 | 13 | return wrapper; 14 | } 15 | 16 | const hash = (args) => { 17 | return args.join(); 18 | }; 19 | 20 | work = spy(work); 21 | 22 | work(1, 2); // 3 23 | work(4, 5); // 9 24 | 25 | console.log(work); 26 | 27 | for (let args of work.calls) { 28 | console.log("call:" + args); // "call:1,2", "call:4,5" 29 | } 30 | -------------------------------------------------------------------------------- /Snippets/Functions/sumWithArbitaryAmountOfBrackets.js: -------------------------------------------------------------------------------- 1 | const sum = (x) => { 2 | let total = x; 3 | return function by(y) { 4 | if (y === undefined) { 5 | return total; 6 | } else { 7 | total += y; 8 | return by; 9 | } 10 | }; 11 | }; 12 | 13 | console.log(sum(1)(2)(5)()); 14 | 15 | // But what if we need exactly like this: sum(1)(2)(5) for the result 16 | function sum(a) { 17 | let currentSum = a; 18 | 19 | function f(b) { 20 | currentSum += b; 21 | return f; 22 | } 23 | 24 | f.toString = function () { 25 | return currentSum; 26 | }; 27 | 28 | return f; 29 | } 30 | 31 | const val = sum(1)(8); // 3 32 | alert(val); // alert calls val.toString(). We can modify this function for our use case 33 | -------------------------------------------------------------------------------- /Snippets/Functions/throttleDecorator.js: -------------------------------------------------------------------------------- 1 | function throttle(func, delay) { 2 | let flag = true; 3 | return function (...args) { 4 | if (flag) { 5 | flag = false; 6 | setTimeout(() => { 7 | func.apply(this, args); 8 | flag = true; 9 | }); 10 | } 11 | }; 12 | } 13 | 14 | const f = (text) => { 15 | console.log(text); 16 | }; 17 | 18 | const f1000 = throttle(f, 1000); 19 | f1000("Hi I am 1000s throttle function"); 20 | -------------------------------------------------------------------------------- /Snippets/Functions/timeBomb.js: -------------------------------------------------------------------------------- 1 | // 5,4,3,2,1, Bang! 2 | 3 | function timeBomb(i) { 4 | return i === 0 ? "Bang" : i; 5 | } 6 | for (let i = 5; i >= 0; i--) { 7 | setTimeout(() => { 8 | console.log(timeBomb(i)); 9 | }, [(5 - i) * 1000]); 10 | } 11 | -------------------------------------------------------------------------------- /Snippets/Functions/transparentCaching.js: -------------------------------------------------------------------------------- 1 | const delay = (data, ms) => { 2 | setTimeout(() => console.log("computing", data), ms); 3 | }; 4 | let slow = async (x) => { 5 | await delay(x, 3000); 6 | return x; 7 | }; 8 | 9 | const cachingDecorator = (func) => { 10 | const cache = new Map(); 11 | return function (x) { 12 | if (cache.has(x)) { 13 | return cache.get(x); 14 | } 15 | const res = func(x); 16 | cache.set(x, res); 17 | return res; 18 | }; 19 | }; 20 | 21 | slow = cachingDecorator(slow); 22 | 23 | slow(4).then(slow(5)).then(slow(4)); 24 | 25 | console.log(await slow(5)); 26 | console.log(await slow(4)); 27 | -------------------------------------------------------------------------------- /Snippets/Objects/accumulator.js: -------------------------------------------------------------------------------- 1 | function Accumulator(initValue) { 2 | this.value = initValue; 3 | this.read = (payload) => { 4 | this.value += payload; 5 | }; 6 | } 7 | 8 | let accumulator = new Accumulator(1); // initial value 1 9 | 10 | accumulator.read(1); 11 | accumulator.read(8); 12 | 13 | console.log(accumulator.value); 14 | -------------------------------------------------------------------------------- /Snippets/Objects/bindPolyFill.js: -------------------------------------------------------------------------------- 1 | Function.prototype.myBind = myBind; 2 | 3 | function myBind(context, ...args1) { 4 | const newContext = this; 5 | return function (...args2) { 6 | newContext.apply(context, [...args1, ...args2]); 7 | }; 8 | } 9 | 10 | let user = { 11 | firstName: "John", 12 | sayHi(area, birthdate) { 13 | console.log(`Hello, ${this.firstName} from ${area}, born on ${birthdate}!`); 14 | }, 15 | }; 16 | 17 | let sayHi = user.sayHi.myBind(user, "Ahmedabad"); // (*) 18 | sayHi("26/06"); 19 | -------------------------------------------------------------------------------- /Snippets/Objects/calculator.js: -------------------------------------------------------------------------------- 1 | class Calculator { 2 | constructor(a, b) { 3 | this.a = a; 4 | this.b = b; 5 | } 6 | 7 | sum() { 8 | console.log(this.a); 9 | console.log(this.a + this.b); 10 | return this; 11 | } 12 | 13 | mul() { 14 | console.log(this.a * this.b); 15 | return this; 16 | } 17 | } 18 | 19 | const calculator = new Calculator(1, 2); 20 | calculator.sum(); 21 | calculator.mul(); 22 | 23 | // alternate way 24 | 25 | function Calc(a, b) { 26 | this.a = a; 27 | this.b = b; 28 | 29 | this.sum = () => { 30 | return this.a + this.b; 31 | }; 32 | this.mul = () => { 33 | return this.a * this.b; 34 | }; 35 | } 36 | 37 | const calc = new Calc(5, 2); 38 | console.log(calc.sum()); 39 | console.log(calc.mul()); 40 | 41 | // approach 2: with chaining 42 | 43 | function Calculator(initialValue) { 44 | this.total = initialValue; 45 | this.sum = function (a) { 46 | this.total += a; 47 | return this; 48 | }; 49 | this.sub = function (a) { 50 | this.total -= a; 51 | return this; 52 | }; 53 | this.misc = function (cb) { 54 | this.total = cb(this.total); 55 | return this; 56 | }; 57 | this.val = function () { 58 | return this.total; 59 | }; 60 | } 61 | 62 | const cal = new Calculator(2); 63 | console.print( 64 | cal 65 | .sum(2) 66 | .misc((val) => val + 100) 67 | .val() 68 | ); 69 | 70 | // approach 3: using functions 71 | 72 | function cal(initialValue) { 73 | let total = initialValue; 74 | 75 | function add(a) { 76 | total += a; 77 | return cal(total); 78 | } 79 | 80 | function val() { 81 | return total; 82 | } 83 | 84 | return { 85 | add, 86 | val, 87 | }; 88 | } 89 | 90 | console.print(cal(2).add(2).add(2).val()); 91 | -------------------------------------------------------------------------------- /Snippets/Objects/cloneObject.js: -------------------------------------------------------------------------------- 1 | // using copying properties 2 | 3 | let user = { 4 | name: "John", 5 | age: 30, 6 | }; 7 | 8 | let clone = {}; // the new empty object 9 | 10 | // let's copy all user properties into it 11 | for (let key in user) { 12 | clone[key] = user[key]; 13 | } 14 | 15 | // now clone is a fully independent object with the same content 16 | clone.name = "Pete"; // changed the data in it 17 | 18 | console.log(user.name); // still John in the original object 19 | 20 | // Using Object.assign 21 | 22 | let permissions1 = { canView: true }; 23 | let permissions2 = { canEdit: true }; 24 | 25 | // copies all properties from permissions1 and permissions2 into user 26 | Object.assign(user, permissions1, permissions2); 27 | 28 | // now user = { name: "John", canView: true, canEdit: true } 29 | 30 | Object.assign(user, { name: "Pete" }); 31 | 32 | console.log(user.name); // now user = { name: "Pete" } 33 | 34 | let clone2 = Object.assign({}, user); // shallow copy 35 | 36 | console.log(clone2); 37 | 38 | // clone in a different way 39 | 40 | let clone = Object.defineProperties({}, Object.getOwnPropertyDescriptors(obj)); 41 | -------------------------------------------------------------------------------- /Snippets/Objects/computedProperties.js: -------------------------------------------------------------------------------- 1 | const obj = {}; 2 | 3 | for (let i = 0; i < 10; i++) { 4 | obj[`field${i}`] = 1; 5 | } 6 | 7 | console.log(obj); 8 | 9 | let fruit = "apple"; 10 | let bag = { 11 | [fruit + "Computers"]: 5, // bag.appleComputers = 5 12 | }; 13 | -------------------------------------------------------------------------------- /Snippets/Objects/deepCopy.js: -------------------------------------------------------------------------------- 1 | const x = { b: [{ a: [1, 2, 3], b: [4, 5, 6], c: [7, 8, 9] }] }; 2 | const y = { b: [{ a: [1, 2, 3], b: [4, 5, 6], c: [7, 8, 9] }] }; 3 | 4 | const z = deepCopy(x); 5 | 6 | function deepCopy(obj) { 7 | let target = {}; 8 | const keys = Object.keys(obj); 9 | keys.forEach((key) => { 10 | if (typeof obj[key] === "object") { 11 | target[key] = deepCopy(obj[key]); 12 | } else { 13 | target[key] = obj[key]; 14 | } 15 | }); 16 | return target; 17 | } 18 | 19 | console.log(z); 20 | console.log(z === x); 21 | -------------------------------------------------------------------------------- /Snippets/Objects/immediatelyCalledConstructorFunction.js: -------------------------------------------------------------------------------- 1 | // create a function and immediately call it with new 2 | let user = new (function () { 3 | this.name = "John"; 4 | this.isAdmin = false; 5 | 6 | // ...other code for user creation 7 | // maybe complex logic and statements 8 | // local variables etc 9 | })(); 10 | -------------------------------------------------------------------------------- /Snippets/Objects/isEmpty.js: -------------------------------------------------------------------------------- 1 | const isEmpty = (obj) => { 2 | return Object.keys(obj).length; 3 | }; 4 | 5 | let schedule = {}; 6 | 7 | console.log(isEmpty(schedule)); // true 8 | 9 | schedule["8:30"] = "get up"; 10 | 11 | console.log(isEmpty(schedule)); // false 12 | -------------------------------------------------------------------------------- /Snippets/Objects/ladder.js: -------------------------------------------------------------------------------- 1 | // chaining 2 | 3 | let ladder = { 4 | step: 0, 5 | up() { 6 | this.step++; 7 | return this; 8 | }, 9 | down() { 10 | this.step--; 11 | return this; 12 | }, 13 | showStep: function () { 14 | // shows the current step 15 | console.log(this.step); 16 | }, 17 | }; 18 | 19 | ladder.up().down(); 20 | -------------------------------------------------------------------------------- /Snippets/Objects/methodsAndthis.js: -------------------------------------------------------------------------------- 1 | let user = { 2 | name: "Soham", 3 | age: 5, 4 | sayHi: function () { 5 | console.log("Hi " + this.name); 6 | }, 7 | }; 8 | 9 | let user2 = { 10 | name: "Ashutosh", 11 | age: 15, 12 | }; 13 | 14 | function makeUser() { 15 | return { 16 | name: "John", 17 | ref: this, 18 | }; 19 | } 20 | 21 | let user3 = makeUser(); 22 | 23 | console.log(user3.ref); // undefined in node / Error in browser 24 | 25 | function makeUser2() { 26 | return { 27 | name: "John", 28 | ref() { 29 | return this; 30 | }, 31 | }; 32 | } 33 | 34 | let user4 = makeUser2(); 35 | 36 | console.log(user4.ref().name); // John 37 | -------------------------------------------------------------------------------- /Snippets/Objects/multiplyNumeric.js: -------------------------------------------------------------------------------- 1 | const multiplyNumeric = (obj) => { 2 | for (key in obj) { 3 | if (typeof obj[key] === "number") { 4 | obj[key] *= 2; 5 | } 6 | } 7 | console.log(obj); 8 | }; 9 | // before the call 10 | let menu = { 11 | width: 200, 12 | height: 300, 13 | title: "My menu", 14 | }; 15 | 16 | multiplyNumeric(menu); 17 | -------------------------------------------------------------------------------- /Snippets/Objects/objectToPrimitiveConversion.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sohamsshah/JavaScriptONLY/8af48465775464b3637ecc8ae35b7a1e09722b73/Snippets/Objects/objectToPrimitiveConversion.js -------------------------------------------------------------------------------- /Snippets/Objects/orderedLikeObject.js: -------------------------------------------------------------------------------- 1 | let codes = { 2 | "+49": "Germany", 3 | "+41": "Switzerland", 4 | "+44": "Great Britain", 5 | // .., 6 | "+1": "USA", 7 | }; 8 | 9 | for (let code in codes) { 10 | console.log(+code); // 49, 41, 44, 1 11 | } 12 | 13 | codes = { 14 | 49: "Germany", 15 | 41: "Switzerland", 16 | 44: "Great Britain", 17 | // .., 18 | 1: "USA", 19 | }; 20 | 21 | console.log(codes); 22 | 23 | for (let code in codes) { 24 | console.log(code); // 1, 41, 44, 49 25 | } 26 | -------------------------------------------------------------------------------- /Snippets/Objects/propertyDescriptors.js: -------------------------------------------------------------------------------- 1 | let user = { 2 | name: "John", 3 | }; 4 | 5 | // get property 6 | let descriptor = Object.getOwnPropertyDescriptor(user, "name"); 7 | 8 | console.log(descriptor); 9 | 10 | // define property 11 | Object.defineProperty(user, "name", { 12 | value: "Soham", 13 | }); 14 | 15 | // non-writable 16 | Object.defineProperty(user, "name", { 17 | writable: false, 18 | }); 19 | 20 | // non-enumerable 21 | 22 | Object.defineProperty(user, "toString", { 23 | enumerable: false, 24 | }); 25 | 26 | // non-configurable 27 | 28 | Object.defineProperty(user, "name", { configurable: false }); 29 | 30 | // cannot even change other ennumberable and writable 31 | -------------------------------------------------------------------------------- /Snippets/Objects/propertyGetterSetter.js: -------------------------------------------------------------------------------- 1 | let obj = { 2 | name: "Soham", 3 | surname: "Shah", 4 | get fullName() { 5 | return `${this.name} ${this.surname}`; 6 | }, 7 | set propName(value) { 8 | [this.name, this.surname] = value.split(" "); 9 | }, 10 | }; 11 | 12 | // hiding a variable 13 | 14 | let user = { 15 | get name() { 16 | return this._name; 17 | }, 18 | 19 | set name(value) { 20 | if (value.length < 4) { 21 | alert("Name is too short, need at least 4 characters"); 22 | return; 23 | } 24 | this._name = value; 25 | }, 26 | }; 27 | 28 | user.name = "Pete"; 29 | alert(user.name); // Pete 30 | 31 | user.name = ""; 32 | -------------------------------------------------------------------------------- /Snippets/Objects/reference.js: -------------------------------------------------------------------------------- 1 | const user = { 2 | name: "Soham", 3 | }; 4 | 5 | const admin = user; 6 | 7 | console.log(admin); 8 | 9 | admin.name = "Dhruvi"; 10 | 11 | console.log(admin); 12 | 13 | user.name = "Samyak"; 14 | 15 | console.log(admin); 16 | 17 | console.log(admin == { name: "Samyak" }); 18 | -------------------------------------------------------------------------------- /Snippets/Objects/restAndspread.js: -------------------------------------------------------------------------------- 1 | // Rest 2 | 3 | function sumAll(...args) { 4 | // args is the name for the array 5 | let sum = 0; 6 | 7 | for (let arg of args) sum += arg; 8 | 9 | return sum; 10 | } 11 | 12 | console.log(sumAll(1, 2, 3)); 13 | 14 | function showName(firstName, lastName, ...titles) { 15 | console.log(firstName + " " + lastName); // Julius Caesar 16 | 17 | // the rest go into titles array 18 | // i.e. titles = ["Consul", "Imperator"] 19 | console.log(titles[0]); // Consul 20 | console.log(titles[1]); // Imperator 21 | console.log(titles.length); // 2 22 | } 23 | 24 | showName("Julius", "Caesar", "Consul", "Imperator"); 25 | 26 | // arguments array 27 | 28 | function showName2() { 29 | console.log(arguments.length); 30 | console.log(arguments[0]); 31 | console.log(arguments[1]); 32 | 33 | // it's iterable 34 | // for(let arg of arguments) console.log(arg); 35 | } 36 | 37 | // shows: 2, Julius, Caesar 38 | showName2("Julius", "Caesar"); 39 | 40 | // shows: 1, Ilya, undefined (no second argument) 41 | showName2("Ilya"); 42 | 43 | // BEWARE: Arrow Functions dont have "arguments" 44 | 45 | function f() { 46 | // If we access the arguments object from an arrow function, it takes them from the outer “normal” function. 47 | 48 | let showArg = () => console.log(arguments[0]); 49 | showArg(); 50 | } 51 | 52 | f(1); // 1 53 | 54 | // Spread 55 | 56 | let arr1 = [1, -2, 3, 4]; 57 | let arr2 = [8, 3, -8, 1]; 58 | 59 | console.log(Math.max(...arr1, ...arr2)); // 8 60 | 61 | let str = "Hello"; 62 | 63 | // Array.from converts an iterable and array-like object into an array 64 | console.log(Array.from(str)); // H,e,l,l,o 65 | 66 | // Array-like is an object that index and length property 67 | 68 | let arrLike = { 0: "foo", 5: "bar", length: 6 }; 69 | console.log(Array.from(arrLike)); 70 | 71 | console.log(Array.from([1, 2, 3], (x) => x + x)); 72 | -------------------------------------------------------------------------------- /Snippets/Polyfill/bind-polyfill.js: -------------------------------------------------------------------------------- 1 | // bind polyfill 2 | 3 | Function.prototype.customBind = function (...args) { 4 | let context = this; 5 | let params = args.slice(1); 6 | 7 | return function (...args2) { 8 | context.apply(args[0], [...params, ...args2]); 9 | }; 10 | }; 11 | -------------------------------------------------------------------------------- /Snippets/Polyfill/filter-polyfill.js: -------------------------------------------------------------------------------- 1 | // filter polyfill 2 | 3 | Array.prototype.customFilter = function (callbackFn) { 4 | const result = []; 5 | 6 | for (let i = 0; i < this.length; i++) { 7 | if (callbackFn.call(this, this[i], i)) { 8 | result.push(this[i]); 9 | } 10 | } 11 | return result; 12 | }; 13 | -------------------------------------------------------------------------------- /Snippets/Polyfill/forEach-polyfill.js: -------------------------------------------------------------------------------- 1 | // forEach polyfill 2 | 3 | Array.prototype.customForEach = function (callbackFn) { 4 | for (let i = 0; i < this.length; i++) { 5 | callbackFn.call(this, this[i], i); 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /Snippets/Polyfill/map-polyfill.js: -------------------------------------------------------------------------------- 1 | // map polyfill 2 | 3 | Array.prototype.customMap = function (callbackFn) { 4 | const result = []; 5 | 6 | for (let i = 0; i < this.length; i++) { 7 | result.push(callbackFn.call(this, this[i], i)); 8 | } 9 | return result; 10 | }; 11 | -------------------------------------------------------------------------------- /Snippets/Polyfill/promiseAll-polyfill.js: -------------------------------------------------------------------------------- 1 | // promise polyfill 2 | 3 | Promise.customAll = function (promiseArray) { 4 | return new Promise((resolve, reject) => { 5 | let completed = 0; 6 | const promiseResults = []; 7 | 8 | promiseArray.forEach((value, index) => { 9 | Promise.resolve(value) 10 | .then((result) => { 11 | completed++; 12 | promiseResults[index] = result; 13 | 14 | if (completed === promiseArray.length) { 15 | resolve(promiseResults); 16 | } 17 | }) 18 | .catch((err) => reject(err)); 19 | }); 20 | }); 21 | }; 22 | -------------------------------------------------------------------------------- /Snippets/Polyfill/reduce-polyfill.js: -------------------------------------------------------------------------------- 1 | // reduce polyfill 2 | 3 | Array.prototype.customReduce = function (callbackFn, initialValue) { 4 | let accumulator = initialValue; 5 | 6 | for (let i = 0; i < this.length; i++) { 7 | if (accumulator !== undefined) { 8 | accumulator = callbackFn.call(undefined, accumulator, this[i], i, this); 9 | } else { 10 | accumulator = this[i]; 11 | } 12 | } 13 | return accumulator; 14 | }; 15 | -------------------------------------------------------------------------------- /Snippets/Promises/asyncAwait.js: -------------------------------------------------------------------------------- 1 | function loadJson(url) { 2 | return fetch(url).then((response) => { 3 | if (response.status == 200) { 4 | return response.json(); 5 | } else { 6 | throw new Error(response.status); 7 | } 8 | }); 9 | } 10 | 11 | loadJson("https://javascript.info/no-such-user.json").catch(alert); // Error: 404 12 | 13 | async function loadJsonAsyncAwait(url) { 14 | const response = await fetch(url); 15 | if (response.status === 200) { 16 | return response.json(); 17 | } 18 | throw new Error(response.status); 19 | } 20 | 21 | loadJsonAsyncAwait("https://javascript.info/no-such-user.json").catch(alert); // Error: 404 22 | -------------------------------------------------------------------------------- /Snippets/Promises/callAsyncFromNonAsync.js: -------------------------------------------------------------------------------- 1 | async function wait() { 2 | await new Promise((resolve) => setTimeout(resolve, 3000)); 3 | 4 | return 10; 5 | } 6 | 7 | function f() { 8 | // get value from the promise by calling async code in sync func 9 | wait().then((value) => console.log(value)); 10 | } 11 | 12 | f(); 13 | -------------------------------------------------------------------------------- /Snippets/Promises/microtask.js: -------------------------------------------------------------------------------- 1 | const a = "5"; 2 | const promise = new Promise((resolve, reject) => { 3 | setTimeout(() => resolve(1), 3000); 4 | console.log("Inside promise"); // 1 5 | }); 6 | 7 | promise.then((val) => console.log("Promise", val)); // 3 8 | 9 | setTimeout(() => console.log("Set Timeout ran"), 3000); // 4 10 | 11 | console.log(a); // 2 12 | -------------------------------------------------------------------------------- /Snippets/Promises/noNeedToReturnPromiseInThenChain.js: -------------------------------------------------------------------------------- 1 | function first(num) { 2 | return Promise.resolve(num); // starting the then chain by returning a promise 3 | } 4 | 5 | function second(num) { 6 | return num + 1; // no need to return promise as this function is in 'then' chain 7 | } 8 | 9 | first(4) 10 | .then((valueOne) => second(valueOne)) 11 | .then((valueTwo) => console.log(valueTwo)); 12 | -------------------------------------------------------------------------------- /Snippets/Promises/promiseAPI.js: -------------------------------------------------------------------------------- 1 | /* 2 | There are 6 static methods of Promise class: 3 | 4 | Promise.all(promises) – waits for all promises to resolve and returns an array of their results. If any of the given promises rejects, it becomes the error of Promise.all, and all other results are ignored. 5 | Promise.allSettled(promises) (recently added method) – waits for all promises to settle and returns their results as an array of objects with: 6 | status: "fulfilled" or "rejected" 7 | value (if fulfilled) or reason (if rejected). 8 | Promise.race(promises) – waits for the first promise to settle, and its result/error becomes the outcome. 9 | Promise.any(promises) (recently added method) – waits for the first promise to fulfill, and its result becomes the outcome. If all of the given promises are rejected, AggregateError becomes the error of Promise.any. 10 | Promise.resolve(value) – makes a resolved promise with the given value. 11 | Promise.reject(error) – makes a rejected promise with the given error. 12 | 13 | */ 14 | Promise.race([ 15 | new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)), 16 | new Promise((resolve, reject) => 17 | setTimeout(() => reject(new Error("Whoops!")), 2000) 18 | ), 19 | new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000)), 20 | ]).then((value) => console.log(value)); 21 | -------------------------------------------------------------------------------- /Snippets/Promises/promiseAll.js: -------------------------------------------------------------------------------- 1 | Promise.myAll = function (promises) { 2 | return new Promise((resolve, reject) => { 3 | let results = []; 4 | let count = 0; 5 | let toBeRejected = false; 6 | 7 | promises.forEach((promise, index) => { 8 | if (toBeRejected) return; 9 | Promise.resolve(promise) 10 | .then((res) => { 11 | count += 1; 12 | results[index] = res; // maintaining the order 13 | if (count === promises.length) { 14 | resolve(results); 15 | } 16 | }) 17 | .catch((err) => { 18 | reject(err); 19 | toBeRejected = true; 20 | }); 21 | }); 22 | }); 23 | }; 24 | 25 | const promise1 = Promise.resolve(1); 26 | const promise2 = new Promise((resolve, reject) => 27 | setTimeout(() => resolve(2), 3000) 28 | ); 29 | const promise3 = 3; 30 | 31 | Promise.myAll([Promise.reject("bar"), promise1, promise2, promise3]) 32 | .then((value) => console.log(value)) 33 | .catch((err) => console.log(err)); 34 | -------------------------------------------------------------------------------- /Snippets/Promises/promiseAllSettled.js: -------------------------------------------------------------------------------- 1 | Promise.myAllSettled = function (promises) { 2 | let results = []; 3 | let count = 0; 4 | return new Promise((resolve, reject) => { 5 | promises.forEach((promise, index) => { 6 | Promise.resolve(promise) 7 | .then((value) => { 8 | count += 1; 9 | results[index] = value; 10 | if (count === promises.length) { 11 | resolve(results); 12 | } 13 | }) 14 | .catch((err) => { 15 | count += 1; 16 | results[index] = "Error: " + err; 17 | if (count === promises.length) { 18 | resolve(results); 19 | } 20 | }); 21 | }); 22 | }); 23 | }; 24 | 25 | const promise1 = Promise.resolve(1); 26 | const promise2 = new Promise((resolve, reject) => 27 | setTimeout(() => resolve(2), 3000) 28 | ); 29 | const promise3 = 3; 30 | 31 | Promise.myAllSettled([Promise.reject("bar"), promise1, promise2, promise3]) 32 | .then((value) => console.log(value)) 33 | .catch((err) => console.log(err)); 34 | -------------------------------------------------------------------------------- /Snippets/Promises/promiseAny.js: -------------------------------------------------------------------------------- 1 | Promise.myAny = function (promises) { 2 | let errList = []; 3 | let errCount = 0; 4 | return new Promise((resolve, reject) => { 5 | promises.forEach((promise, index) => { 6 | Promise.resolve(promise).then( 7 | (value) => { 8 | return resolve(value); 9 | }, 10 | (reason) => { 11 | errList[index] = reason; 12 | errCount += 1; 13 | if (errCount === promises.length) { 14 | return reject([ 15 | new AggregateError([errList], "All promises were rejected"), 16 | ]); 17 | } 18 | } 19 | ); 20 | }); 21 | }); 22 | }; 23 | 24 | const promise1 = Promise.resolve(1); 25 | const promise2 = new Promise((resolve, reject) => 26 | setTimeout(() => resolve(2), 3000) 27 | ); 28 | const promise3 = Promise.resolve(3); 29 | 30 | Promise.myAny([ 31 | Promise.reject("bar"), 32 | Promise.reject("foo"), 33 | Promise.reject("nice"), 34 | Promise.reject("wow"), 35 | ]) 36 | .then((value) => console.log(value)) 37 | .catch((err) => console.log(err)); 38 | 39 | Promise.any([ 40 | Promise.reject("bar"), 41 | Promise.reject("foo"), 42 | Promise.reject("nice"), 43 | Promise.reject("wow"), 44 | ]) 45 | .then((value) => console.log(value)) 46 | .catch((err) => console.log(err)); 47 | -------------------------------------------------------------------------------- /Snippets/Promises/promiseRace.js: -------------------------------------------------------------------------------- 1 | Promise.myRace = function (promises) { 2 | return new Promise((resolve, reject) => { 3 | promises.forEach((promise) => { 4 | Promise.resolve(promise).then( 5 | (value) => resolve(value), 6 | (reason) => reject(reason) 7 | ); 8 | }); 9 | }); 10 | }; 11 | 12 | const promise1 = Promise.resolve(1); 13 | const promise2 = new Promise((resolve, reject) => 14 | setTimeout(() => resolve(2), 3000) 15 | ); 16 | const promise3 = Promise.resolve(3); 17 | 18 | Promise.myRace([Promise.reject(new Error("bar")), promise1, promise2, promise3]) 19 | .then((value) => console.log(value)) 20 | .catch((err) => console.log("error")); 21 | 22 | Promise.race([Promise.reject("bar"), promise1, promise2, promise3]) 23 | .then((value) => console.log(value)) 24 | .catch((err) => console.log("error")); 25 | -------------------------------------------------------------------------------- /Snippets/Promises/resolveVsReturn.js: -------------------------------------------------------------------------------- 1 | function second() { 2 | return new Promise((resolve, reject) => { 3 | // resolve/reject happens only one time 4 | resolve(1); 5 | reject("Failed"); 6 | resolve(2); 7 | console.log("After resolve/reject"); // this will be printed first because aLl lines will be executed 8 | }); 9 | } 10 | 11 | function first() { 12 | second() 13 | .then((value) => console.log(value)) 14 | .catch((err) => console.log(err)); 15 | } 16 | 17 | first(); 18 | -------------------------------------------------------------------------------- /Snippets/Promises/retryNTimes.js: -------------------------------------------------------------------------------- 1 | // wait function 2 | const wait = (ms) => { 3 | return new Promise((resolve) => { 4 | setTimeout(() => resolve(), ms); 5 | }); 6 | }; 7 | 8 | const retryWithDelay = ( 9 | operation, 10 | retries = 3, 11 | delay = 50, 12 | finalErr = "Retry Failed" 13 | ) => { 14 | return new Promise((resolve, reject) => 15 | operation() 16 | .then(resolve) 17 | .catch((reason) => { 18 | console.log(retries); 19 | if (retries > 0) { 20 | return wait(delay) 21 | .then( 22 | retryWithDelay.bind(null, operation, retries - 1, delay, finalErr) 23 | ) 24 | .then(resolve) 25 | .catch(reject); 26 | } 27 | // throw final error 28 | return reject(finalErr); 29 | }) 30 | ); 31 | }; 32 | 33 | const getTestFunc = () => { 34 | let callCounter = 0; 35 | return async () => { 36 | callCounter += 1; 37 | 38 | if (callCounter) { 39 | throw new Error("Not yet"); 40 | } 41 | }; 42 | }; 43 | 44 | // Test the code 45 | const test = async () => { 46 | await retryWithDelay(getTestFunc(), 10, 1000); 47 | console.log("success"); 48 | }; 49 | 50 | // Print the result 51 | test().catch(console.error); 52 | -------------------------------------------------------------------------------- /Snippets/Promises/throwingErrorOutsidePromiseChain.js: -------------------------------------------------------------------------------- 1 | function first() { 2 | throw new Error("lol"); // error wont be caught in .catch() 3 | return Promise.resolve(1); 4 | } 5 | 6 | function second(num) { 7 | throw new Error("lol"); // error will be caught in .catch() 8 | return num + 2; 9 | } 10 | 11 | first() 12 | .then((valueOne) => second(valueOne)) 13 | .then((valueTwo) => console.log(valueTwo)) 14 | .catch((err) => console.log(err)); 15 | -------------------------------------------------------------------------------- /Snippets/Promises/tryCatch.js: -------------------------------------------------------------------------------- 1 | async function first() { 2 | try { 3 | // return await second(); // remains synchronous for the function if used await 4 | return second(); //asynchronous returning the function 5 | } catch (err) { 6 | console.log("Try/Catch", err); 7 | } 8 | } 9 | 10 | function second() { 11 | return Promise.reject("Something went wrong!"); 12 | } 13 | 14 | first() 15 | .then(() => { 16 | console.log("End"); 17 | }) 18 | .catch((err) => { 19 | console.log("From .catch()", err); 20 | }); 21 | -------------------------------------------------------------------------------- /Snippets/Prototype/basic.js: -------------------------------------------------------------------------------- 1 | let arr = ["Soham", "Dhruvi"]; 2 | 3 | let obj = { 4 | name: "Soham", 5 | city: "Ahmedabad", 6 | getIntro: function () { 7 | console.log(this.name + "from" + this.city); 8 | }, 9 | }; 10 | 11 | function fun() { 12 | console.log("hello"); 13 | } 14 | 15 | /* 16 | Learnings 17 | arr.__proto__ === Array.prototype 18 | arr.__proto__.__proto__ === Object.prototype 19 | arr.__proto__.__proto__ === null 20 | 21 | obj.__proto__ === Object.prototype 22 | obj.__proto__proto__ === null 23 | 24 | fun.__proto__ === Function.prototype 25 | fun.__proto__.__proto__ === Object.prototype 26 | fun.__proto__.__proto__.__prototype === null 27 | 28 | Everything is object in JavaScript 29 | */ 30 | -------------------------------------------------------------------------------- /Snippets/Prototype/forInLoop.js: -------------------------------------------------------------------------------- 1 | let animal = { 2 | eats: true, 3 | }; 4 | 5 | let rabbit = { 6 | jumps: true, 7 | __proto__: animal, 8 | }; 9 | 10 | // Object.keys only returns own keys 11 | console.log(Object.keys(rabbit)); // jumps 12 | 13 | // for..in loops over both own and inherited keys 14 | for (let prop in rabbit) console.log(prop); // jumps, then eats 15 | 16 | // only loop in own keys and ignore inherited keys 17 | for (let prop in rabbit) { 18 | let isOwn = rabbit.hasOwnProperty(prop); 19 | 20 | if (isOwn) { 21 | alert(`Our: ${prop}`); // Our: jumps 22 | } else { 23 | alert(`Inherited: ${prop}`); // Inherited: eats 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Snippets/Prototype/getAndset.js: -------------------------------------------------------------------------------- 1 | let user = { 2 | name: "John", 3 | surname: "Smith", 4 | 5 | set fullName(value) { 6 | [this.name, this.surname] = value.split(" "); 7 | }, 8 | 9 | get fullName() { 10 | return `${this.name} ${this.surname}`; 11 | }, 12 | }; 13 | 14 | let admin = { 15 | __proto__: user, 16 | isAdmin: true, 17 | }; 18 | 19 | console.log(admin.fullName); // John Smith 20 | 21 | // setter triggers! 22 | admin.fullName = "Alice Cooper"; 23 | 24 | console.log(admin.fullName); // Alice Cooper, state of admin modified 25 | console.log(user.fullName); // John Smith, state of user protected 26 | -------------------------------------------------------------------------------- /Snippets/Prototype/nativePrototypes.js: -------------------------------------------------------------------------------- 1 | Function.prototype.defer = function (ms) { 2 | setTimeout(this, ms); 3 | }; 4 | 5 | function f() { 6 | console.log("Hello!"); 7 | } 8 | 9 | f.defer(1000); // shows "Hello!" after 1 sec 10 | 11 | Function.prototype.defer2 = function (ms) { 12 | let k = this; 13 | return function (...args) { 14 | setTimeout(() => k.apply(this, args), ms); 15 | }; 16 | }; 17 | 18 | // check it 19 | function k(a, b) { 20 | console.log(a + b); 21 | } 22 | 23 | k.defer(1000)(1, 2); // shows 3 after 1 sec 24 | -------------------------------------------------------------------------------- /Snippets/Prototype/prototype.js: -------------------------------------------------------------------------------- 1 | let animal = { 2 | eats: true, 3 | }; 4 | 5 | function Rabbit(name) { 6 | this.name = name; 7 | } 8 | 9 | Rabbit.prototype = animal; 10 | 11 | let rabbit = new Rabbit("White Rabbit"); // rabbit.__proto__ == animal 12 | 13 | let rabbit2 = new rabbit.constructor("Black Rabbit"); // another way to create a new object 14 | 15 | // re-assigning prototype of Rabbit 16 | Rabbit.prototype = { 17 | jumps: true, 18 | }; 19 | 20 | let rabbit3 = new Rabbit(); 21 | console.log(rabbit.constructor === Rabbit); // false 22 | 23 | // Not overwrite Rabbit.prototype totally 24 | // just add to it 25 | Rabbit.prototype.jumps = true; 26 | // the default Rabbit.prototype.constructor is preserved 27 | 28 | let rabbit4 = new Rabbit(); 29 | console.log(rabbit.constructor === Rabbit); // false 30 | 31 | // Other alternative way 32 | Rabbit.prototype = { 33 | jumps: true, 34 | constructor: Rabbit, 35 | }; 36 | -------------------------------------------------------------------------------- /Snippets/Prototype/searchingAlgorithm.js: -------------------------------------------------------------------------------- 1 | /* 2 | Problem statement 3 | Use __proto__ to assign prototypes in a way that any property lookup will follow the path: pockets → bed → table → head. For instance, pockets.pen should be 3 (found in table), and bed.glasses should be 1 (found in head). 4 | Answer the question: is it faster to get glasses as pockets.glasses or head.glasses? Benchmark if needed. 5 | */ 6 | 7 | let head = { 8 | glasses: 1, 9 | }; 10 | 11 | let table = { 12 | pen: 3, 13 | __proto__: head, 14 | }; 15 | 16 | let bed = { 17 | sheet: 1, 18 | pillow: 2, 19 | __proto__: table, 20 | }; 21 | 22 | let pockets = { 23 | money: 2000, 24 | __proto__: bed, 25 | }; 26 | 27 | console.log(pockets.pen); // 3 28 | console.log(bed.glasses); // 1 29 | 30 | /* 31 | In modern engines, performance-wise, there’s no difference whether we take a property from an object or its prototype. They remember where the property was found and reuse it in the next request. 32 | 33 | For instance, for pockets.glasses they remember where they found glasses (in head), and next time will search right there. They are also smart enough to update internal caches if something changes, so that optimization is safe. 34 | */ 35 | -------------------------------------------------------------------------------- /Snippets/Prototype/this.js: -------------------------------------------------------------------------------- 1 | // animal has methods 2 | let animal = { 3 | walk() { 4 | if (!this.isSleeping) { 5 | console.log(`I walk`); 6 | } 7 | }, 8 | sleep() { 9 | this.isSleeping = true; 10 | }, 11 | }; 12 | 13 | let rabbit = { 14 | name: "White Rabbit", 15 | __proto__: animal, 16 | }; 17 | 18 | // modifies rabbit.isSleeping 19 | rabbit.sleep(); 20 | 21 | console.log(rabbit.isSleeping); // true 22 | console.log(animal.isSleeping); // undefined (no such property in the prototype) 23 | -------------------------------------------------------------------------------- /Snippets/Prototype/whyAreBothHamstersFull.js: -------------------------------------------------------------------------------- 1 | let hamster = { 2 | stomach: [], 3 | eat(food) { 4 | this.stomach.push(food); 5 | }, 6 | }; 7 | 8 | let speedy = { 9 | __proto__: hamster, 10 | }; 11 | 12 | let lazy = { 13 | __proto__: hamster, 14 | }; 15 | 16 | // This one found the food 17 | speedy.eat("apple"); 18 | console.log(speedy.stomach); // apple 19 | 20 | // This one also has it, why? 21 | console.log(lazy.stomach); // apple 22 | 23 | /* 24 | Reason: 25 | 26 | speedy.eat() -> couldn't find in its obj -> finds it in hamster 27 | Now, this = speedy 28 | In this.stomach.push() -> it searches for stomach value -> couldn't find in speedy -> found in hamster 29 | So, this.stomach.push actually pushes food to the hamster object's stomach; which is common for both of them 30 | */ 31 | 32 | /* 33 | Solution: 34 | 35 | let speedy = { 36 | __proto__: hamster, 37 | stomach: [] 38 | }; 39 | 40 | let lazy = { 41 | __proto__: hamster, 42 | stomach: [] 43 | }; 44 | 45 | */ 46 | -------------------------------------------------------------------------------- /Snippets/Recursion/factorial.js: -------------------------------------------------------------------------------- 1 | const factorial = (num) => { 2 | if (num === 1) { 3 | return 1; 4 | } 5 | return num * factorial(num - 1); 6 | }; 7 | 8 | console.log(factorial(5)); 9 | -------------------------------------------------------------------------------- /Snippets/Recursion/fibonacci.js: -------------------------------------------------------------------------------- 1 | // fibonacci 2 | 3 | const fibonacci = (num) => { 4 | if (num === 1) { 5 | return 1; 6 | } 7 | if (num === 0) { 8 | return 0; 9 | } 10 | return fibonacci(num - 2) + fibonacci(num - 1); 11 | }; 12 | 13 | console.log(fibonacci(7)); 14 | 15 | // DP Approach 16 | 17 | function fib(n) { 18 | let a = 1; 19 | let b = 1; 20 | for (let i = 3; i <= n; i++) { 21 | let c = a + b; 22 | a = b; 23 | b = c; 24 | } 25 | return b; 26 | } 27 | -------------------------------------------------------------------------------- /Snippets/Recursion/linkedList.js: -------------------------------------------------------------------------------- 1 | let list = { 2 | value: 1, 3 | next: { 4 | value: 2, 5 | next: { 6 | value: 3, 7 | next: { 8 | value: 4, 9 | next: null, 10 | }, 11 | }, 12 | }, 13 | }; 14 | 15 | const printList = (obj) => { 16 | console.log(obj.value); 17 | if (obj.next !== null) { 18 | printList(obj.next); 19 | } 20 | }; 21 | 22 | console.log(printList(list)); 23 | -------------------------------------------------------------------------------- /Snippets/Recursion/power.js: -------------------------------------------------------------------------------- 1 | const power = (x, n) => { 2 | console.log(x, n); 3 | if (n === 1) { 4 | return x; 5 | } 6 | return x * power(x, n - 1); 7 | }; 8 | 9 | console.log(power(2, 3)); 10 | -------------------------------------------------------------------------------- /Snippets/Recursion/recursiveTraversal.js: -------------------------------------------------------------------------------- 1 | let company = { 2 | sales: [ 3 | { 4 | name: "John", 5 | salary: 1000, 6 | }, 7 | { 8 | name: "Alice", 9 | salary: 1600, 10 | }, 11 | ], 12 | 13 | development: { 14 | sites: [ 15 | { 16 | name: "Peter", 17 | salary: 2000, 18 | }, 19 | { 20 | name: "Alex", 21 | salary: 1800, 22 | }, 23 | ], 24 | 25 | internals: [ 26 | { 27 | name: "Jack", 28 | salary: 1300, 29 | }, 30 | ], 31 | }, 32 | }; 33 | 34 | const computeSalary = (department, salary) => { 35 | if (Array.isArray(department)) { 36 | return department.reduce((prev, current) => prev + current.salary, 0); 37 | } else { 38 | let sum = 0; 39 | for (let subDep of Object.values(department)) { 40 | sum += computeSalary(subDep); 41 | } 42 | return sum; 43 | } 44 | }; 45 | 46 | console.log(computeSalary(company)); 47 | -------------------------------------------------------------------------------- /Snippets/Recursion/sumTo.js: -------------------------------------------------------------------------------- 1 | const sumTo = (n) => { 2 | if (n === 1) { 3 | return 1; 4 | } else { 5 | return n + sumTo(n - 1); 6 | } 7 | }; 8 | 9 | console.log(sumTo(5)); // 15 10 | console.log(sumTo(100000)); // error 11 | -------------------------------------------------------------------------------- /Snippets/Strings/charCount.js: -------------------------------------------------------------------------------- 1 | function charCount(str){ 2 | let dict = {} 3 | for(const c of str){ 4 | if(c in dict){ 5 | dict[c]+=1 6 | }else{ 7 | dict[c] = 1 8 | } 9 | } 10 | return dict 11 | } 12 | 13 | const ans = charCount("Hello") 14 | 15 | // Most repeated character 16 | 17 | let max = {value:-Infinity}; 18 | 19 | for(let i of Object.keys(ans)){ 20 | if(ans[i] > max.value){ 21 | max = {value:ans[i], key:i} 22 | } 23 | 24 | } 25 | 26 | console.log(max.key) -------------------------------------------------------------------------------- /Snippets/Strings/lowerCaseConverter.js: -------------------------------------------------------------------------------- 1 | // toLowerCase() method changes the string to lowercase letters. 2 | let favLanguage = "JavasCript"; 3 | console.log(favLanguage.toLowerCase()); // javascript 4 | let standard = "ECMA"; 5 | console.log(standard.toLowerCase()); // ecma 6 | let oneMoreLangugae = "PHP"; 7 | console.log(oneMoreLangugae.toLowerCase()); // php 8 | -------------------------------------------------------------------------------- /Snippets/Strings/removeSpaces.js: -------------------------------------------------------------------------------- 1 | function removeSpaces(str){ 2 | let ans = str.split(" ").join(""); 3 | return ans 4 | } 5 | 6 | console.log(removeSpaces("Soham is a good guy")); -------------------------------------------------------------------------------- /Snippets/Strings/repeat.js: -------------------------------------------------------------------------------- 1 | /** 2 | * repeat methods creates specified n copies and concatenates together and returns it. Original string will be unaltered 3 | */ 4 | let stringToBeRepeated = "love-Javascript"; 5 | console.log(stringToBeRepeated.repeat(5)); //love-Javascriptlove-Javascriptlove-Javascriptlove-Javascriptlove-Javascript 6 | -------------------------------------------------------------------------------- /Snippets/Strings/replaceString.js: -------------------------------------------------------------------------------- 1 | function replaceChar(str,c1,c2){ 2 | let regex = new RegExp(c1,"g"); 3 | console.log(regex) 4 | let ans = str.replace(regex,'2'); 5 | return ans 6 | } 7 | 8 | console.log(replaceChar("Soham is a good guy", "o","d")); -------------------------------------------------------------------------------- /Snippets/Strings/search.js: -------------------------------------------------------------------------------- 1 | /** 2 | * search a word in the sentence and find out at which position it is found for first time. 3 | */ 4 | 5 | let jsLove = "Javascript is awesome. I am a Javascript lover. You have to experience this awesomeness"; 6 | let searchWord = "awesome"; 7 | console.log(searchWord + " found at " + (jsLove.search(searchWord) + 1) + " position"); // 14 8 | -------------------------------------------------------------------------------- /Snippets/Strings/substrings.js: -------------------------------------------------------------------------------- 1 | function substring(str){ 2 | let arr = [] 3 | for(let i=1; i<=str.length;i++){ 4 | let temp = ""; 5 | for(let j=0; j<=str.length-i;j++){ 6 | temp+=str[j]; 7 | } 8 | arr.push(temp); 9 | } 10 | console.log(arr) 11 | 12 | } 13 | 14 | console.log(substring("1234567")) -------------------------------------------------------------------------------- /Snippets/Strings/trim.js: -------------------------------------------------------------------------------- 1 | /** 2 | * trim removes whitespaces in the beginning of the string and end of the string but not in the middle 3 | */ 4 | 5 | let string = " Data Structures "; 6 | console.log(string); // Data Structures 7 | console.log(string.trim()); //Data Structures 8 | -------------------------------------------------------------------------------- /Snippets/Strings/upperCaseConverter.js: -------------------------------------------------------------------------------- 1 | // toUpperCase() method changes the string to upper letters. 2 | let favLanguage = "JavasCript"; 3 | console.log(favLanguage.toUpperCase()); // JAVASCRIPT 4 | let firstName = "ECMA"; 5 | console.log(firstName.toUpperCase()); // ECMA 6 | let oneMoreLangugae = "Python"; 7 | console.log(oneMoreLangugae.toUpperCase()); // PYTHON 8 | --------------------------------------------------------------------------------