├── .gitignore ├── Array-Problems ├── array-complements.js ├── array-left-rotation-by-steps.js ├── array-of-Objects-mutate-formatting-Mongo-date-Performance.js ├── array-of-Objects-mutate-formatting-Mongo-date.js ├── array-of-Objects-mutate-simple.js ├── array-right-rotation-by-no-of-positions.js ├── find-closest-number-in-array.js ├── find-count-of-max-elements.js ├── find-length-of-integer-without-converting-to-string.js ├── find-min-max-of-after-popping-one-elem.js ├── flatten-Array-Deep-2.js ├── flatten-arr-of-objects-with-flat-package.js ├── flatten-arr-of-objects-with-lodash-flatMap-2.js ├── flatten-arr-of-objects-with-lodash-flatMap-GREAT-performance.js ├── flatten-arr-of-objects-with-lodash-flatMap-GREAT.js ├── flatten-arr-of-objects-with-lodash-merge.js ├── flatten-arr-of-objects-with-plain-JS-1.js ├── flatten_array.js ├── flatten_array_Deep.js ├── forEach-first-Principle-custom-callback.js ├── indexOf_manually_build.js ├── intersection-of-arrays.js ├── largest-numbers-from-subarray.js ├── map-first-Principle-custom-callback.js ├── max-repeated-num-in-array.js ├── max-repeating-element.js ├── misc_Array_Problems_JS-Cookbook.js ├── mongo-json-data-TEST.js ├── reduce_method_applications.js ├── reverseArray-Recursively.js ├── search-unknown-length-Array.js ├── shuffle_Array-1.js ├── shuffle_Array-2.js ├── tempCodeRunnerFile.js └── tiny-Array-probs │ ├── clone_Array.js │ └── returns-true-if-all-elemensts-true.js ├── ES6 ├── Destructuring_Geneal.md ├── calback-hell-resolved-with-promise.js ├── callback-hell-examples.js ├── create-class-in-ES6.js ├── destructuring.js ├── every-method-of-Array.js ├── fat-arrow-function.js ├── filter-implement-remove-duplicates.js ├── find-method.js ├── function-currying.js ├── map-Implementation-On-Objects.js ├── promise-basic-implementation.js ├── reduce-implementation.js ├── rest-spread-2.js ├── rest-spread.jpg ├── rest-spread.js ├── some-method-of-Array.js ├── this-in-ES6.js ├── this-in-ES6 │ ├── README.md │ ├── this-in-ES6.js │ ├── this-in-ES6_2.js │ └── this-in-ES6_3.js ├── this-in-ES6_2.js └── this-in-ES6_3.js ├── Functional-Programming ├── 1.js ├── max.js └── pure_functions.js ├── General-JS-Problems ├── Pi-To-n-th-digits.js ├── asyncMap.js ├── atoi-string-to-Number-2.js ├── atoi-string-to-number.js ├── caching_memoization-function.js ├── calculate-log-recursively.js ├── check-nonEmptyString.js ├── comparing-number-to-string.txt ├── convert-integer-to-words-2.js ├── convert-integer-to-words.js ├── convert-word-to-integer-atoi.js ├── count-vowels.js ├── decimal-to-roman.js ├── factorial-Performance-Recursive-vs-Iterative.js ├── fibonacci-number-GOOD-Future-Ref.js ├── fibonacci-number.js ├── fibonacci-sum-odd.js ├── fibonacci-with-memoization.js ├── find_number_appearing-twice.js ├── form-largest-number-from-given-array.js ├── function_chaining-call-function-inside-another-as-object-property.js ├── greatest_common_divisor.js ├── ifPowerOfFour.js ├── integer_length.js ├── intersection-of-arrays.js ├── isNumeric.js ├── isPalindrome.js ├── isUgly.js ├── largest-Numbe-in-Array.js ├── largest-second-value-from-Array-Multiple-Solution.js ├── largest-third-value-from-Array-Multiple-Solution.js ├── largest_product_yielded_ from_three_ integers.js ├── linked-list.js ├── map-and-filter-application.js ├── max-min-from-array-of-objects.js ├── max-product-three-elements.js ├── median-of-Array.js ├── merge_two_sorted_array.js ├── missing-number.js ├── multi-diamensional-array.js ├── narcissistic _number.js ├── nested-arrays-1.js ├── nested-arrays-function-chaining2.js ├── non-repeating-char-in-a-string.js ├── pangram.js ├── parenthesis-match.js ├── parenthesis_return-matching-ending.js ├── permutation_array_of_numbers-Heap-Algo.js ├── permutation_array_of_numbers-backtrack.js ├── permutation_array_of_text-string.js ├── pipeFunction.js ├── print-Triangle-Staircase-1.js ├── print-Triangle-Staircase-2.js ├── print-Triangle-Staircase-REVERSE-2.js ├── print-pyramid-Reverse.js ├── print-pyramid-structure.js ├── print-right-aligned-triangel-staircase-problem-HR.js ├── print-side-by-side-bow-shape-triangle.js ├── pure-impure-func-with-slice-and-splice.js ├── raise-To-Power-bit-shifting.js ├── random-code-1.js ├── remove-duplicate-chars-from-string.js ├── remove-duplicate-from-Array-O(n).js ├── remove-duplicate-from-array.js ├── remove-duplicate-from-string.js ├── repeatedly-add-digits-till-sum-is-single.js ├── reverseArray-of-numbers.js ├── search-string-heighlight.html ├── secretary-hiriing.js ├── setTimeOut-As-Callback.js ├── shuffle-array-so-all-zeros-are-at-beginning.js ├── small-exercise.js ├── small-snippets.js ├── sort-array-of-objects.js ├── sum-integers-without-Operator.js ├── sum-large-numbers.js └── swapNumber-without-temp.js ├── Imp-TECHNIQUES ├── convert-String-Arr-to-IntArray.js ├── do-While-loop-Guessing-Game.js ├── general-Array-Creation.js ├── generate-2-D-array-on-the-fly-inside-a-program.js ├── generate-array-on-the-fly.js ├── method_chaining.js ├── parse-Int-toString.js ├── replace-splice-with-slice.js └── spread-operator-for-multiple-arguments.js ├── Most-Popular ├── Numbers │ └── swapNumber-without-temp.js ├── Prime-Num │ ├── find_Prime_factors.js │ ├── isPrime.js │ ├── prime-Find-nth-Prime-Number.js │ ├── prime-generation-between-Range.js │ ├── prime-num-between-range-Eratosthenes-algorithm.js │ ├── prime-num-between-range.js │ └── prime_palindrome.js ├── String │ ├── reverse-string-multiple-ways.js │ ├── reverseArray-of-numbers.js │ └── reverseWords.js ├── anagram.js ├── count-vowels.js ├── counting-zeros-in-number.js └── quick-sort-with-Counter.js ├── Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques ├── Delete-Prop-with-numbers-as-keys-regulal-destructuring-wont-work.js ├── Lodash_Usefull_Techniques │ └── pick-partialRight_Only_cherryPick_Objects.js ├── Object-of-arrays-with-further-nested-array-return-an-element-meeting-condition.js ├── Object.assign.md ├── array-map-like-function-for-Objects.js ├── array-of-objects-1.js ├── cloninng_Shallow-with-assign-method.js ├── cloninng_deep-2.js ├── cloninng_deep.js ├── convert-2D-Obj-to-arr-of-Obj-Highcharts-multiple-bar-graph.js ├── convert-arr-of-obj-to-arr-of-arr-removing-some-fields-useful-external-api.js ├── convert-arr-of-objects-into-another-dynamically-add-field-useful-for-api-request.js ├── convert-obj-of-key-value-pairs-to-arrays-DeNormalization.js ├── convert-obj-of-nested-obj-to-arr-of-arr-worldtrading-data-api-with-vx-chart.js ├── convert-plain-object-to-array-of-objects-useful-external-api.js ├── copy-one-object-to-another-object.js ├── delete_Properties_with_rest_spread.js ├── flatten-2d-arrays-picking-only-second-element-highcharts.js ├── flatten-objects-plain-js-recursive.js ├── getting-key-with-max-value-from-object.js ├── json-accessing-json-objects.js ├── lodash-pick-object-fields-from-array.js ├── map-Implementation-On-Objects.js ├── map-over-arr-of-objects-to-return-value-conditionally-as-an-ar.js ├── map-recduce-filter.js ├── max-min-from-array-of-objects.js ├── merge-objects-with-spread-operator.js ├── nested-object-prob-1.js ├── nested-objects-4.js ├── nested-objects-prob-2.js ├── nested-objects-prob-3.js ├── number-as-key-in-obj-is-it-allowed.md ├── object-accessing-keys-values.js ├── object-seal-and-freeze.js ├── object-with-nested-arrays-values.js ├── property-descriptor.md ├── push-nested-array-of-objects-to-another-2.js ├── push-nested-array-of-objects-to-another.js ├── pushing_new_key_value_pair_to_existing_obj.js └── sort-array-of-objects.js ├── Promise-Notes ├── How-Promise-makes-code-Asynchronous-non-blocking.md ├── README.md ├── calback-hell-resolved-with-promise.js ├── callback-hell-examples.js ├── promise-basic-implementation.js └── then-in-Promise-Future-Reference-GOOD.md ├── Readme.md ├── Regexp ├── check-if-String-has-NO-numbers.js ├── check-if-String-has-only-numbers.js ├── match-basics.js ├── pigLatin-with-match.js ├── regExp-Method-Impotant-for-String.js ├── replace-method-basics.js ├── search-method-basics.js └── test-method-basics.js ├── String ├── camel-to-Title.js ├── frequency-of-occurance-of-letters.js ├── longest_Substring-of-two-strings.js ├── no-of-occurance-of-char-in-string.js ├── padded-Number.js ├── passage-Counter.js ├── reverse-string-multiple-ways.js ├── shift-each-letter-by-number.-of-position.js ├── string-related-misc-problems.js ├── string-splice-method.js ├── title-To-Camel.js ├── toLocalString-Application.js └── tweet-word-limits.js ├── careercup └── google-biz-trip-boardingPass.js ├── date-conversion-comparison-moment ├── convert-string-date-from-MUI-pickert-to-YYYY-MM-DD.js └── mongo-Date-Comparison-with-current-date.js ├── numbers └── summing-digits-of-a-number-subtracting-first-digit-if-negative.js ├── package-lock.json ├── package.json ├── reWrite-JS-Function ├── every-myOwn-custom-callback.js ├── filter-myOwn-custom-callback.js ├── forEach-myOwn-custom-callback.js ├── indexOf-myOwn-custom-callback.js ├── map-myOwn-custom-callback.js ├── reduce-myOwn-custom-callback.js └── some-myOwn-custom-callback.js ├── tsconfig.json └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | 12 | # misc 13 | .DS_Store 14 | .env.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | 23 | # Ignore docs files 24 | _gh_pages 25 | .ruby-version 26 | 27 | # Numerous always-ignore extensions 28 | *.diff 29 | *.err 30 | *.orig 31 | *.log 32 | *.rej 33 | *.swo 34 | *.swp 35 | *.zip 36 | *.vi 37 | *~ 38 | *.~lock* 39 | .~lock* 40 | 41 | # OS or Editor folders 42 | .DS_Store 43 | ._* 44 | Thumbs.db 45 | .cache 46 | .project 47 | .settings 48 | .tmproj 49 | *.esproj 50 | nbproject 51 | *.sublime-project 52 | *.sublime-workspace 53 | .idea 54 | 55 | # Komodo 56 | *.komodoproject 57 | .komodotools 58 | 59 | # grunt-html-validation 60 | validation-status.json 61 | validation-report.json 62 | 63 | # Folders to ignore 64 | node_modules 65 | Project-Note-PAUL 66 | .vscode 67 | 68 | # Ignore all logfiles and tempfiles. 69 | !/log/.keep 70 | /tmp 71 | /.gems 72 | 73 | CountDownTimer-Note.odt 74 | random-code-1.js 75 | random-code-2.js 76 | random-code-3.js 77 | performance-1.js 78 | 79 | #ignore file name ending in "-bkp.js" OR "-bkp.ts" OR "-bkp.py" or "-test.js" OR "-test.ts" in its name. So I will have to put "-test.js" at all files that is just for my development-time random testing code . 80 | **/*-bkp.js 81 | **/*-bkp.ts 82 | **/*-bkp.py 83 | **/*-test.js 84 | **/*-test.ts 85 | **/*-test.py 86 | **/*-test.ipynb 87 | **/*-test.md 88 | **/*-test.json 89 | -------------------------------------------------------------------------------- /Array-Problems/array-complements.js: -------------------------------------------------------------------------------- 1 | // returns things in array 'a' that are not in array 'b' 2 | // ['a','b','c','1', '2', '3'].complement(['b', 'c', 'd', 'e']); 3 | // ['a', '1', '2', '3'] 4 | 5 | complements = (arr1, arr2) => { 6 | 7 | return (Array.isArray(arr1) && Array.isArray(arr2)) 8 | ? arr1.filter((elem) => arr2.indexOf(elem) === - 1) 9 | : undefined 10 | } 11 | 12 | let arr1 = ['a','b','c','1', '2', '3']; 13 | let arr2 = ['b', 'c', 'd', 'e']; 14 | 15 | console.log(complements(arr1, arr2)); // => [ 'a', '1', '2', '3' ] -------------------------------------------------------------------------------- /Array-Problems/array-of-Objects-mutate-formatting-Mongo-date-Performance.js: -------------------------------------------------------------------------------- 1 | const { data } = require("./mongo-json-data-TEST"); 2 | const moment = require("moment"); 3 | 4 | /* Problem Statement - From call to Mongo, I am getting the date field formatted according to Mongo's own formatting syntax. But after getting the raw data from Mongo, I shall format each of the date field to whatever formatting I need 5 | 6 | The Performance test here, implements the problem from file - array-of-Objects-mutate-formatting-Mongo-date 7 | 8 | 9 | */ 10 | 11 | /* 12 | The basic idea is to create a new empty object for each item in the array and assign the properties from old objects to them, respectively. This means we get an object with a new reference, so we are not going to modify the Original One. 13 | */ 14 | const doNotMutateOriginalArr = (arr) => { 15 | let mutatedArr = arr.map(e => { 16 | if (e.imported_date) { 17 | e = { 18 | ...e, 19 | imported_date: 20 | moment(e.imported_date).format("MMM D, YYYY 12:00:00 ") + `AM` 21 | }; 22 | } 23 | return e; 24 | }); 25 | return mutatedArr 26 | } 27 | 28 | // In this function, I am mutating the original array itself. 29 | 30 | const mutateOriginalArr = (arr) => { 31 | arr.map(e => { 32 | if (e.imported_date) { 33 | e.date = moment(e.imported_date).format("MMM D, YYYY 12:00:00 ") + `AM` 34 | } 35 | return e; 36 | }) 37 | return arr; 38 | } 39 | 40 | // console.log(doNotMutateOriginalArr(data)); 41 | // console.log(mutateOriginalArr(data)); 42 | 43 | 44 | console.time("1st"); 45 | doNotMutateOriginalArr(data) 46 | console.timeEnd("1st"); 47 | 48 | console.log("*******************************"); 49 | 50 | console.time("2nd"); 51 | mutateOriginalArr(data) 52 | console.timeEnd("2nd"); -------------------------------------------------------------------------------- /Array-Problems/array-of-Objects-mutate-simple.js: -------------------------------------------------------------------------------- 1 | const events = [ 2 | { 3 | name: "First Event", 4 | metadata: { 5 | type: "public" 6 | } 7 | }, 8 | { 9 | name: "Event 2", 10 | metadata: { 11 | type: "private" 12 | } 13 | }, 14 | { 15 | name: "Third Event", 16 | metadata: { 17 | type: "closed" 18 | } 19 | } 20 | ]; 21 | 22 | /* FROM BLOG POST - https://medium.freecodecamp.org/handling-state-in-react-four-immutable-approaches-to-consider-d1f5c00249d5 23 | 24 | Note, here I am NOT mutating the original array. 25 | The basic idea is to create a new empty object for each item in the array and assign the properties from old objects to them, respectively. This means we get an object with a new reference, so we are not going to modify the Original One. 26 | */ 27 | const mappedEvents = events.map(e => { 28 | if (e.name) { 29 | e = { ...e, name: "Second Event Mutated" }; 30 | } 31 | return e; 32 | }); 33 | 34 | console.log(mappedEvents); 35 | 36 | /* OUTPUT - 37 | [ { name: 'Second Event Mutated', metadata: { type: 'public' } }, 38 | { name: 'Second Event Mutated', metadata: { type: 'private' } }, 39 | { name: 'Second Event Mutated', metadata: { type: 'closed' } } ] 40 | */ 41 | -------------------------------------------------------------------------------- /Array-Problems/array-right-rotation-by-no-of-positions.js: -------------------------------------------------------------------------------- 1 | /* Write a function that takes an array of integers and returns that array rotated by N positions. 2 | For example, if N=2, given the input array [1, 2, 3, 4, 5, 6] the function should return [5, 6, 1, 2, 3, 4] */ 3 | 4 | /* A> Rotating an array is the same as chopping it into two pieces and putting them together "backwards". 5 | 6 | B> So, for rotation, chop this array into 2 pieces the last 3 elements, and the rest of the elements. 7 | 8 | C> Now just bring those last 3 elements into first positon and concatenate the rest of the elements to this. 9 | */ 10 | 11 | function rightRotate (array, k) { 12 | var L = array.length; 13 | return array.slice(L - k).concat(array.slice(0, L - k)); 14 | }; 15 | 16 | console.log(rightRotate([1,2,3,4,5,6,7], 3)); -------------------------------------------------------------------------------- /Array-Problems/find-closest-number-in-array.js: -------------------------------------------------------------------------------- 1 | // Find the number in an array that is closest to a given number 2 | 3 | // sort based on distance from the reference value num, and then take the first item. 4 | closestNumInArr = (arr, num) => { 5 | return arr.sort((a, b) => Math.abs(num - a) - Math.abs(num - b))[0]; 6 | } 7 | 8 | console.log(closestNumInArr([5,10,15,20,25,30,35], 22)); -------------------------------------------------------------------------------- /Array-Problems/find-count-of-max-elements.js: -------------------------------------------------------------------------------- 1 | /* Source Problem - https://youtu.be/E_hTGcx8o7g?t=3m24s - The Indian guy doing mock interview 2 | 3 | Given an array containing multiple number of max elements - count the number of max elements. 4 | 5 | so, given [ 1, 2, 2, 3, 4, 5, 4, 5] 6 | 7 | I should return 2 as 5 occurs 2 times. 8 | */ 9 | 10 | maxCount = arr => { 11 | 12 | arr = arr.sort((a, b) => b - a); 13 | 14 | let max = Math.max(...arr); 15 | 16 | result = 0; 17 | 18 | for (let i = 0; i < arr.length; i++ ) { 19 | if (max === arr[i]) { 20 | result++ 21 | } 22 | if (arr[i] < max) break; 23 | } 24 | return result; 25 | } 26 | 27 | 28 | let myArr = [ 1, 2, 2, 3, 4, 5, 4, 5] 29 | 30 | console.log(maxCount(myArr)); -------------------------------------------------------------------------------- /Array-Problems/find-min-max-of-after-popping-one-elem.js: -------------------------------------------------------------------------------- 1 | // https://youtu.be/hbp6IrCysDs?t=3m3s - The Indian guy doing mock interview. given an array, write a function to return the maximum and minimum possible sum of all the rest of the elements, after taking out a random element from the array. 2 | 3 | // Solution Algo - After sorting the array, when I leave the max element (i.e. the right-most elem) the rest of the array sum will be he minimum sum. And similarly, when I leave the left-most elem, the sum of the rest of elements are the max sum. 4 | 5 | minMax_after_popping_one_Elem = arr => { 6 | 7 | // Remember slice() method does not include the second argument in the returned sliced array. So it takes elements upto but not including the second-argumet. 8 | // And the js-native sort method will sort in ascending order with the largest element at the right-most position. 9 | 10 | let minSum = arr.sort().slice(0, arr.length - 1).reduce((a, b) => a + b); 11 | 12 | let maxSum = arr.sort().slice(1, arr.length).reduce((a, b) => a + b); 13 | 14 | return console.log(minSum, maxSum); 15 | 16 | } 17 | 18 | myArr = [ 2, 1, 3, 4] 19 | 20 | minMax_after_popping_one_Elem(myArr); 21 | 22 | // Slight modification with destructuring assignment 23 | 24 | minMax = arr => [min, max] = [(arr.sort().slice(0, arr.length - 1)).reduce((a, b) => a + b), (arr.sort().slice(1, arr.length)).reduce((a, b) => a + b) ] 25 | 26 | console.log(minMax(myArr)); -------------------------------------------------------------------------------- /Array-Problems/flatten-Array-Deep-2.js: -------------------------------------------------------------------------------- 1 | // Recursive helper function 2 | const flattenArr_TerminalCondition = ([first, ...rest], accumulator) => 3 | (first === undefined ) 4 | ? accumulator 5 | : (Array.isArray(first)) 6 | ? flattenArr_TerminalCondition([...first, ...rest], accumulator) 7 | : flattenArr_TerminalCondition(rest, accumulator.concat(first)); 8 | 9 | 10 | const flattenDeep = array => flattenArr_TerminalCondition(array, []); 11 | 12 | console.log(flattenDeep([[1,[2,[[3]]]],4,[5,[[[6]]]]])) -------------------------------------------------------------------------------- /Array-Problems/flatten-arr-of-objects-with-flat-package.js: -------------------------------------------------------------------------------- 1 | /* Problem Statement - All I am trying to do is to create a new array with a an extra field name of "imported_commodity_name" (from the nested object) from original array (receieved from DB -call) which does not have that extra field 2 | */ 3 | 4 | var flatten = require("flat"); 5 | 6 | var data = [ 7 | { 8 | _id: "5c76bc3a5ff10c6d53ef67b4", 9 | imported_commodity_objectId: { 10 | _id: "5c651f71ddff9f780e4cdbcd", 11 | name: "Platinum12", 12 | type: "Precious Metals", 13 | createdAt: "2019-02-14T07:57:37.736Z", 14 | updatedAt: "2019-02-27T16:35:22.214Z", 15 | __v: 0 16 | }, 17 | qty_in_mts: 1, 18 | imported_date: "2019-02-27T16:34:18.281Z", 19 | no_of_vessels_per_day: 1, 20 | createdAt: "2019-02-27T16:35:06.071Z", 21 | updatedAt: "2019-02-27T16:35:06.071Z", 22 | __v: 0 23 | }, 24 | { 25 | _id: "5c76bc305ff10c6d53ef67b3", 26 | imported_commodity_objectId: { 27 | _id: "5c6c0f6e9c84ea3c7194a7dc", 28 | name: "Oil", 29 | type: "Energy", 30 | createdAt: "2019-02-19T14:15:10.421Z", 31 | updatedAt: "2019-02-19T14:15:10.421Z", 32 | __v: 0 33 | }, 34 | qty_in_mts: 1, 35 | imported_date: "2019-02-27T16:34:18.281Z", 36 | no_of_vessels_per_day: 1, 37 | createdAt: "2019-02-27T16:34:56.790Z", 38 | updatedAt: "2019-02-27T16:34:56.790Z", 39 | __v: 0 40 | } 41 | ]; 42 | 43 | const list = flatten(data, { safe: true }); 44 | 45 | console.log(list); 46 | -------------------------------------------------------------------------------- /Array-Problems/flatten-arr-of-objects-with-lodash-flatMap-2.js: -------------------------------------------------------------------------------- 1 | /* 2 | https://stackoverflow.com/questions/47165218/lodash-flatmap-to-flatten-object?rq=1 3 | 4 | GREAT SOLUTION BASED ON WHICH I CREATED MY OWN MORE SIMPLIFIED SOLUTION (flatten-arr-of-objects-with-lodash-flatMap.js) TO GET A PARTICULAR NESTED OBJECT'S VALUE 5 | 6 | I am trying to pull out all of the start and end times from allocationIntervals.jobTaskTimeAllocationInterval to create something like the following: 7 | 8 | const arr = [{ 9 | employeeId: "22826", 10 | taskId: "16465169" 11 | startTime: "2017-03-15T01:50:00.000Z", 12 | endTime: "2017-03-15T02:50:00.000Z" 13 | }, 14 | { 15 | employeeId: "22826", 16 | taskId: "16465169", 17 | startTime: "2017-04-16T02:50:00.000Z", 18 | endTime: "2017-04-16T03:50:00.000Z" 19 | }]; 20 | 21 | */ 22 | 23 | const _ = require("lodash"); 24 | const flatMap = require("lodash/flatMap"); 25 | 26 | const arr = [ 27 | { 28 | "@id": "6005752", 29 | employeeId: { 30 | id: "22826" 31 | }, 32 | allocationIntervals: { 33 | jobTaskTimeAllocationInterval: { 34 | "@id": "34430743", 35 | startTime: "2017-03-15T01:50:00.000Z", 36 | endTime: "2017-03-15T02:50:00.000Z" 37 | }, 38 | "@id": "34430756", 39 | startTime: "2017-04-16T02:50:00.000Z", 40 | endTime: "2017-04-16T03:50:00.000Z" 41 | }, 42 | taskId: { 43 | id: "16465169" 44 | } 45 | } 46 | ]; 47 | 48 | const createAllocation = (item, allocation) => ({ 49 | employeeId: item.employeeId.id, 50 | taskId: item.taskId.id, 51 | startTime: allocation.startTime, 52 | endTime: allocation.endTime 53 | }); 54 | 55 | const result = _.flatMap(arr, item => [ 56 | createAllocation(item, item.allocationIntervals), 57 | createAllocation(item, item.allocationIntervals.jobTaskTimeAllocationInterval) 58 | ]); 59 | 60 | console.log(result); 61 | -------------------------------------------------------------------------------- /Array-Problems/flatten-arr-of-objects-with-lodash-merge.js: -------------------------------------------------------------------------------- 1 | /* Problem Statement - All I am trying to do is to create a new array with a an extra field name of "imported_commodity_name" (from the nested object) from original array (receieved from DB -call) which does not have that extra field 2 | 3 | PAUL NOTE - merge will work ONLY FOR OBJECTS 4 | */ 5 | 6 | const _ = require("lodash"); 7 | const merge = require("lodash/merge"); 8 | 9 | var data = [ 10 | { 11 | _id: "5c76bc3a5ff10c6d53ef67b4", 12 | imported_commodity_objectId: { 13 | _id: "5c651f71ddff9f780e4cdbcd", 14 | name: "Platinum12", 15 | type: "Precious Metals", 16 | createdAt: "2019-02-14T07:57:37.736Z", 17 | updatedAt: "2019-02-27T16:35:22.214Z", 18 | __v: 0 19 | }, 20 | qty_in_mts: 1, 21 | imported_date: "2019-02-27T16:34:18.281Z", 22 | no_of_vessels_per_day: 1, 23 | createdAt: "2019-02-27T16:35:06.071Z", 24 | updatedAt: "2019-02-27T16:35:06.071Z", 25 | __v: 0 26 | }, 27 | { 28 | _id: "5c76bc305ff10c6d53ef67b3", 29 | imported_commodity_objectId: { 30 | _id: "5c6c0f6e9c84ea3c7194a7dc", 31 | name: "Oil", 32 | type: "Energy", 33 | createdAt: "2019-02-19T14:15:10.421Z", 34 | updatedAt: "2019-02-19T14:15:10.421Z", 35 | __v: 0 36 | }, 37 | qty_in_mts: 1, 38 | imported_date: "2019-02-27T16:34:18.281Z", 39 | no_of_vessels_per_day: 1, 40 | createdAt: "2019-02-27T16:34:56.790Z", 41 | updatedAt: "2019-02-27T16:34:56.790Z", 42 | __v: 0 43 | } 44 | ]; 45 | 46 | const list = _.merge(data, data.imported_commodity_objectId); 47 | 48 | console.log(list); 49 | -------------------------------------------------------------------------------- /Array-Problems/flatten_array.js: -------------------------------------------------------------------------------- 1 | // SMALLEST SIMPLEST Functional solution for flattening 2-D arrays - Works for 2-D arrays but DOES NOT FOR more multi-dimensional arrays 2 | 3 | const flattened1 = arr => [].concat(...arr) 4 | 5 | let myArr1 = [[1], [2], [3, 4], 5] 6 | let myArr2 = [[1], [2], [[3], 4], 5] 7 | var myArr3 = [ 8 | [1, 2], 9 | [3, 4, 5], 10 | [6, 7, 8, 9], 11 | ] 12 | 13 | console.log(flattened1(myArr1)) // => [ 1, 2, 3, 4, 5 ] 14 | console.log(flattened1(myArr2)) // => [ 1, 2, [ 3 ], 4, 5 ] 15 | console.log(flattened1(myArr3)) // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] 16 | 17 | // ******************************************************************* 18 | 19 | // Other alternative 20 | 21 | var arrays = [["a"], ["b", "c"]] 22 | 23 | console.log(Array.prototype.concat.apply([], arrays)) // => [ 'a', 'b', 'c' ] 24 | 25 | // Good old O(N^2) solution for 2-D arrays - BUT IF ANY OF THE ELEMENT IS NO AN ARRAY, THEN IT WILL FAIL, AS IT WILL NOT INCLUDE A NON-ARRAY ELEMENT INTO THE FINAL ARRAY 26 | 27 | const flatten_2d = arr => { 28 | let flattenedArr = [] 29 | 30 | for (let i = 0; i < arr.length; i++) { 31 | for (let j = 0; j < arr[i].length; j++) { 32 | flattenedArr.push(arr[i][j]) 33 | } 34 | } 35 | return flattenedArr 36 | } 37 | 38 | console.log(flatten_2d(myArr1)) // => [ 1, 2, 3, 4 ] 39 | console.log(flatten_2d(myArr2)) // => [ 1, 2, [ 3 ], 4 ] 40 | console.log(flatten_2d(myArr3)) // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] 41 | -------------------------------------------------------------------------------- /Array-Problems/flatten_array_Deep.js: -------------------------------------------------------------------------------- 1 | /* SOLUTION-1 - BEST IMPLEMENTATION FOR Deep flattening a multi-diamensional array. 2 | 3 | Use recursion. Use Array.concat() with an empty array ([]) and the spread operator (...) to flatten an array. Recursively flatten each element that is an array.*/ 4 | 5 | const deepFlatten1 = arr => [].concat(...arr.map(toFlatten => { 6 | 7 | return (Array.isArray(toFlatten) ? deepFlatten1(toFlatten) : toFlatten) 8 | 9 | })) 10 | 11 | console.log(deepFlatten1([1, [2], [[3], 4], 5])); // => [ 1, 2, 3, 4, 5 ] 12 | 13 | // SOLUTION-2 - Same implementation using reduce() and without using arrow syntax 14 | 15 | const deepFlatten2 = arr => { 16 | return arr.reduce((flat, yetToFlatten) => { 17 | return flat.concat(Array.isArray(yetToFlatten) ? deepFlatten2(yetToFlatten) : yetToFlatten); 18 | }, []); 19 | } 20 | 21 | let myArr1 = [[1], [2], [3, 4], 5] 22 | 23 | console.log(deepFlatten2(myArr1)); // => [ 1, 2, 3, 4, 5 ] 24 | 25 | /*My Note - Explanation of why an empty array passed as the second argument to the reduce function which is the accumulator - The code breaks without it, giving arr.reduce is not a function. 26 | 27 | The empty array [] is the starting accumulator value for the reduce function, the initial value. In this case it's the value of flat in the first call to the anonymous function passed to reduce. If it is not specified, then the first call to reduce binds the first element out of the array-argument given to deepFlatten2() function to flat, which in the above test-case would result in 1 (the first element of the argument) being bound to flat in both the examples. 1.concat is not a function 28 | 29 | */ 30 | 31 | // SOLUTION-3 - huge (e.g. 200 000 elements) arrays and also works on nested arrays 32 | 33 | const flattenLargeArray = function(arr, result = []) { 34 | 35 | for (let i = 0, length = arr.length; i < length; i++) { 36 | 37 | const value = arr[i]; 38 | 39 | if (Array.isArray(value)) { 40 | 41 | flattenLargeArray(value, result); 42 | } else { 43 | result.push(value); 44 | } 45 | } 46 | return result; 47 | }; 48 | 49 | 50 | console.log(flattenLargeArray([1, [1], [[3]]])); 51 | 52 | console.log(flattenLargeArray(Array(2).fill(Array(2).fill(Array(2).fill([1]))))); 53 | 54 | console.log(flattenLargeArray([[1],[2,3],[4]])); 55 | 56 | console.log(flattenLargeArray([1, [2], [[3], 4], 5])); 57 | -------------------------------------------------------------------------------- /Array-Problems/forEach-first-Principle-custom-callback.js: -------------------------------------------------------------------------------- 1 | // filter - Implement your owen Array.prototype.map function 2 | // Solution - 1 3 | 4 | Array.prototype.myMap = function (callback) { 5 | 6 | arr = [] 7 | 8 | for (let i = 0; i < this.length; i++) { 9 | 10 | arr.push(callback(this[i], i, this)); 11 | } 12 | return arr; 13 | } 14 | 15 | let numbers = [ 1, 4, 9 ] ; 16 | 17 | let squareRoot = numbers.myMap(i => Math.sqrt(i)) 18 | 19 | console.log(squareRoot); // => [ 1, 2, 3 ] 20 | 21 | 22 | // Without using Array.prototype 23 | 24 | myMap2 = (array, callback) => { 25 | 26 | let arr = []; 27 | 28 | for (let i = 0; i < array.length; i++) { 29 | arr.push(callback(array[i], i, this)) 30 | } 31 | return arr; 32 | } 33 | 34 | let squareRoot1 = myMap2(numbers, (num) => { 35 | return Math.sqrt(num) 36 | }) 37 | 38 | console.log(squareRoot1); // => [ 1, 2, 3 ] -------------------------------------------------------------------------------- /Array-Problems/indexOf_manually_build.js: -------------------------------------------------------------------------------- 1 | /* Problem Statement - 2 | Build the function indexOf, for the case when the browser does not support the function natively. 3 | */ 4 | 5 | if(!Array.prototype.indexOf) { 6 | Array.prototype.indexOf = function indexOf(searchElement, startFromIndex) { 7 | if(startFromIndex == null) { 8 | startFromIndex = 0; 9 | } else if (startFromIndex < 0) { 10 | startFromIndex = Math.max(0, (this.length + startFromIndex)); 11 | } 12 | for (var i = startFromIndex; i < this.length; i++ ) { 13 | if (this[i] === searchElement) 14 | return i; 15 | } 16 | return -1; 17 | }; 18 | } 19 | 20 | /*My Own learning note - Note that when variable startFromIndex < 0, we are updating its value by adding it with length of the array - based on the official definition of this argument when its negative - "it is taken as the offset from the end of the array". And "the array is still searched from front to back" So if startFromIndex is passed a value of -1 and the array has a length of 3, the indexOf function will start its searching from index position of 1 towards right. 21 | */ -------------------------------------------------------------------------------- /Array-Problems/largest-numbers-from-subarray.js: -------------------------------------------------------------------------------- 1 | /* https://www.freecodecamp.org/challenges/return-largest-numbers-in-arrays 2 | 3 | Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. So the given sub-array will be a 2D Array of Arrays 4 | 5 | largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27,5,39,1001] */ 6 | 7 | function largestOfFour(arr) { 8 | 9 | let maxArray = [0, 0, 0, 0]; 10 | 11 | for (let outerIndex = 0; outerIndex < arr.length; outerIndex++) { 12 | for (let innerIndex = 0; innerIndex < arr[outerIndex].length; innerIndex++) { 13 | if (arr[outerIndex][innerIndex] > maxArray[outerIndex]) { 14 | maxArray[outerIndex] = arr[outerIndex][innerIndex] ; 15 | } 16 | } 17 | } 18 | return maxArray; 19 | } 20 | 21 | console.log(largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])); -------------------------------------------------------------------------------- /Array-Problems/map-first-Principle-custom-callback.js: -------------------------------------------------------------------------------- 1 | // filter - Implement your owen Array.prototype.map function 2 | // Solution - 1 3 | 4 | Array.prototype.myMap = function (callback) { 5 | 6 | arr = [] 7 | 8 | for (let i = 0; i < this.length; i++) { 9 | 10 | arr.push(callback(this[i], i, this)); 11 | } 12 | return arr; 13 | } 14 | 15 | let numbers = [ 1, 4, 9 ] ; 16 | 17 | let squareRoot = numbers.myMap(i => Math.sqrt(i)) 18 | 19 | console.log(squareRoot); // => [ 1, 2, 3 ] 20 | 21 | 22 | // Without using Array.prototype 23 | 24 | myMap2 = (array, callback) => { 25 | 26 | let arr = []; 27 | 28 | for (let i = 0; i < array.length; i++) { 29 | arr.push(callback(array[i], i, this)) 30 | } 31 | return arr; 32 | } 33 | 34 | let squareRoot1 = myMap2(numbers, (num) => { 35 | return Math.sqrt(num) 36 | }) 37 | 38 | console.log(squareRoot1); // => [ 1, 2, 3 ] -------------------------------------------------------------------------------- /Array-Problems/max-repeated-num-in-array.js: -------------------------------------------------------------------------------- 1 | // given an array of integers, find the number that is repeated the most. 2 | 3 | maxRepeatNum = arr => { 4 | 5 | let elemHash = {}; 6 | 7 | for (let i of arr) { 8 | if (elemHash[i]) { 9 | elemHash[i] += 1 10 | } else { 11 | elemHash[i] = 1 12 | } 13 | } 14 | // return elemHash // => { '1': 2, '2': 1, '3': 2, '5': 3, '8': 1 } // this is just for debugging 15 | 16 | // Now return the the key that has the max value, I have few option for that 17 | 18 | // Option-1 - Getting key with the highest value from object 19 | // return Object.keys(elemHash).reduce((a, b) => (elemHash[a] > elemHash[b]) ? a : b ) // => 5 20 | 21 | 22 | //Option-2 - Getting key with the highest value from object 23 | let max = Math.max(...(Object.keys(elemHash).map(i => elemHash[i]))) 24 | // so max is now the highest value that I have in the entire object 25 | // So, now I have to find the key given this highest value 26 | return Object.keys(elemHash).filter(i => elemHash[i] === max)[0]; // => 5 27 | 28 | } 29 | 30 | let myArr = [ 1, 2, 1, 3, 5, 5, 8, 3, 5] 31 | 32 | console.log(maxRepeatNum(myArr)); // => 5 33 | 34 | -------------------------------------------------------------------------------- /Array-Problems/max-repeating-element.js: -------------------------------------------------------------------------------- 1 | /* Get the element with the highest occurrence in an array 2 | 3 | https://www.geeksforgeeks.org/find-the-maximum-repeating-number-in-ok-time/ 4 | 5 | The naive approach is to run two loops, the outer loop picks an element one by one, the inner loop counts number of occurrences of the picked element. Finally return the element with maximum count. Time complexity of this approach is O(n^2). 6 | 7 | A better approach is to create a count array of size k and initialize all elements of count[] as 0. Iterate through all elements of input array, and for every element arr[i], increment count[arr[i]]. Finally, iterate through count[] and return the index with maximum value. This approach takes O(n) time, but requires O(k) space. 8 | 9 | For example, in ['pear', 'apple', 'orange', 'apple'] the 'apple' element is the most frequent one. 10 | 11 | */ 12 | 13 | maxRepeatingElem = arr => { 14 | 15 | var counter = {}; 16 | 17 | for (let i of arr) { 18 | 19 | (counter[i] == null ) ? ( counter[i] = 1 ) : counter[i]++ 20 | 21 | } 22 | 23 | // Find the key given the max value from a key-value pair of object 24 | return Object.keys(counter).reduce((a, b) => counter[a] > counter[b] ? a : b) 25 | 26 | // Alternative to find the key given the max value from a key-value pair of object - i.e. I could replace the above return with the below 27 | // return Object.keys(counter).find(i => counter[i] === Math.max(...Object.values(counter))); 28 | } 29 | 30 | 31 | let myArr = ['pear', 'apple', 'orange', 'apple']; 32 | 33 | console.log(maxRepeatingElem(myArr)); -------------------------------------------------------------------------------- /Array-Problems/misc_Array_Problems_JS-Cookbook.js: -------------------------------------------------------------------------------- 1 | /* Problem statement 1 - You want to convert an array of decimal numbers into a new array with their hexadecimal equivalents. 2 | */ 3 | 4 | var decimalArray = [23, 255, 122, 5, 16, 99]; 5 | 6 | var hexadecimalArray = decimalArray.map(function(element) { 7 | return element.toString(16); 8 | }); 9 | 10 | console.log(hexadecimalArray); 11 | 12 | 13 | /* Problem statement 2 - You want to filter element values in an array and assign the results to a new array. */ 14 | 15 | var charSet = ["**","bb","cd","**","cc","**","dd","**"]; 16 | 17 | var newArray = charSet.filter(function(element) { 18 | return (element !== "**"); 19 | }); 20 | 21 | console.log(newArray); 22 | 23 | /* Problem Statement 3 - You want to ensure that array contents meet certain criteria. In this case, ensure that every element in the array consists of alphabetical characters */ 24 | 25 | function testValue(element, index, array) { 26 | var testExp = /^[a-zA-Z]+$/; 27 | return testExp.test(element); 28 | }; 29 | 30 | var elementSet = ["**",123,"aaa","abc","-",46,"AAA"]; 31 | 32 | var result = elementSet.every(testValue); 33 | 34 | console.log(result); 35 | 36 | var elementSet2 = ["elephant","lion","cat","dog"]; 37 | 38 | var result2 = elementSet2.every(testValue); 39 | 40 | console.log(result2); 41 | 42 | /* The Array-problems some() method checks to ensure that at least some of the array elements are alphabetical strings*/ 43 | 44 | var result3 = elementSet.some(testValue); 45 | 46 | console.log(result3); 47 | 48 | /* Problem Statement 3 - */ -------------------------------------------------------------------------------- /Array-Problems/reduce_method_applications.js: -------------------------------------------------------------------------------- 1 | /* Problem Statement - 2 | Parse the array and return an object that contains the number of times each string occured in the array*/ 3 | 4 | var array = ["apple","orange","apple","orange","pear","orange"]; 5 | 6 | function getWordCount() { 7 | var previous = {}; 8 | return array.reduce(function(previous, next) { 9 | previous[next] = (previous[next] + 1) || 1; 10 | return previous; 11 | }, previous); 12 | } 13 | 14 | console.log(getWordCount()); 15 | 16 | /* 17 | My own learnin note - See another example of this kind of mechanism of grabbing the output into a nice object within curly braces, with property-value pairs, after doing some execution on the original array elements in Elequent Javascript book, page-92*/ 18 | -------------------------------------------------------------------------------- /Array-Problems/reverseArray-Recursively.js: -------------------------------------------------------------------------------- 1 | /* Problem Statement - 2 | Implement a function that will recursively traverse an array and return a string of the array element values, in reverse order*/ 3 | 4 | function reverseArray(arr, indx, str) { 5 | return indx == 0 ? str : reverseArray(arr, --indx, (str+= " " + arr[indx])); 6 | } 7 | 8 | /* Learning note on the above function - We start with the end of the array (as the requirement is to reverse the array elements), and with each iteration, we decrement indx AND ALSO update the 'str' parameter by adding the string value of that particular arr[index]. So on the very first iteration will yield 'motorbike'. 9 | */ 10 | 11 | var arr1 = ['car', 'boat', 'bike', 'motorbike']; 12 | console.log(reverseArray(arr1, arr1.length, "")); 13 | 14 | // Alternative to reverse an array with the 'z' pattern matching library 15 | 16 | require('z'); 17 | 18 | var myReverse = list => { 19 | return list.matches ( 20 | () => [], //match empty list (to check list ending) 21 | (head, tail) => myReverse(tail).concat(head) //match list head/tail to create reversed list recusively 22 | ) 23 | } 24 | console.log(myReverse(['car', 'boat', 'bike', 'motorbike'])); 25 | -------------------------------------------------------------------------------- /Array-Problems/search-unknown-length-Array.js: -------------------------------------------------------------------------------- 1 | const expect = require('chai').expect; 2 | 3 | /* PROBLEM - Search Unknown Length Array - Given a sorted array of unknown length and a number to search for, return the index of the number in the array. Accessing an element out of bounds throws exception. If the number occurs multiple times, return the index of any occurrence. If it isn’t present, return -1. */ 4 | 5 | let myArr = [3, 5, 6, 7, 8]; 6 | 7 | console.log(myArr.indexOf(11)); -------------------------------------------------------------------------------- /Array-Problems/shuffle_Array-2.js: -------------------------------------------------------------------------------- 1 | // Slight variation of the BEST AND SIMPLE IN-PLACE SOLUTION IN O(n) time in the other file 2 | // Implementation of the Durstenfeld shuffle, a computer-optimized version of Fisher-Yates of the same Array shuffle problem 3 | 4 | shuffleArray = arr => { 5 | for (let i = arr.length - 1; i >= 0; i--) { 6 | let randIndex = Math.floor(Math.random() * ( i + 1)); 7 | [ arr[i], arr[randIndex] ] = [ arr[randIndex], arr[i] ] 8 | } 9 | return arr; 10 | } 11 | 12 | let myArr1 = [1, 2, 3, 4, 5] 13 | console.log(shuffleArray(myArr1)) 14 | 15 | // The running time of this algorithm is O(n). Note that the shuffle is done in-place. So if you do not want to modify the original array, make a copy of it first with .slice(0). -------------------------------------------------------------------------------- /Array-Problems/tempCodeRunnerFile.js: -------------------------------------------------------------------------------- 1 | 2 | console.time("1st"); 3 | // _.flatMap(data, item => [createAllocation1(item)]); 4 | console.log(_.flatMap(data, item => [createAllocation1(item)])); 5 | console.timeEnd("1st"); 6 | 7 | console.log("*******************************"); 8 | 9 | console.time("2nd"); 10 | _.flatMap(data, item => [createAllocation2(item)]); 11 | console.timeEnd("2nd"); 12 | 13 | console.log("*******************************"); -------------------------------------------------------------------------------- /Array-Problems/tiny-Array-probs/clone_Array.js: -------------------------------------------------------------------------------- 1 | // Method-1 2 | let originalArray = [ 1, 2, 3] 3 | let [...arrayClone] = originalArray; 4 | console.log(arrayClone) // => [ 1, 2, 3 ] 5 | 6 | // Method-2 7 | let originalArray1 = [ 1, 2, 3] 8 | let arr2 = originalArray1.concat() 9 | console.log(arr2) // => [ 1, 2, 3 ] 10 | 11 | 12 | 13 | // Method-3 - Technically slice IS the fastest way, HOWEVER it is even faster if you add the 0 begin index. 14 | // myArray.slice(0) is faster than myArray.slice(); 15 | 16 | let originalArray2 = [ 1, 2, 3] 17 | let arr3 = originalArray1.slice(0) 18 | console.log(arr3) // => [ 1, 2, 3 ] 19 | 20 | // Method-4 21 | let originalArray3 = [ 1, 2, 3] 22 | let arr4 = originalArray1.splice(0) 23 | console.log(arr4) // => [ 1, 2, 3 ] 24 | 25 | /* Method-5 - Easiest way to deep clone Array or Object: 26 | this also inherits its limitations. Among other things, that means your array cannot contain undefined or any functions. Both of those will be converted to null for you during the JSON.stringify process. Other strategies, such as (['cool','array']).slice() will not change them but also do not deep clone objects within the array. So there is a tradeoff. 27 | Very bad perf and don't work with special objects like DOM, date, regexp, function 28 | 29 | The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. 30 | The JSON.stringify() method converts a JavaScript value to a JSON string 31 | 32 | */ 33 | let originalArray4 = [ 1, 2, 3] 34 | let arr5 = JSON.parse(JSON.stringify(originalArray4)) 35 | console.log(arr5) // => [ 1, 2, 3 ] -------------------------------------------------------------------------------- /Array-Problems/tiny-Array-probs/returns-true-if-all-elemensts-true.js: -------------------------------------------------------------------------------- 1 | /*PROBLEM - 1 >> Returns true if the provided predicate function returns true for all elements in a collection, false otherwise. 2 | 3 | Use Array.every() to test if all elements in the collection return true based on fn. Omit the second argument, fn, to use Boolean as a default. */ 4 | 5 | all = (arr, fn = Boolean) => arr.every(fn); 6 | 7 | // console.log(all([4, 2, 3], x => x > 1)); 8 | 9 | // console.log(([4, 2, 3].every( x => x < 3 ))); 10 | 11 | 12 | /* PROBLEM - 2 >> Returns true if the provided predicate function returns true for at least one element in a collection, false otherwise. 13 | 14 | Use Array.some() to test if any elements in the collection return true based on fn. Omit the second argument, fn, to use Boolean as a default. */ 15 | 16 | any = (arr, fn = Boolean) => arr.some(fn); 17 | 18 | // console.log(any([4, 2, 3], x => x < 4)); 19 | 20 | console.log([4, 2, 3].some(x => x < 3)); 21 | 22 | -------------------------------------------------------------------------------- /ES6/Destructuring_Geneal.md: -------------------------------------------------------------------------------- 1 | ### General Object Destructuring Example 2 | 3 | ```js 4 | let myObj = { 5 | name: "Luke", 6 | age: 25, 7 | hobbies: "music" 8 | }; 9 | 10 | let { name, age, hobbies } = myObj; 11 | 12 | console.log(name, age, hobbies); // => Luke 25 music 13 | ``` 14 | 15 | Now the variables listed in between the curly braces are assigned the value of their respective properties in myObj. 16 | 17 | ### The order in which the variables are listed in the curly braces doesn’t matter. Additionally, we don’t have to list all the properties of an object if we only need one or two. 18 | 19 | ```js 20 | console.log(age, name, hobbies); // => 25 'Luke' 'music' 21 | 22 | console.log(hobbies, name, age); // => music Luke 25 23 | 24 | console.log(hobbies, name); // => music Luke 25 | 26 | ``` 27 | 28 | ### General Array Destructuring Example 29 | 30 | ```js 31 | let arr = [‘Jim’, ‘Bob’, ‘Sarah’, ‘Cassie’]; 32 | 33 | let [ jim, bob, sarah, cassie ] = arr; 34 | 35 | console.log(jim, bob, sarah, cassie); //outputs: Jim Bob Sarah Cassie 36 | ``` 37 | 38 | ## Unlike objects, the name we give the variables doesn’t matter. Let’s change the above example: So, each of the variable names will ONLY count for the index-positions I fetch. 39 | 40 | ```js 41 | let arr = [‘Jim’, ‘Bob’, ‘Sarah’, ‘Cassie’]; 42 | 43 | let [ var1, var2, var3, var4] = arr; 44 | 45 | console.log(var1, var2, var3, var4); //outputs: Jim Bob Sarah Cassie 46 | ``` 47 | 48 | ### If I include less variables then there are indexes in the arrays, then just like in Object-destructuring, only that many array element will be included in the returned array, starting from zero-index position and AGAIN without giving any meaning to the the name I give to the variables. So, each of the variable names will ONLY count for the index-positions I fetch. 49 | 50 | let arr = [‘Jim’, ‘Bob’, ‘Sarah’, ‘Cassie’]; 51 | 52 | let [ jim, bob, cassie ] = arr; 53 | 54 | console.log(jim, bob, cassie); //outputs: Jim Bob Sarah 55 | 56 | ## Using Spread operator - It is often used for splitting out a part of an object, but keeping the remaining properties in another object. 57 | 58 | ```js 59 | let myObj = { 60 | 61 | name: "Luke", 62 | age: 25, 63 | hobbies: "music" 64 | 65 | }; 66 | 67 | let { hobbies, ...rest } = myObj; // => Luke 25 music 68 | 69 | console.log(hobbies, rest) // => music { name: 'Luke', age: 25 } 70 | 71 | console.log(hobbies, rest.age) // => music 25 72 | 73 | ``` -------------------------------------------------------------------------------- /ES6/callback-hell-examples.js: -------------------------------------------------------------------------------- 1 | 2 | setTimeout((changeMaker) => { 3 | let list = changeMaker + ', '; 4 | 5 | setTimeout((changeMaker) => { 6 | list += changeMaker + ', '; 7 | 8 | setTimeout((changeMaker) => { 9 | list += changeMaker + ', '; 10 | 11 | setTimeout((changeMaker) => { 12 | list += changeMaker + ', '; 13 | 14 | setTimeout((changeMaker) => { 15 | list += changeMaker 16 | 17 | console.log(list); 18 | }, 1, 'Travis Kalanick'); 19 | }, 1, 'MarkZuckerberg'); 20 | }, 1, 'SteveWoz'); 21 | }, 1, 'SteveJobs'); 22 | }, 1, 'BillGates'); 23 | 24 | 25 | /* Looking at the above, setTimeout gets a callback function that executes after one millisecond. The last parameter just feeds the callback with data, i.e the argument 'changeMaker' . This is like an Ajax call except the return 'changeMaker' parameter would come from the server. 26 | 27 | I am gathering a list of changeMakers through asynchronous code. Each callback gives me a single 'changeMaker' name and I append that to the list. */ 28 | 29 | -------------------------------------------------------------------------------- /ES6/create-class-in-ES6.js: -------------------------------------------------------------------------------- 1 | class User { 2 | 3 | constructor (name, age) { 4 | this.name = name; 5 | this.age = age; 6 | } 7 | 8 | getUserData() { 9 | console.log(this.name + " is " + this.age + " years old."); 10 | } 11 | } 12 | 13 | let user = new User('paul', 18) 14 | user.getUserData() -------------------------------------------------------------------------------- /ES6/destructuring.js: -------------------------------------------------------------------------------- 1 | //Destructuring Example-1 2 | /* Destructuring allows us to extract data from arrays and objects into separate variables. 3 | 4 | Destructuring can also be used for passing objects into a function, allowing you to pull specific properties out of an object in a concise manner. It is also possible to assign default values to destructured arguments, which can be a useful pattern if passing in a configuration object. */ 5 | 6 | let jane = { firstName: 'Jane', lastName: 'Doe'}; 7 | let john = { firstName: 'John', lastName: 'Doe', middleName: 'Smith' } 8 | 9 | // the below pattern that I always use in React 10 | let sayName = ({firstName, lastName, middleName = "N/A"}) => { 11 | console.log(`Hello ${firstName} ${lastName} ${middleName}`); 12 | } 13 | 14 | // sayName(jane); // -> Hello Jane N/A Doe 15 | // sayName(john) // -> Hello John Doe Smith 16 | 17 | // Examples of array destructuring for function parameters: 18 | function foo ( [x, y] ) { 19 | console.log(x, y); 20 | } 21 | 22 | // foo([1,2]); // -> 1 2 23 | // foo([2]); // -> 2 undefined 24 | // foo([]) // -> undefined undefined 25 | 26 | 27 | // Examples of Object destructuring for parameters in function declaration: 28 | 29 | function foo ( { x, y } ) { 30 | console.log(x, y); 31 | } 32 | 33 | foo({y: 1, x: 2}) // -> 2 1 34 | 35 | foo({y: 1}) // -> undefined 1 36 | 37 | foo({}) // -> undefined undefined 38 | 39 | /* This technique is an approximation of named arguments, in that the properties on the object map to the destructured parameters of the same names. That also means that we get optional parameters (in any position) for free, as you can see leaving off the x "parameter" worked as we'd expect. */ 40 | 41 | 42 | //Destructuring Example-2 43 | 44 | let full_name =['John','Deo']; 45 | 46 | let [first_name,last_name]=full_name; 47 | 48 | console.log(first_name,last_name); 49 | // outputs John Deo -------------------------------------------------------------------------------- /ES6/every-method-of-Array.js: -------------------------------------------------------------------------------- 1 | /*every: 2 | 3 | callback is a predicate - it should return a truthy or falsy value 4 | callback answers: does this item meet your criteria? 5 | callback gets these arguments: item, index, list 6 | final return value: false after the first item that failed to meet your criteria, else true 7 | note: stops iterating once it receives a falsy value from your callback. 8 | example use case:*/ 9 | 10 | const allPositiveNumbers = [1 , 2, 3].every((item) => { 11 | return item > 0; 12 | }) 13 | 14 | console.log(allPositiveNumbers); -------------------------------------------------------------------------------- /ES6/fat-arrow-function.js: -------------------------------------------------------------------------------- 1 | setTimeout(function() { 2 | console.log("'setTimeout called") 3 | }, 1000) 4 | 5 | /* The function we pass as an argument to setTimeout is called an anonymous function because it doesn’t have a name. 6 | 7 | ES6 has introduced a slightly different syntax to define anonymous functions called the fat arrow syntax, with it we can re-write the above as: */ 8 | 9 | setTimeout(() => { 10 | console.log("Fat arrow fn in setTimeout called") 11 | }, 1000) 12 | 13 | // What if we wanted to pass an argument to the function? We can re-write the below normal function to one that uses the fat arrow syntax: 14 | 15 | let add = function(a,b) { 16 | return a + b; 17 | }; 18 | 19 | // Can now be written as: 20 | 21 | let add = (a,b) => a + b; 22 | 23 | // In the first example we write return a + b but in the fat arrow version we just wrote a + b. That’s because in the fat arrow syntax if it is on one line, the statement gets returned automatically without the need to use the return keyword. 24 | // There is no "thin arrow function". -------------------------------------------------------------------------------- /ES6/filter-implement-remove-duplicates.js: -------------------------------------------------------------------------------- 1 | // Problem-1 Filter even numbers 2 | 3 | let numberArray = [1,2,3,4,5,6,7,8,9,10]; 4 | 5 | let evenNumbers = []; 6 | 7 | for (let i = 0; i < numberArray.length; i++) { 8 | if (numberArray[i] % 2 === 0) { 9 | evenNumbers.push(numberArray[i]); 10 | } 11 | } 12 | // console.log(evenNumbers); 13 | 14 | let evenNumbersWithFilter = numberArray.filter((item) => (item % 2 === 0)); 15 | 16 | // console.log(evenNumbersWithFilter); 17 | 18 | 19 | // Problem 2:- Filter objects with tags javascript 20 | 21 | var persons = [ 22 | {id : 1, name : "John", tags : "javascript"}, 23 | {id : 2, name : "Alice", tags : "javascript"}, 24 | {id : 3, name : "Roger", tags : "java"}, 25 | {id : 4, name : "Adam", tags : "javascript"}, 26 | {id : 5, name : "Alex", tags : "java"} 27 | ]; 28 | 29 | let jsTags = persons.filter((item) => (item.tags === "javascript")) 30 | 31 | // console.log(jsTags); 32 | 33 | // Problem 2 with indexOf 34 | let jsTags2 = persons.filter((item) => (item.tags.indexOf("javascript") > -1)); 35 | 36 | // console.log(jsTags2); 37 | 38 | // Other example - traverses an array and inserts non-duplicate elements into a new array. That is, if an element is duplicated, then only insert that element once into the final newArray 39 | 40 | function findNonDuplicates (array) { 41 | let models = []; 42 | for(var i = 0; i < array.length; i++) { 43 | if(array.indexOf(array[i]) === i) { 44 | models.push(array[i]); 45 | } 46 | } 47 | return models; 48 | } 49 | 50 | let arr = [1, 2, 3, 4.4, 2]; 51 | // console.log(findNonDuplicates((arr))); 52 | 53 | // using filter 54 | function findNonDuplicatesFilter (array) { 55 | return array.filter((elem, index, arr) => { 56 | return array.indexOf(elem) === index; 57 | }) 58 | } 59 | 60 | // console.log(findNonDuplicatesFilter(arr)); 61 | 62 | // Write a function that returns the number of zeros in a given array? 63 | noOfZeros = arr => { 64 | return arr.filter(zero => (zero === 0)).length 65 | } 66 | 67 | console.log(noOfZeros([1, 2, 0, 0, 5])); 68 | 69 | -------------------------------------------------------------------------------- /ES6/find-method.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | find () - arguments explanation 4 | 5 | callback is a predicate - it should return a truthy or falsy value 6 | callback answers: is this item what you’re looking for? 7 | callback gets these arguments: item, index, list 8 | final return value: the item you’re looking for, or undefined 9 | note: stops iterating once it receives a truthy value from your callback. 10 | example use case 11 | 12 | 13 | findIndex: 14 | 15 | callback is a predicate - it should return a truthy or falsy value 16 | callback answers: is this item what you’re looking for? 17 | callback gets these arguments: item, index, list 18 | final return value: the index of the item you’re looking for, or -1 19 | note: stops iterating once it receives a truthy value from your callback. 20 | example use case:*/ 21 | 22 | 23 | // Examaple to find negaive number 24 | function findNegativeNum (elem) { 25 | return elem < 0; 26 | } 27 | 28 | let myArr = [1, 20, false, -2]; 29 | 30 | // find method returns first negative number found 31 | // console.log(myArr.find(findNegativeNum)); // -2 32 | 33 | // findIndex method returns index of first negative number located 34 | // console.log(myArr.findIndex(findNegativeNum)); // 3 35 | 36 | // example function to find non-numeric array values 37 | function findNonNum(elem) { 38 | return typeof elem !== 'number' ; 39 | } 40 | 41 | let myArr1 = [2, 27, 33.45, 'apple', 'yes', 0, 3.14]; 42 | 43 | // find method returns value of first non-numeric element 44 | // console.log(myArr1.find(findNonNum)); 45 | // findIndex returns location of first non-numeric element 46 | // console.log(myArr1.findIndex(findNonNum)); 47 | 48 | // another example array to search for non-numeric values 49 | let myArr3 = [1, 2, 3, 4.4]; 50 | 51 | // console.log(myArr3.find(findNonNum)); // returns undefined 52 | // console.log(myArr3.findIndex(findNonNum)); // returns -1 53 | 54 | 55 | const objects = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]; 56 | 57 | const findIdWithb = objects.find((item) => { 58 | return item.id === 'b' 59 | }); 60 | 61 | console.log(findIdWithb); 62 | 63 | const findIdIndexWithb = objects.findIndex((item) => { 64 | return item.id === 'b' 65 | }); 66 | 67 | console.log(findIdIndexWithb); -------------------------------------------------------------------------------- /ES6/function-currying.js: -------------------------------------------------------------------------------- 1 | /* https://en.wikipedia.org/wiki/Currying 2 | 3 | n mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument. 4 | 5 | Currying is a process to reduce functions of more than one argument to functions of one argument with the help of lambda calculus. 6 | f(n, m) --> f'(n)(m) 7 | */ 8 | 9 | // simple add() funtion without currying 10 | add = (x, y) => x + y 11 | add(2, 3) // => 5 12 | 13 | // Now the same function in curryied form 14 | add_curried = x => y => x + y 15 | 16 | //in order to use our curried function, we have to call it a bit differently … This is because the first (outer) function call returns a second (inner) function. Only after we call the second function do we actually get the result. 17 | 18 | console.log(add_curried(2)(3)) // => 5 19 | 20 | // Here is the same code of curried function without arrow functions … 21 | let add_curried_ES5 = function (x) { 22 | return function(y) { 23 | return x + y 24 | } 25 | } 26 | 27 | console.log(add_curried_ES5(2)(3)) // => 5 28 | 29 | // SIMPLE EXPLANATION - Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. 30 | 31 | const notCurry = (x, y, z) => x + y + z; // a regular function 32 | const curry = x => y => z => x + y + z; // a curry function 33 | 34 | // currying applied on a familiar JavaScript method and generating new functions using it: 35 | // First, normal implementation 36 | let myStr = "rohan" 37 | console.log(myStr.substr(0, 2)); // => ro 38 | 39 | // now curried implementation 40 | const curriedSubstr = start => length => str => str.substr(start, length) 41 | 42 | const getCurriedSubstr = (start, length, str) => curriedSubstr(start) (length) (str) 43 | 44 | console.log(getCurriedSubstr(0, 2, myStr)) // => ro 45 | 46 | -------------------------------------------------------------------------------- /ES6/map-Implementation-On-Objects.js: -------------------------------------------------------------------------------- 1 | // The map() method creates a new array with the results of calling a provided function on every element in this array. 2 | 3 | // Problem - 1 We’ve an array of products, that has two properties: `id` and `name`. I want to get all ids, wih map() method: 4 | 5 | let products = [ 6 | { 7 | id: 0, 8 | name: 'Product 1' 9 | }, 10 | { 11 | id: 1, 12 | name: 'Product 2' 13 | } 14 | ]; 15 | 16 | let productsIds = products.map((item) => { 17 | return item.id; 18 | }) 19 | 20 | // console.log(productsIds); 21 | 22 | /* Problem-2 23 | 24 | The map() mehod's syntax is as below 25 | 26 | let newArr = oldArr.map((val, index, arr) => { 27 | // return element to new Array 28 | }); 29 | 30 | newArr — the new array that is returned 31 | oldArr — the array to run the map function on 32 | val — the current value being processed 33 | index — the current index of the value being processed 34 | arr — the original array 35 | 36 | Create an object from a given array and the given array is as below 37 | [1,2,3,4]; 38 | 39 | */ 40 | 41 | let arr = [1,2,3,4]; 42 | 43 | let obj = arr.map((val, index, arr) => { 44 | return { 45 | VALUE : val, 46 | INDEX: index 47 | } 48 | }) 49 | 50 | // console.log(obj); 51 | 52 | // Problem-2 - Using map() return full name from the given array 53 | var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}]; 54 | 55 | let newArr = []; 56 | 57 | oldArr.map((item, index) => { 58 | item.full_name = [item.first_name, item.last_name].join(' '); 59 | return item; 60 | }); 61 | console.log(oldArr); -------------------------------------------------------------------------------- /ES6/rest-spread.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rohan-paul/Javascript-Common-Challenges-Problems/79fe5eb3f88cf35840e836fc9ca8d9fd7063f2c4/ES6/rest-spread.jpg -------------------------------------------------------------------------------- /ES6/rest-spread.js: -------------------------------------------------------------------------------- 1 | /* KEY POINT - The spread operator allows us to spread the value of an array (or any iterable) across zero or more arguments in a function or elements in an array (or any iterable). 2 | 3 | SO WITH SPREAD THING 'UNPACKING ELEMENTS' - Allowes an iterable (array, string, object) to be expanded where more arguments / elements are expected. 4 | 5 | The rest parameter allows us to pass an indefinite number of parameters to a function and access them in an array. So rest parameter is ONLY about when I am implementing argument passing mechanism in more compact way - Otherwise both take the same triple-dot (...) syntax 6 | Rest parameters must be at the end or it does not work 7 | 8 | SO WITH REST THING 'PACKING ELEMENTS' - Collects multiple elements and condenses them into a single eleme. 9 | 10 | */ 11 | 12 | // Example - Display the array of passed arguments. 13 | 14 | function printArguments(...theArguments) { 15 | console.log(theArguments); 16 | } 17 | 18 | printArguments("hi", "this", "is", "paul"); // => [ 'hi', 'this', 'is', 'paul' ] 19 | 20 | // Example - 2 - spreading object 21 | 22 | let spreadableObj = { 23 | key1: "value1", 24 | key2: "value2" 25 | }; 26 | 27 | let newObj = { 28 | ...spreadableObj, 29 | key3: "value3" 30 | }; 31 | 32 | console.log(newObj); // => { key1: 'value1', key2: 'value2', key3: 'value3' } 33 | 34 | // Example - 3 - Spreading Array 35 | 36 | //Combine two arrays. 37 | 38 | const spreadableOne = [1, 2, 3, 4]; 39 | const spreadableTwo = [5, 6, 7, 8]; 40 | 41 | const combinedArr = [...spreadableOne, ...spreadableTwo]; 42 | console.log(combinedArr); // => [ 1, 2, 3, 4, 5, 6, 7, 8 ] 43 | 44 | // Remove an array element without mutating the original array. From the below arrray remove 'salmon' and return the array - Great example, without using splice(), as splice() will mutate the original array 45 | 46 | const animals = ["squirrel", "bear", "deer", "salmon", "rat"]; 47 | 48 | const newArr = [...animals.slice(0, 3), ...animals.slice(4)]; 49 | 50 | console.log(newArr); // [ 'squirrel', 'bear', 'deer', 'rat' ] 51 | -------------------------------------------------------------------------------- /ES6/some-method-of-Array.js: -------------------------------------------------------------------------------- 1 | /*some: 2 | 3 | callback is a predicate - it should return a truthy or falsy value 4 | callback answers: does this item meet your criteria? 5 | callback gets these arguments: item, index, list 6 | final return value: true after the first item that meets your criteria, else false 7 | note: stops iterating once it receives a truthy value from your callback. 8 | example use case:*/ 9 | 10 | const hasNegativeNumber = [1, 2, 3, -4, 5].some((item) => { 11 | return item < 0; 12 | }) 13 | 14 | console.log(hasNegativeNumber); -------------------------------------------------------------------------------- /ES6/this-in-ES6/this-in-ES6_3.js: -------------------------------------------------------------------------------- 1 | // Regular function binding to global object's this 2 | 3 | function foo() { 4 | return console.log(this.a); // global 5 | } 6 | 7 | foo.a = 'func'; 8 | 9 | global.a = 'global-variable'; 10 | 11 | // note in above, I can not use var a = 'global' in my node environment, but can do so in the chrome dev-tool environment. Remember, in browser the global object is window and in node its 'global' 12 | 13 | 14 | foo(); // => global-variable 15 | 16 | /* 17 | The reason why above gave a console of global-variable, is because we mentioned earlier that this context for a function, is not decided by where it is declared, but by how and where it is called! Here, foo was called from the global context, and during its execution, this will be binded to the global object [Default binding rule], and since, regular functions and global object can only have this context, this context at the time of execution was pointing to the variable a declared in global scope, and hence the value was a was global and not func. 18 | 19 | */ 20 | 21 | // As expected and explained in ES_2.js file that below will output undefine, as arrow function does not have any this binding 22 | 23 | var obj_1 = { 24 | a : 'object???', 25 | foo_1 : () => { console.log(this.a) } 26 | }; 27 | 28 | obj_1.foo_1(); // undefined 29 | 30 | 31 | 32 | // Now, wrapping arrow within a function, would make the regular function to bind the object's this.a value 33 | 34 | var obj_2 = { 35 | 36 | a : 'object???', 37 | 38 | foo : function() { 39 | return (() => { 40 | console.log(this.a) 41 | })(); 42 | } 43 | }; 44 | 45 | obj_2.foo(); // object??? 46 | 47 | // 48 | 49 | -------------------------------------------------------------------------------- /ES6/this-in-ES6_3.js: -------------------------------------------------------------------------------- 1 | // Regular function binding to global object's this 2 | 3 | function foo() { 4 | return console.log(this.a); // global 5 | } 6 | 7 | foo.a = 'func'; 8 | 9 | global.a = 'global-variable'; 10 | 11 | // note in above, I can not use var a = 'global' in my node environment, but can do so in the chrome dev-tool environment. Remember, in browser the global object is window and in node its 'global' 12 | 13 | 14 | foo(); // => global-variable 15 | 16 | /* 17 | The reason why above gave a console of global-variable, is because we mentioned earlier that this context for a function, is not decided by where it is declared, but by how and where it is called! Here, foo was called from the global context, and during its execution, this will be binded to the global object [Default binding rule], and since, regular functions and global object can only have this context, this context at the time of execution was pointing to the variable a declared in global scope, and hence the value was a was global and not func. 18 | 19 | */ 20 | 21 | // As expected and explained in ES_2.js file that below will output undefine, as arrow function does not have any this binding 22 | 23 | var obj_1 = { 24 | a : 'object???', 25 | foo_1 : () => { console.log(this.a) } 26 | }; 27 | 28 | obj_1.foo_1(); // undefined 29 | 30 | 31 | 32 | // Now, wrapping arrow within a function, would make the regular function to bind the object's this.a value 33 | 34 | var obj_2 = { 35 | 36 | a : 'object???', 37 | 38 | foo : function() { 39 | return (() => { 40 | console.log(this.a) 41 | })(); 42 | } 43 | }; 44 | 45 | obj_2.foo(); // object??? 46 | 47 | // 48 | 49 | -------------------------------------------------------------------------------- /Functional-Programming/1.js: -------------------------------------------------------------------------------- 1 | /* Return everything 2 | Everything should return, also functions that emit side-effects. Try to preserve homomorphism. Try to keep the return type of a function consistent. Don't mix computations that transform data with things like writing to screen. Modular code is easier to maintain. Use parameters for replaceable data instead of hard-coding. */ 3 | 4 | // Implementation of the above with examples by first using non-best-practice way to return factorial of no-5 5 | 6 | let fact = 1; 7 | 8 | for (let i = 1; i <= 5; i++ ) { 9 | fact *= i; 10 | } 11 | 12 | console.log('Fact of 5: ', fact); 13 | 14 | //Now the best practice 15 | 16 | const factorial = n => 17 | n === 0 ? 1 : n * factorial(n - 1); 18 | 19 | console.log('Factorial of 5 is : ', factorial(5)); 20 | 21 | -------------------------------------------------------------------------------- /Functional-Programming/max.js: -------------------------------------------------------------------------------- 1 | // require _ from ('underscore'); 2 | 3 | var _ = require('underscore'); 4 | 5 | console.log(_.max([1, 2, 3, 4, 5])); 6 | 7 | /* Write a function named plucker() that takes a key into an associative structure—such as an array or an object and returns a function that, given a structure, returns the value at the key. */ 8 | 9 | function plucker (key) { 10 | return function (obj) { 11 | return (obj && obj[key]); 12 | } 13 | } 14 | 15 | //Use case 16 | var best = {title: "Infinite Jest", author: "DFW"}; 17 | 18 | var getTitle = plucker('title'); 19 | // console.log(getTitle(best)); // Infinite Jest 20 | 21 | // Note, getTitle itself is a function because plucker() returns a function as its first return and that takes an argument. 22 | 23 | // another use case 24 | var books = [{title: "Chthon"}, {stars: 5}, {title: "Botchan"}]; 25 | 26 | var third = plucker(2); 27 | console.log(third(books)); // { title: 'Botchan' } 28 | 29 | 30 | -------------------------------------------------------------------------------- /Functional-Programming/pure_functions.js: -------------------------------------------------------------------------------- 1 | // 1>> Combine multiple arrays into one array. 2 | combine = (...arrays) => [].concat(...arrays); 3 | 4 | // console.log(combine(["foo"], ["bar", "baz"], [1, 2])) // => ["foo", "bar", "baz", 1, 2] 5 | 6 | 7 | // 2>> compact(array) - Returns a copy of the array with all falsy values removed. 8 | // compact([0, 1, false, 2, "", 3]) // => [1, 2, 3] 9 | 10 | compact = arr => arr.filter(i => i) 11 | 12 | // console.log(compact([0, 1, false, 2, "", 3])); 13 | 14 | //Alternative 2 15 | compact2 = arr => arr.filter(Boolean) 16 | // console.log(compact2([0, 1, false, 2, "", 3])); 17 | 18 | /* contains(array, value) - Returns true if the value is present in the array. 19 | 20 | contains([1, 2, 3], 3) // => true */ 21 | 22 | contains = (() => Array.prototype.includes 23 | ? (arr, value) => arr.includes(value) 24 | : (arr, value) => arr.some(elem => elem === value) 25 | )(); 26 | 27 | console.log(contains([1, 2, 3], 3)); -------------------------------------------------------------------------------- /General-JS-Problems/Pi-To-n-th-digits.js: -------------------------------------------------------------------------------- 1 | /* 2 | Find PI to the Nth Digit - Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go. 3 | 4 | Based on John Machin's formula pi/4 = 4 * arctan (1/5) - arctan (1/239) 5 | */ 6 | 7 | findPI_ToNthDigits = n => { 8 | 9 | if (n === undefined || n > 20) { 10 | n = 20 11 | } 12 | 13 | return (16 * Math.atan(1/5) - 4 * (Math.atan(1/239))) 14 | } 15 | 16 | console.log(findPI_ToNthDigits(20)); 17 | -------------------------------------------------------------------------------- /General-JS-Problems/atoi-string-to-Number-2.js: -------------------------------------------------------------------------------- 1 | /* Convert a string to an integer in C, JavaScript, and Ruby 2 | 3 | Some Theory - A> The number system ranges from 48 to 59 in chartCodeAt() method 4 | 5 | console.log("0".charCodeAt("0")); // 48 6 | console.log("9".charCodeAt("0")); // 57 7 | 8 | B> JavaScript's highest integer value that a number can go to without losing precision? - he max safe integer is 231-1, or 2147483647. 9 | */ 10 | 11 | // SOLUTION WITHOUT USING REGEXP AND PARSEINT 12 | 13 | myAtoi = str => { 14 | 15 | let i = 0, numSign = '+', number = '', finalOutputNum = 0, base10Multiplier = 1; 16 | 17 | str = str.trim() // remove all whitespaces from both ends 18 | 19 | // First move i forward and update sign to take up '-' if '-' is found 20 | // And if a '+' is found just treat it, as if there was nothing before the number and check-out the next number to start building the number with the next loop 21 | if (str[0] === '+') { 22 | i++ 23 | } else if (str[0] === '-') { 24 | numSign = '-' 25 | i++ 26 | } 27 | 28 | // For the above code, I could just use Regexp, like my other solution in my other file. 29 | 30 | // Now traverse through the given string argument and build the number string. 31 | 32 | for (i ; i < str.length; i++) { 33 | 34 | if (str[i].charCodeAt(0) >= 48 && str[i].charCodeAt(0) <= 57) { 35 | number += str[i] 36 | } else { 37 | if (number === "") { 38 | return 0 39 | } else { 40 | break; 41 | } 42 | } 43 | } 44 | 45 | // From the above I have a string "number". Now without using parseInt() I will convert it to an integer 46 | for (i = (number.length - 1); i >=0; i--) { 47 | 48 | finalOutputNum += base10Multiplier * number[i]; 49 | base10Multiplier *= 10; 50 | 51 | if ( finalOutputNum > 2147483647 && numSign === '+' ) { 52 | return 2147483647 53 | } else if (finalOutputNum > 2147483648 && numSign === '-' ) { 54 | return -2147483648; 55 | } 56 | } 57 | 58 | return ( numSign === '-' ? (-1 * finalOutputNum) : finalOutputNum ) 59 | 60 | } 61 | 62 | console.log(myAtoi("+1")); // => 1 -------------------------------------------------------------------------------- /General-JS-Problems/calculate-log-recursively.js: -------------------------------------------------------------------------------- 1 | function logBase2 (num ) { 2 | if ( num == 1) { 3 | return 0; 4 | } else { 5 | return (1 + logBase2( num / 2)); 6 | } 7 | } 8 | 9 | /* The formulae:- 10 | 11 | log(num) to base 2 = y 12 | 13 | means mathematically 14 | 15 | 2^y = num 16 | */ 17 | 18 | console.log(logBase2(16)); // Should output 4 19 | 20 | /* Explanation 21 | 22 | function logBase2(16); 23 | 24 | = 1 + logBase2 (16 / 2) >> 1 + ( 1 + logBase2(8)) 25 | 26 | = 1 + ( 1 + ( 1 + logBase2 (4)) 27 | 28 | = 1 + ( 1 + ( 1 + (1 + logBase2(2)))); 29 | 30 | = 1 + ( 1 + (1 + (1 + (logBase (1))))) // Here the abort-condition is reached and the loop stops, as logBase2(1) returns 0 31 | 32 | = 1 + 1 + 1 + 1 + 0 = 4 33 | 34 | 35 | */ -------------------------------------------------------------------------------- /General-JS-Problems/check-nonEmptyString.js: -------------------------------------------------------------------------------- 1 | // Problem - You want to verify (assume its called 'unknownVariable') that a variable is defined, is a string, and is not empty. 2 | 3 | if(((typeof unknownVariable !== 'undefined' && unknownVariable) && 4 | unknownVariable.length() > 0) && 5 | typeof unknownVariable.valueOf() == 'string') 6 | -------------------------------------------------------------------------------- /General-JS-Problems/comparing-number-to-string.txt: -------------------------------------------------------------------------------- 1 | Question 2 of 56 2 | 3 | What will be the result of the following line of JavaScript code? 4 | var result = "a" < 3; 5 | alert(result); 6 | Support your answer with detailed reasoning. Be as explicit as possible. 7 | 8 | var result = "a" < 3; 9 | alert(result); 10 | 11 | Will output - false 12 | 13 | JavaScript defines >= and <= (and several other operators) in a way that allows them to coerce their operands to different types. It's just part of the definition of the operator. 14 | 15 | In the case of <, >, <=, and >= check §11.8.5 of the specification. 16 | 17 | If both operands are strings (after having been coerced from objects, if necessary), it does a string comparison. 18 | 19 | Otherwise, it coerces the operands to numbers and does a numeric comparison. 20 | 21 | This works because of typecasting and the fact that NaN < 3 is false. 22 | 23 | When applying to the < operator, both operands are cast to Numbers, so that comparison becomes 24 | 25 | Number("string") < 3 26 | 27 | which is equivalent to NaN < 3 which evaluates to false 28 | 29 | 30 | Question 14 of 56 31 | 32 | var num = -10; 33 | alert(num.toString(2)); 34 | 35 | Will output >> -1010 36 | 37 | The toString() function is used with a number num as shown in above syntax using the ‘.’ operator. This function will convert num to a string. 38 | 39 | Parameters Used: This function accepts a single optional parameter base. This parameter specifies the base in which the integer is represented in string. It is an integer between 2 and 36 which is used to specify the base for representing numeric values. -------------------------------------------------------------------------------- /General-JS-Problems/convert-word-to-integer-atoi.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rohan-paul/Javascript-Common-Challenges-Problems/79fe5eb3f88cf35840e836fc9ca8d9fd7063f2c4/General-JS-Problems/convert-word-to-integer-atoi.js -------------------------------------------------------------------------------- /General-JS-Problems/count-vowels.js: -------------------------------------------------------------------------------- 1 | /* Find the count of Vowels in the given string using match method and regular expression in JS 2 | */ 3 | 4 | //The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object. 5 | 6 | function countVowels(str) { 7 | const re = /(a|e|i|o|u)/g 8 | 9 | let vowelCounter = 0 10 | 11 | for (let i of str) { 12 | if (i.match(re)) { 13 | vowelCounter++ 14 | } 15 | } 16 | return vowelCounter 17 | } 18 | 19 | // console.log(countVowels("Paul")); // => 2 20 | 21 | // Alternative - 2 22 | countVowels2 = str => { 23 | let vowelCounter = str.match(/[aeiou]/gi) 24 | return vowelCounter === null 25 | ? "No vowels in the given string" 26 | : vowelCounter.length 27 | } 28 | 29 | // console.log(countVowels2("Psfsfl")); 30 | 31 | const countVowels3 = str => str.match(/[aeiou]/gi).length 32 | 33 | // console.log(countVowels3("Paul")); 34 | 35 | countVowels4 = str => { 36 | return Array.from(str).filter(vowelsInStr => "aeiou".includes(vowelsInStr)) 37 | .length 38 | } 39 | 40 | // The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate. 41 | 42 | console.log(countVowels4("Paul")) 43 | -------------------------------------------------------------------------------- /General-JS-Problems/factorial-Performance-Recursive-vs-Iterative.js: -------------------------------------------------------------------------------- 1 | function factorial_Recursive(num) { 2 | return (num === 1 ? 1 : num * factorial_Recursive(num - 1)); 3 | } 4 | 5 | 6 | function factorial_Iterative(num) { 7 | if (num < 0 ) { 8 | return 'undefined'; 9 | } 10 | var fact = 1; 11 | 12 | for (var i = num; i > 0; i--) { 13 | fact *= i; 14 | } 15 | return fact; 16 | } 17 | 18 | console.time("fact_recursive"); 19 | factorial_Recursive(1000); 20 | console.timeEnd("fact_recursive"); 21 | 22 | console.log("*******************************"); 23 | 24 | console.time("fact_Iterative"); 25 | factorial_Iterative(1000); 26 | console.timeEnd("fact_Iterative"); 27 | 28 | console.log("*******************************"); 29 | 30 | // Cool version to make factorial 31 | const factorial_cool = n => 32 | [...Array(n + 1).keys()].slice(1).reduce((x, y) => x * y); 33 | 34 | console.log(factorial_cool(4)); // => 24 35 | -------------------------------------------------------------------------------- /General-JS-Problems/fibonacci-number-GOOD-Future-Ref.js: -------------------------------------------------------------------------------- 1 | // Problem-1 - Find the n-th fibonacci number iteratively (using ES6 destructuring) - BEST LOOKING STANDARD SOLUTION WITH DESTRUCTURING 2 | n_th_fibonacci = n => { 3 | let [a, b] = [0, 1] 4 | 5 | while (--n) { 6 | ;[a, b] = [b, b + a] 7 | } 8 | return b 9 | } 10 | 11 | console.log(n_th_fibonacci(10)) // => 55 12 | 13 | /* Explanation of the above - The two numbers a and b are initialized as 1 and 0, and in every iteration of the loop (counting backwards from n to 0), b becomes the sum of the two numbers ( its current value and prrevious value of the series ) and the lower number a becomes the previous value of the higher number b. When n reaches 0, the higher of the two numbers is returned and, it resolves to the nth number in the Fibonacci sequence. 14 | 15 | Note, that the condition while (--num) is equivalent to while (num > 0) because as soon as --num becomes zero, i.e. "false" the while loop no more get executed 16 | */ 17 | 18 | /* Problem-2 - Return a full fibonacci series upto a specified positon (e.g. upto the 10th Fibonacci number in the Fibonacci series) as an array. every number after the first two is the sum of the two preceding ones 19 | So the final series will look like below (so the 10 th fibonacci is 55) 20 | 21 | position = 1 2 3 4 5 6 7 8 9 10 22 | FibNumber = 1 1 2 3 5 8 13 21 34 55 23 | 24 | GOOD STANDARD SOLUTION-Refer to this for general implementation - (following the same approach as above solution) - 25 | */ 26 | n_th_fibonacci = n => { 27 | let [a, b] = [0, 1] 28 | let fibSeries = [1] 29 | 30 | while (--n) { 31 | ;[a, b] = [b, b + a] 32 | fibSeries.push(b) 33 | } 34 | return fibSeries 35 | } 36 | 37 | console.log(n_th_fibonacci(10)) // => [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ] 38 | -------------------------------------------------------------------------------- /General-JS-Problems/fibonacci-sum-odd.js: -------------------------------------------------------------------------------- 1 | /* Problem Statement - 2 | Return the sum of all odd Fibonacci numbers up to and including the passed number if it is a Fibonacci number. 3 | 4 | The first few numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8, and each subsequent number is the sum of the previous two numbers. As an example, passing 4 to the function should return 5 because all the odd Fibonacci numbers under 4 are 1, 1, and 3.*/ 5 | 6 | addOddFibonacciNum = num => { 7 | let a = 0, b = 1, fib = 1, fibOddSum = 1; 8 | 9 | while ( a + b <= num ) { 10 | f = a + b; 11 | b = f; 12 | a = f - a; 13 | 14 | if ( f % 2 !== 0) { 15 | fibOddSum += f; 16 | } 17 | } 18 | return fibOddSum; 19 | } 20 | 21 | console.log(addOddFibonacciNum(4)); // => 5 -------------------------------------------------------------------------------- /General-JS-Problems/find_number_appearing-twice.js: -------------------------------------------------------------------------------- 1 | /* 2 | I have a list where every number in the range 1....n appears 3 | once except for one number which appears twice. 4 | Write a function for finding the number that appears twice. 5 | */ 6 | 7 | // METHOD 1: runtime = O(n) & memory = O(n) 8 | findDup = (list, n) => { 9 | let obj = {} 10 | let currentElem 11 | 12 | for (let i = 0; i < list.length; i++) { 13 | currentElem = list[i] 14 | if (obj[currentElem]) { 15 | return currentElem 16 | } else { 17 | obj[currentElem] = true 18 | } 19 | } 20 | } 21 | // so the above function will only return the fist occuring duplicate no 22 | 23 | myList = [1, 4, 2, 3, 4, 5, 6, 7, 8, 9, 10] 24 | 25 | // console.log(findDup(myList)); 26 | 27 | /* METHOD 2: runtime = O(n) & memory = O(1) 28 | Using the arithmetic sum formulae 29 | Note the Arithmetic Sum formulae is (n*(n + 1))/2 i.e. (n2 + n)/2 30 | */ 31 | 32 | findDupAlt = (list, n) => { 33 | let arithmeticSum = (n * n + n) / 2 34 | let sumList = 0 35 | for (let i of list) { 36 | sumList += i 37 | } 38 | return sumList - arithmeticSum 39 | } 40 | 41 | console.log(findDupAlt(myList, 10)) 42 | -------------------------------------------------------------------------------- /General-JS-Problems/form-largest-number-from-given-array.js: -------------------------------------------------------------------------------- 1 | /* Given an array of non negative integers,arrange them such that they form the largest number. 2 | Sample input: 3 | [3, 30, 34, 5, 9], 4 | 5 | Output number is 9534330. 6 | 7 | (Note: The result may be very large, so you can to return a string instead of an integer if that's required)* 8 | */ 9 | 10 | /* Algo - https://www.geeksforgeeks.org/given-an-array-of-numbers-arrange-the-numbers-to-form-the-biggest-number/ 11 | 12 | The idea is to use any comparison based sorting algorithm. In the used sorting algorithm, instead of using the default comparison, write a comparison function myCompare() and use it to sort numbers. 13 | 14 | Given two numbers X and Y, how should myCompare() decide which number to put first – we compare two numbers XY (Y appended at the end of X) and YX (X appended at the end of Y). If XY is larger, then X should come before Y in output, else Y should come before. For example, let X and Y be 542 and 60. To compare X and Y, we compare 54260 and 60542. Since 60542 is greater than 54260, we put Y first. 15 | */ 16 | 17 | /* To match the output of 9534330, looks like, the problem asks that we can not change a single number in the given array, that is, from the given array [3, 30, 34, 5, 9] - a 30 and 34 should remain as 30 and 34 - hence my solution below */ 18 | 19 | largestNum = arr => arr.map(String).sort((a, b) => (b+a) - (a+b)).reduce((accum, elem) => (accum + elem) ,'') 20 | 21 | console.log(largestNum([3, 30, 34, 5, 9])); // => 9534330 22 | 23 | /* Explanation of the part < sort((a, b) => (b+a) - (a+b)) > 24 | 25 | Here, I am just comparing a special combination of a, b (instead of a and b directly) - i.e. a special combination of each pair of elements in an array - before deciding how to sort them. So, like the explanation in geeksforgeeks, that I am just using a custom compare function. 26 | 27 | If XY is larger, then X should come before Y in output, else Y should come before. 28 | 29 | So, here, the sort function will take each pair of elements from the Array, and which way of placing them side-by-side is givng the larger number. e.g. for the pair 5 and 34, it will check if 534 is larger or 345 is larger. 30 | 31 | And because 534 is larger, it will place then accordingly. 32 | 33 | */ -------------------------------------------------------------------------------- /General-JS-Problems/function_chaining-call-function-inside-another-as-object-property.js: -------------------------------------------------------------------------------- 1 | /* Write a function func1 which will call another function func2 as a object property. Tat is I should be able to run func1()func2() . 2 | 3 | The purpose of this exercise is to understand how most of the function calls work in node.js. Like the below one 4 | 5 | var http = require('http'); 6 | http.createServer(function (req, res) { 7 | res.writeHead(200, {'Content-Type' : 'text/plain'}); 8 | res.write('Hello World'); 9 | res.end(); 10 | }).listen(3000); 11 | 12 | 13 | And in the above, what exactly is happening is - 14 | 15 | http.createServer().listen(); 16 | 17 | Where http is an object, and I am chaining createServer() and listen() to that 18 | 19 | */ 20 | 21 | function func1() { 22 | return { 23 | func2: () => { 24 | console.log("Inside func2"); 25 | return { 26 | func3: () => { 27 | console.log("Inside func3"); 28 | } 29 | } 30 | } 31 | } 32 | } 33 | 34 | func1().func2().func3(); -------------------------------------------------------------------------------- /General-JS-Problems/greatest_common_divisor.js: -------------------------------------------------------------------------------- 1 | // Find the greatest common divisor of two numbers 2 | function greatestCommonDivisor(a, b) { 3 | var divisor = 2, 4 | greatestDivisor; 5 | 6 | if ( a < 2 || b < 2) 7 | return 1; 8 | 9 | while (a >= divisor && b >= divisor) { 10 | if( a % divisor == 0 && b % divisor == 0) { 11 | greatestDivisor = divisor; 12 | } 13 | divisor++; 14 | } 15 | return greatestDivisor; 16 | } 17 | 18 | console.log(greatestCommonDivisor(14, 21)); -------------------------------------------------------------------------------- /General-JS-Problems/ifPowerOfFour.js: -------------------------------------------------------------------------------- 1 | // Check if a number is any power of 4. Its the same logic as checking if a number is power of 2. See my file small-snippets.js 2 | /* Notes - Keep dividing the number by 4, i.e, do n = n/4 iteratively until n becomes 1. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 4. Otherwise is a power of 2. */ 3 | var isPowerOfFour = function (num) { 4 | while ( num != 1) { 5 | num = (num / 4); 6 | 7 | if ( num % 4 != 0 && num != 1) { 8 | return false; 9 | } 10 | }; 11 | return true; 12 | }; 13 | 14 | // We are checking with num != 1 because 1 can be the result of any number raised to power of 0 15 | console.log(isPowerOfFour(18)); 16 | 17 | // Check if the a number (1st argument) is a power of another number (the second argument) 18 | var isPower = function (num, n) { 19 | while ( num != 1) { 20 | num = (num / n); 21 | 22 | if ( num % n != 0 && num != 1) { 23 | return false; 24 | } 25 | }; 26 | return true; 27 | }; 28 | 29 | // We are checking with num != 1 because 1 can be the result of any number raised to power of 0 30 | console.log(isPower(16, 2)); -------------------------------------------------------------------------------- /General-JS-Problems/integer_length.js: -------------------------------------------------------------------------------- 1 | /* Write a function that takes an integer as input and returns the number of digits in that integer.*/ 2 | 3 | function integerLength(num) { 4 | return ('' + (num | 0)).length; 5 | } 6 | 7 | console.log(integerLength()); -------------------------------------------------------------------------------- /General-JS-Problems/isNumeric.js: -------------------------------------------------------------------------------- 1 | /* Write a JavaScript function to check whether a variable is numeric or not. 2 | 3 | Test Data: 4 | console.log(is_Numeric(12)); 5 | console.log(is_Numeric('abcd')); 6 | console.log(is_Numeric('12')); 7 | console.log(is_Numeric(' ')); 8 | console.log(is_Numeric(1.20)); 9 | console.log(is_Numeric(-200)); 10 | 11 | Output: 12 | true 13 | false 14 | true 15 | false 16 | true 17 | true */ 18 | 19 | is_Numeric = (num) => { 20 | return !isNaN(parseFloat(num)) && isFinite(num); 21 | } 22 | 23 | console.log(is_Numeric(12)); 24 | console.log(is_Numeric('abcd')); 25 | console.log(is_Numeric('12')); 26 | console.log(is_Numeric(' ')); 27 | console.log(is_Numeric(1.20)); 28 | console.log(is_Numeric(-200)); -------------------------------------------------------------------------------- /General-JS-Problems/isPalindrome.js: -------------------------------------------------------------------------------- 1 | // Implement a isPalindrome function with class constructor 2 | function Palindrome(str) { 3 | this.str = str 4 | } 5 | 6 | Palindrome.prototype.isPalindrome = function(str) { 7 | this.str = str 8 | 9 | let cleanStr = str.toLowerCase().replace(/[^a-zA-Z0-9]/gi, "") 10 | 11 | let len = cleanStr.length 12 | 13 | for (let i = 0; i < len / 2; i++) { 14 | if (cleanStr[i] !== cleanStr[len - 1 - i]) { 15 | return false 16 | } 17 | } 18 | return true 19 | } 20 | 21 | console.log(Palindrome.prototype.isPalindrome("eye")) 22 | 23 | console.log("eye".Palindrome.prototype.isPalindrome()) 24 | -------------------------------------------------------------------------------- /General-JS-Problems/isUgly.js: -------------------------------------------------------------------------------- 1 | /*https://www.geeksforgeeks.org/ugly-numbers/ 2 | 3 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 4 | Note that 1 is typically treated as an ugly number. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention, 1 is considered to be ugly number. 5 | */ 6 | 7 | /* Solution Algo - To check if a number is ugly, divide the number by greatest divisible powers of 2, 3 and 5, if the number becomes 1 then it is an ugly number otherwise not. 8 | 9 | Let's take an example : N=9000 (We want to check this number is ugly or not) , but for that we have to check it by dividing N by the Greatest Divisible Power of prime ( 2,3 or 5) : 10 | N=9000 = 2^3 * 3^2 * 5^3 11 | So, GDP of 2 becomes - 2^3 = 8 12 | GDP of 3 becomes - 3^2 = 9 13 | GDP of 5 becomes - 5^3=125 14 | 15 | 16 | */ 17 | 18 | isUgly = (num) => { 19 | 20 | if (num < 0) return false; 21 | if (num === 1) return true; 22 | 23 | while (num % 2 === 0 ) { num /= 2} 24 | while (num % 3 === 0 ) { num /= 3} 25 | while (num % 5 === 0 ) { num /= 5} 26 | 27 | return num === 1; 28 | } 29 | 30 | 31 | 32 | console.log(isUgly(9000)); -------------------------------------------------------------------------------- /General-JS-Problems/largest-Numbe-in-Array.js: -------------------------------------------------------------------------------- 1 | // Problem statement - Find Second largest element in an array 2 | function largest (arr) { 3 | return arr.reduce((a, b) => { 4 | return a > b ? a : b; 5 | }); 6 | } 7 | 8 | function largest2 (arr) { 9 | return arr.reduce((a, b) => { 10 | return Math.max(a, b); 11 | }) 12 | } 13 | 14 | // Finding max and min value from first priciple. Much faster than Math.max.apply. 15 | function largest3 (arr) { 16 | let max = 0; 17 | 18 | for (i= 0; i < arr.length; i++) { 19 | if (arr[i] > max) { 20 | max = arr[i]; 21 | } 22 | } 23 | return max; 24 | } 25 | 26 | 27 | // Using for..of syntax of ES6 28 | function largest4(arr) { 29 | let max = 0; 30 | for (let variable of arr) { 31 | if (variable > max) { 32 | max = variable; 33 | } 34 | } 35 | return max; 36 | } 37 | 38 | // Using spread operaton 39 | function largest5 (arr) { 40 | return Math.max(...arr); 41 | } 42 | 43 | console.log(largest4([1, 4, 3, 2])); -------------------------------------------------------------------------------- /General-JS-Problems/largest_product_yielded_ from_three_ integers.js: -------------------------------------------------------------------------------- 1 | /* Given an array of integers, find the largest product yielded from three of the integers */ 2 | 3 | -------------------------------------------------------------------------------- /General-JS-Problems/max-min-from-array-of-objects.js: -------------------------------------------------------------------------------- 1 | /*Finding Minimum and Maximum values in an Array of Objects 2 | 3 | We have an array of objects like below in the variable called data 4 | 5 | [ 6 | {x: 1, y: 14830}, 7 | {x: 2, y: 85055}, 8 | {x: 3, y: 03485}, 9 | {x: 4, y: 57885}, 10 | // ... 11 | ] 12 | 13 | Build two function calls — one for the minimum Y value, and one for the maximum Y value. 14 | 15 | */ 16 | 17 | // first create the variable data which is an array of objects with random set of 1000 records 18 | 19 | const data = []; 20 | for (let x = 0; x < 1000; x++) { 21 | data.push({ x: x, y: Math.floor(Math.random() * 1000) }); 22 | } 23 | // console.log(data); 24 | 25 | // Note in the below function the accumulator is the the variable minY and the first value of this is set to be data[0].y 26 | 27 | function getMinYValue () { 28 | return data.reduce((minY, thisObj) => thisObj.y < minY ? thisObj.y : minY, data[0].y) 29 | } 30 | 31 | function getMaxYValue() { 32 | return data.reduce((maxY, thisObj) => thisObj.y > maxY ? thisObj.y : maxY, data[0].y); 33 | } 34 | 35 | // Using Map and spread operaton. First get all the y values from each of the objects within data. 36 | 37 | function getYOnly () { 38 | return data.map( YVal => YVal.y ); 39 | } 40 | 41 | 42 | function getMinValueAlt () { 43 | return Math.min(...getYOnly()); 44 | } 45 | 46 | function getMaxValueAlt () { 47 | return Math.max(...getYOnly()); 48 | } 49 | 50 | console.log(getMaxValueAlt()); 51 | 52 | console.log(getMinValueAlt()); -------------------------------------------------------------------------------- /General-JS-Problems/max-product-three-elements.js: -------------------------------------------------------------------------------- 1 | // Given an array of integers, find the largest product yielded from three of the integers 2 | 3 | /* Algo - 4 | 5 | Sort the given array in ascending order and you have to take the maximum of these cases to get the answer.. 6 | 7 | Product of last 3 numbers in sorted array 8 | Product of first two and last number in the sorted array 9 | 10 | */ 11 | 12 | maxProductOfThreeeElem = (arr) => { 13 | 14 | let sortedArr = arr.sort((a, b) => a - b); 15 | 16 | // Greatest product is either (min1 * min2 * max1 || max1 * max2 * max3) 17 | 18 | let product1 = 1, product2 = 1, len = arr.length - 1; 19 | 20 | product1 = sortedArr[0] * sortedArr[1] * sortedArr[len]; 21 | 22 | for (let i = len; i > len - 3; i-- ) { 23 | product2 *= sortedArr[i]; 24 | } 25 | 26 | return Math.max(product1, product2) 27 | } 28 | 29 | console.log(maxProductOfThreeeElem([1,2,3,4])); // => 12 30 | console.log(maxProductOfThreeeElem([-4,2,3,1])); // => 12 31 | console.log(maxProductOfThreeeElem([-4,-2,-3,1])); // => 12 -------------------------------------------------------------------------------- /General-JS-Problems/median-of-Array.js: -------------------------------------------------------------------------------- 1 | /* Calculate the median of an array with javascript . faced this in Techolution Interview on 21-June-2018. Below was my solution at Techolution and it was indeed correct 2 | 3 | example; input = [1,2,3,4,5] 4 | output = 3 5 | 6 | input = [4,5,6,1,2,3] 7 | output = 3.5 */ 8 | 9 | median = arr => { 10 | 11 | let sortedArr = arr.sort((a, b) => a - b); 12 | 13 | let len = sortedArr.length; 14 | 15 | if (sortedArr.length % 2 !== 0) { 16 | let index1 = Math.floor(len / 2) 17 | return sortedArr[index1]; 18 | } else { 19 | let index2 = len / 2; 20 | return (((sortedArr[index2] + sortedArr[index2 - 1]) / 2).toFixed(1)); 21 | } 22 | } 23 | 24 | var input1 = [1,2,3,4,5]; 25 | var input2 = [4,5,6,1,2,3]; 26 | 27 | console.log(median(input1)); 28 | 29 | console.log(median(input2)); 30 | 31 | /* https://www.geeksforgeeks.org/median-of-stream-of-running-integers-using-stl/ 32 | Median can be defined as the element in the data set which separates the higher half of the data sample from the lower half. In other words we can get the median element as, when the input size is odd, we take the middle element of sorted data. If the input size is even, we pick average of middle two elements in sorted stream. */ -------------------------------------------------------------------------------- /General-JS-Problems/merge_two_sorted_array.js: -------------------------------------------------------------------------------- 1 | // merge two sorted array into a single sorted array 2 | 3 | /*Solution steps 4 | 5 | */ 6 | /*function mergeSortedArray(a, b) { 7 | for (var i = 0; i < b.length; i++) { 8 | a.push(b[i]); 9 | } 10 | for (i = 0; i < a.length; i++) { 11 | for(var j = i+1; j < a.length; j++ ) 12 | { 13 | if(a[i] > a[j]) { 14 | var temp = a[i]; 15 | a[i] = a[j]; 16 | a[j] = temp; 17 | } 18 | } 19 | 20 | } 21 | return a; 22 | }*/ 23 | 24 | function mergeSortedArray(a, b) { 25 | var sorted = [], 26 | indexA = 0, 27 | indexB = 0; 28 | 29 | while (indexA < a.length && indexB < b.length) { 30 | if (sortFn(a[indexA], b[indexB]) > 0) { 31 | sorted.push(b[indexB++]); 32 | } else { 33 | sorted.push(a[indexA++]) 34 | } 35 | } 36 | 37 | /* A> Now the above while loop will stop its execution, as soon as one of the array's all elements have been pushed to the new array ( i.e. sorted ). Leaving the case if the other condition of the while loop still is valid (e.g. indexB is still < b.length ). 38 | 39 | B> This will be the case for that array which will have the highest numerical value. 40 | 41 | C> So, to include that terminal case into the final sorted array, I have to check this same condition again after the while loop complete its runs. 42 | 43 | D) And concat that particular array's rest of the values sliced from that index till the end of values. 44 | */ 45 | 46 | if (indexB < b.length) { 47 | sorted = sorted.concat(b.slice(indexB)); 48 | } else { 49 | sorted = sorted.concat(a.slice(indexA)); 50 | } 51 | 52 | return sorted; 53 | 54 | } 55 | 56 | 57 | function sortFn(a, b) { 58 | return a - b; 59 | } 60 | 61 | 62 | 63 | console.log(mergeSortedArray([1, 2, 3, 5, 8], [4, 6, 7, 9])); -------------------------------------------------------------------------------- /General-JS-Problems/missing-number.js: -------------------------------------------------------------------------------- 1 | /* Question: from a unsorted array of numbers 1 to 100 excluding one number, how will you find that number. 2 | 3 | Explanation: You have an array of numbers 1 to 100 in an array. Only one number is missing in the array. The array is unsorted. Find the missing number. */ 4 | 5 | /* sum of a linear series of n numbers = n*(n+1)/2 */ 6 | 7 | function missingNumber(arr) { 8 | let sum = 0; 9 | let n = arr.length + 1; // Am adding 1, because in the given array one number is supposed to be missimg 10 | let expectedSum = (n * (n + 1)/2); 11 | 12 | for ( let i = 0; i < arr.length; i++) { 13 | sum += arr[i]; 14 | } 15 | return expectedSum -sum ; 16 | } 17 | 18 | console.log( missingNumber([5, 2, 6, 1, 3])); -------------------------------------------------------------------------------- /General-JS-Problems/multi-diamensional-array.js: -------------------------------------------------------------------------------- 1 | // Problem Statement - The first dimension represents the activity and the second one shows the number of hours spent per day for each. 2 | // calculates the percentage of the hours spent for each activity and append the percentage to the inner array. 3 | 4 | var activities = [ 5 | ['Work', 9], 6 | ['Eat', 2], 7 | ['Commute', 2], 8 | ['Play Game', 2], 9 | ['Sleep', 7] 10 | ]; 11 | 12 | for (let i = 0; i < activities.length; i++) { 13 | let percentage = ((activities[i][1] / 24) * 100).toFixed(); 14 | activities[i][2] = percentage + "%"; 15 | } 16 | 17 | console.log(activities); -------------------------------------------------------------------------------- /General-JS-Problems/narcissistic _number.js: -------------------------------------------------------------------------------- 1 | // Problem STATEMENT - Check if a given number narcissistic number 2 | /* Narcissistic number 3 | Given N, check whether it is a Narcissistic number or not. 4 | 5 | Note:Narcissistic Number is a number that is the sum of its own digits each raised to the power of the number of digits 6 | 7 | https://www.geeksforgeeks.org/narcissistic-number/ 8 | 9 | */ 10 | 11 | isNarcissistic = num => { 12 | 13 | //convert the original number to string. I can do this in the below way, or using toString() 14 | // let numStr = '' + num; 15 | 16 | let numStr = num.toString(); 17 | 18 | let numLen = numStr.length; 19 | 20 | let narcissisticResult = 0 21 | 22 | for (let i in numStr ) { 23 | narcissisticResult += Math.pow( parseInt(numStr[i]), numLen); 24 | } 25 | 26 | return num === narcissisticResult; 27 | } 28 | 29 | // console.log(isNarcissistic(153)); 30 | 31 | // 153 is Nacrissistic number - (3 digits), you can see 153 = 1^3 + 5^3 + 3^3 32 | 33 | // Alternate Solution 34 | isNarcissistic1 = num => { 35 | return num === (num.toString().split('').reduce((narcissisticResult, currentNum) => { 36 | return narcissisticResult + Math.pow(parseInt(currentNum), num.toString().length) 37 | }, 0)) 38 | } 39 | 40 | console.log(isNarcissistic1(153)); -------------------------------------------------------------------------------- /General-JS-Problems/nested-arrays-1.js: -------------------------------------------------------------------------------- 1 | // Problem-1 - Given the below nested arrays, how would we get the letter 'e'? 2 | 3 | const letters = ['a', ['b', ['c', ['d', ['e']], 'f']]]; 4 | 5 | // First, looking at the array, I can see the array ['e'] is at the 4-th level of nested arrays. 6 | // First, we'd need the second element in letters, letters[1]: 7 | console.log(letters[1]); // => [ 'b', [ 'c', [ 'd', [Array] ], 'f' ] ] 8 | 9 | 10 | // Then the second element of that resultant element 11 | console.log(letters[1][1]); // => [ 'c', [ 'd', [ 'e' ] ], 'f' ] 12 | 13 | // Going in this way I need to accessthe second element succesively of 2 more levels of nested arrays. 14 | 15 | console.log(letters[1][1][1][1]); // => [ 'e' ] 16 | 17 | 18 | -------------------------------------------------------------------------------- /General-JS-Problems/nested-arrays-function-chaining2.js: -------------------------------------------------------------------------------- 1 | // Problem statement - return only cities with population of more than 500000. And the returned city names should be sorted by their population number from lowest to hieghest 2 | // Hint - use function chaining 3 | 4 | var data = [ 5 | {"city":"seattle", "state":"WA", "population":652405, "land_area":83.9}, 6 | {"city":"new york", "state":"NY", "population":8405837, "land_area":302.6}, 7 | {"city":"boston", "state":"MA", "population":645966, "land_area":48.3}, 8 | {"city":"kansas city", "state":"MO", "population":467007, "land_area":315} 9 | ]; 10 | 11 | let bigCities = data.filter((item) => item.population > 500000) 12 | .sort((a, b) => a - b) 13 | .map((item) => item.city) 14 | 15 | console.log(bigCities); -------------------------------------------------------------------------------- /General-JS-Problems/non-repeating-char-in-a-string.js: -------------------------------------------------------------------------------- 1 | /*Find the first non repeating char in a string?*/ 2 | 3 | /*Solution - for each item in the array traverse all the other items of the array. So the */ 4 | 5 | function findFirstNonRepeatedChar(str) { 6 | 7 | let charCounter = 0; 8 | let resultChar = ''; 9 | 10 | str = str.split(''); 11 | 12 | for (let i = 0; i < str.length; i++) { 13 | charCounter = 0; 14 | 15 | for (let j = 0; j < str.length; j++) { 16 | if (str[i] === str[j]) { 17 | charCounter += 1; 18 | } 19 | } 20 | 21 | if (charCounter < 2) { 22 | resultChar = str[i]; 23 | break; 24 | } 25 | } 26 | return resultChar; 27 | } 28 | 29 | console.log(findFirstNonRepeatedChar("aaabbcdd")); -------------------------------------------------------------------------------- /General-JS-Problems/pangram.js: -------------------------------------------------------------------------------- 1 | /*Pangrams are sentences constructed by using every letter of the alphabet at least once. Construct a function to check if a string is a Panagram. 2 | 3 | Input Format: Input consists of a string ss. 4 | Length of ss can be at most 103103 (1≤|s|≤103)(1≤|s|≤103) and it may contain spaces, 5 | lower case and upper case letters. Lower-case and upper-case instances of a letter are considered the same. 6 | 7 | Output: Output a line containing pangram if ss is a pangram, otherwise output not pangram. 8 | */ 9 | 10 | /*Solutio Algo - 11 | 12 | A) Build a hash-map where each alphabets (A to Z i.e. from charCode 65 to charCode 90) are key and their value is set to false. 13 | 14 | B> Then from the given sting in the argument, push each of its alphabets to the Hash as the key and set its value to true. If the given string is a panagram, then after this operation the Hash should have all its key's value to be set to true. 15 | 16 | C> Then iterate throught the Hash's key, and if I find any key's value to be false, then return false. 17 | 18 | */ 19 | 20 | isPangram = (str) => { 21 | 22 | let alphabets = {}; 23 | 24 | str = str.replace(/ /g, '').toLowerCase(); 25 | 26 | 27 | for (let i = 65; i <= 90; i++ ) { 28 | 29 | alphabets[String.fromCharCode(i)] = false; 30 | } 31 | 32 | if (str.length < 26) { 33 | return false 34 | } else { 35 | for (let j = 0; j < str.length; j++) { 36 | alphabets[str[j]] = true; 37 | } 38 | } 39 | 40 | return true; 41 | } 42 | 43 | console.log(isPangram("The quick brown fox jumps over the lazy dog")); // should return true -------------------------------------------------------------------------------- /General-JS-Problems/permutation_array_of_numbers-Heap-Algo.js: -------------------------------------------------------------------------------- 1 | // Implementation of the pseudo-code from - https://en.wikipedia.org/wiki/Heap's_algorithm 2 | 3 | let swap = function (array, index1, index2) { 4 | let temp = array[index1]; 5 | array[index1] = array[index2]; 6 | array[index2] = temp; 7 | return array; 8 | }; 9 | 10 | function permutationHeap (array, result, n) { 11 | n = n || array.length; // set n default to array.length 12 | if ( n === 1) { 13 | result(array); // Print out the array 14 | } else { 15 | for (var i = 1; i <= n; i++ ) { 16 | permutationHeap(array, result, n-1) ; 17 | 18 | // Now with the below strategy of swapping, Heap-Algo keeps track of which elements we had already removed? Then we could just swap out unremoved elements, so that it is different in each case. 19 | if (n % 2) { 20 | swap(array, i - 1, n - 1); // when length is odd ( n % 2 is 1), select the first number, then the second number, then the third number. . . to be swapped with the last number 21 | } else { 22 | swap(array, 0, n - 1); // when length is even (n % 2 is 0), always select the first number to be swapped with the last number 23 | } 24 | } 25 | } 26 | } 27 | 28 | function output(input) { 29 | console.log(input); 30 | } 31 | 32 | permutationHeap(['a', 'b', 'c'], output); 33 | 34 | /* Time Complexity - runs in factorial time O(n!) */ 35 | 36 | /* 37 | For Explanataion on the code check my blog - https://rohan-paul.github.io/javascript/2018/04/26/Implemetning-Heap-Algorithm-to-Find-Permutation-of-set-of-Numbers/ 38 | */ 39 | -------------------------------------------------------------------------------- /General-JS-Problems/pipeFunction.js: -------------------------------------------------------------------------------- 1 | /*A pipe function takes an n sequence of functions or operations ; in which each operation takes an argument; process it; and gives the processed output as an input for the next operation in the sequence. The result of a pipe function is a function that is a bundled up version of the sequence of operations. 2 | 3 | Lets implement a pipe function to performs left-to-right function composition. 4 | 5 | Use Array.reduce() with the spread operator (...) to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. 6 | */ 7 | 8 | const pipeFunction = (...funcs) => 9 | funcs.reduce((x, y) => (...args) => y(x(...args))) 10 | 11 | // Example implementation 12 | const add5 = x => x + 5 13 | const multiply = (x, y) => x * y 14 | const multiplyAndAdd5 = pipeFunction(multiply, add5) 15 | console.log(multiplyAndAdd5(5, 2)) // 15 because ((5 * 2) + 5) 16 | -------------------------------------------------------------------------------- /General-JS-Problems/print-Triangle-Staircase-1.js: -------------------------------------------------------------------------------- 1 | /*Print the following pattern 2 | Input Variable : Number of rows 3 | # 4 | # # 5 | # # # 6 | # # # # 7 | # # # # # 8 | # # # # # # 9 | # # # # # # # 10 | 11 | PROBLEM STATEMENT SPECIAL REQUIREMENT - Observe that its base and height are both equal to N ( i.e. the argument to the function, which is equal to the number of rows) 12 | 13 | */ 14 | 15 | function printTriangle(rows) { 16 | let char = '' 17 | 18 | for (let i = 1; i <= rows; i++) { 19 | for ( let j = 1; j <= i; j++) { 20 | char = char + " # "; 21 | } 22 | console.log((char)); 23 | 24 | char = ''; // Reset the char after printing 25 | } 26 | } 27 | 28 | printTriangle(7); 29 | 30 | /*Explanation 31 | A) The target is to print # on line-1 >> then print # # in line line 2 and so on. 32 | 33 | B) So when i = 1, I will print # >> when i == 2, I will print # # and so on 34 | 35 | C) So for each value of i, do another inner loop and build up the 'char' variable with i-number of # 36 | 37 | D) Then when inner loop is done, print the char variable. 38 | 39 | E) After printing, reset char, so for the next line it can print again. 40 | 41 | */ 42 | 43 | function printTriangle_alt(rows) { 44 | for (let row = 1; row <= rows; row++) { 45 | console.log("#".repeat(row)); 46 | } 47 | } 48 | 49 | // printTriangle_alt(5); -------------------------------------------------------------------------------- /General-JS-Problems/print-Triangle-Staircase-2.js: -------------------------------------------------------------------------------- 1 | /*Print the following pattern 2 | Input Variable : Number of rows 3 | # 4 | # # 5 | # # # 6 | # # # # 7 | # # # # # 8 | # # # # # # 9 | # # # # # # # 10 | */ 11 | 12 | /* Just modifying the the code for printPyramid's - by A) Not printing anything for col1 (the second for loop ) because here there's not need for "PADDING" before the * and B) making col2's max iteration value to ( 2 * row) - This second one I did just experimentally. Without it the row was printing 2 stars instead one. 13 | 14 | Observe that its base and height are both equal to number or totalRows (given as an argument to the function) 15 | */ 16 | 17 | printTriangleStaircase = totalRows => { 18 | 19 | for (let row = 0; row < totalRows; row++ ) { 20 | 21 | let line = '' 22 | 23 | for ( let col1 = 0; col1 < totalRows - row; col1++) { 24 | 25 | line = line + '' 26 | 27 | } 28 | 29 | for (let col2 = 0; col2 <= row; col2++ ) { 30 | 31 | line = line + "*" 32 | } 33 | 34 | console.log(line); 35 | } 36 | } 37 | 38 | printTriangleStaircase(5) -------------------------------------------------------------------------------- /General-JS-Problems/print-Triangle-Staircase-REVERSE-2.js: -------------------------------------------------------------------------------- 1 | /* 2 | ********* 3 | ******* 4 | ***** 5 | *** 6 | * 7 | 8 | But in my solution below, the problem statement does not contain any requirement to the no of stars to the number of rows. 9 | 10 | Same approach as reversing the Pyramid, only here, for col1, I am not adding any extra space at all, as I dont need to have the padding on the left. 11 | 12 | And for col2's max iteration value, I am just making it to (( 2 * row) - 1) - and this is out of experimentation , as without deducting the 1 , I was not getting a single start for the last row. 13 | */ 14 | 15 | printTriangleStaircaseReverse = totalRows => { 16 | 17 | for (let row = totalRows; row > 0; row-- ) { 18 | 19 | let line = '' 20 | 21 | for ( let col1 = totalRows; col1 >= row; col1--) { 22 | 23 | line = line + '' 24 | 25 | } 26 | 27 | for (let col2 = (( 2 * row) - 1); col2 > 0; col2-- ) { 28 | 29 | line = line + "*" 30 | } 31 | 32 | console.log(line); 33 | } 34 | } 35 | 36 | printTriangleStaircaseReverse(5) -------------------------------------------------------------------------------- /General-JS-Problems/print-right-aligned-triangel-staircase-problem-HR.js: -------------------------------------------------------------------------------- 1 | /* https://www.hackerrank.com/challenges/staircase/problem 2 | 3 | Consider a staircase of size n = 4 : 4 | 5 | # 6 | ## 7 | ### 8 | #### 9 | 10 | Observe that its base and height are both equal to n , and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces. 11 | 12 | Write a program that prints a staircase of size . 13 | 14 | Print a staircase of size n using # symbols and spaces. 15 | 16 | Note: The last line must have 0 spaces in it. */ 17 | 18 | staircase = totalRows => { 19 | 20 | for (let row = 0; row < totalRows; row++) { 21 | 22 | let line = ''; 23 | 24 | for ( let col1 = 0; col1 < totalRows - (row + 1); col1++ ) { 25 | 26 | line += ' ' 27 | } 28 | 29 | for (let col2 = 0; col2 <= row; col2++) { 30 | line += '#' 31 | } 32 | console.log(line); 33 | } 34 | } 35 | 36 | staircase(6) 37 | 38 | // In the col1 loop, I had to do (row + 1) because, to decrease the number of empty space printed in each line, so the last line (the base of triangle) would not contain any spaces and ONLY # (which was the requirement of the original problem) -------------------------------------------------------------------------------- /General-JS-Problems/print-side-by-side-bow-shape-triangle.js: -------------------------------------------------------------------------------- 1 | /* - Print the following shape, where the maximum number of stars in the middle postition is maxNum 2 | 3 | * 4 | ** 5 | *** 6 | **** 7 | ***** 8 | ****** 9 | ******* 10 | ******** 11 | ********* 12 | ********** 13 | ********* 14 | ******** 15 | ******* 16 | ****** 17 | ***** 18 | **** 19 | *** 20 | ** 21 | * 22 | 23 | Side by triangel bow shaped 24 | */ 25 | 26 | bowShapedTriangle = maxNum => { 27 | 28 | let triangle_1 = ''; 29 | 30 | // First build the triangle upto maxNum of rows with maxNum of * 31 | for (let i = 0; i < maxNum; i++) { 32 | triangle_1 += '*' 33 | console.log(triangle_1); 34 | } 35 | 36 | // Then just reduce the trianlge starting from next line and and counting from maxNum - 1. As after the 10 '*' the next line should print 9 '*' 37 | for (let i = maxNum - 1; i >= 1 ; i-- ) { 38 | triangle_1 = triangle_1.slice(0, -1); 39 | console.log(triangle_1); 40 | } 41 | } 42 | 43 | bowShapedTriangle(10) 44 | 45 | // String.slice method - The slice() method extracts a section of a string and returns it as a new string, without modifying the original string. 46 | 47 | // str.slice(beginIndex[, endIndex]) 48 | 49 | // If the endIndes is negative, it is treated as strLength + endIndex where strLength is the length of the string (for example, if endIndex is -3 it is treated as strLength - 3). -------------------------------------------------------------------------------- /General-JS-Problems/pure-impure-func-with-slice-and-splice.js: -------------------------------------------------------------------------------- 1 | /* An Impure Function - The splice() method changes the contents of an array by removing existing elements and/or adding new elements. 2 | 3 | syntaqx >>>> array.splice(start[, deleteCount[, item1[, item2[, ...]]]]) 4 | 5 | item1, item2, ... Optional - The elements to add to the array, beginning at the start index. 6 | 7 | Return value - An array containing the deleted elements. 8 | */ 9 | 10 | let arr = [1, 2, 3, 4, 5]; 11 | 12 | console.log(arr.splice(0, 3)); //=> [1, 2, 3] 13 | 14 | console.log(arr.splice(0, 3)); //=> [4, 5] 15 | 16 | console.log(arr.splice(0, 3)); //=> [] 17 | 18 | console.log(arr); //=> [] 19 | 20 | 21 | /* A Pure Function - The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). 22 | 23 | 24 | 25 | 26 | */ 27 | 28 | let arr1 = [1, 2, 3, 4, 5]; 29 | 30 | console.log(arr1.slice(0, 3)); //=> [1, 2, 3] 31 | 32 | console.log(arr1.slice(0, 3)); //=> [1, 2, 3] 33 | 34 | console.log(arr1.slice(0, 3)); //=> [1, 2, 3] 35 | 36 | console.log(arr1); //=> [ 1, 2, 3, 4, 5 ] 37 | 38 | 39 | 40 | /* Slice and Splice do the same thing to the array but in a different way, slice returns a new array according to the input, guaranteeing the same output per input every time. Splice on the other hand modifies the original array and the same output per input is not guaranteed. */ 41 | 42 | // Look at this, how splice() returns the deleted elements of the array, leaving the original array mutated. 43 | let myArr1 = [ 2, 1, 3, 4] 44 | 45 | console.log(myArr1.splice(1, 1)); // => [ 1 ] 46 | 47 | console.log(myArr1); // => [ 2, 3, 4 ] -------------------------------------------------------------------------------- /General-JS-Problems/random-code-1.js: -------------------------------------------------------------------------------- 1 | n_th_fibonacci = n => { 2 | let [a, b] = [0, 1]; 3 | 4 | while (--n) { 5 | [a, b] = [b, b + a ] 6 | } 7 | return b; 8 | } 9 | 10 | console.log(n_th_fibonacci(10000)) // => 55 -------------------------------------------------------------------------------- /General-JS-Problems/remove-duplicate-from-Array-O(n).js: -------------------------------------------------------------------------------- 1 | // uniq - Takes an array of numbers, and returns the unique numbers. Can you do it in O(N) time? 2 | 3 | /* Solution Algo - 4 | 5 | Keeping track of already seen numbers in an object, because checking if an object has a certain key 6 | is cheap (it takes O(1) time). 7 | 8 | But if I didn't use this object, I'd have to check if result contains current on every turn of the 9 | loop, with something like below. 10 | 11 | < if (result.indexOf(currentElem) < 0) result.push(currentElem); > 12 | 13 | This would take up to O(N * log(N)) time. 14 | 15 | */ 16 | 17 | returnUnique = arr => { 18 | let seenObj = {} 19 | 20 | return arr.reduce((finalArr, currentElem) => { 21 | if (currentElem in seenObj) { 22 | return finalArr 23 | } else { 24 | seenObj[currentElem] = true 25 | console.log(seenObj) 26 | return finalArr.concat(currentElem) 27 | } 28 | }, []) 29 | } 30 | 31 | console.log(returnUnique([1, 4, 2, 2, 3, 4, 8])) 32 | 33 | /* In the last line, finalArr.concat(currentElem), I can NOT use finalArr.push() because of the following - (will get error - "array.push not a function" ) 34 | 35 | https://stackoverflow.com/questions/45742030/push-method-not-available-in-reduce-array-accumulator?rq=1 36 | 37 | "This is because Array.prototype.push() returns the new length of the array, not the array itself. Your code will run through one iteration of your reducer, set the accumulative value to an integer, and then fail on the next iteration." 38 | 39 | 40 | Further Reading 41 | 42 | 1. https://stackoverflow.com/a/53526999/1902852 43 | 44 | */ 45 | 46 | // ******************************************** 47 | 48 | // Another even more simpler Implementation of above with O(n) performance 49 | 50 | const getUnique = (array) => { 51 | 52 | // below variable will keep track of already seen numbers in an object, 53 | // because checking if an object has a certain key is cheap (it takes O(1) time). 54 | let objWithOnlyUniqueArrayElements = {} 55 | 56 | return array.filter((elem) => !(objWithOnlyUniqueArrayElements[elem] = elem in objWithOnlyUniqueArrayElements)) 57 | } 58 | 59 | const a1 = [5, 6, 0, 4, 9, 2, 3, 5, 0, 3, 4, 1, 5, 4, 9] 60 | console.log(getUnique(a1)) 61 | 62 | /* 63 | [ 64 | 5, 6, 0, 4, 65 | 9, 2, 3, 1 66 | ] 67 | 68 | Explanation - 69 | */ 70 | 71 | -------------------------------------------------------------------------------- /General-JS-Problems/remove-duplicate-from-string.js: -------------------------------------------------------------------------------- 1 | // Removing duplicate characters from a string. 2 | 3 | removeDupCharFromStr = (str) => { 4 | 5 | let result = []; 6 | 7 | for (let i = 0; i < str.length; i++) { 8 | if ((result.indexOf(str[i])) === -1 ) { 9 | result.push(str[i]) 10 | } 11 | } 12 | return result.join(''); 13 | } 14 | 15 | // console.log(removeDupCharFromStr("Rohaaan")); 16 | 17 | // More compact solution to remove duplicated char from str with ES6 Set 18 | removeDupWordsFromStr_1 = (str) => { 19 | return [...new Set([...str])].join(''); 20 | } 21 | 22 | console.log(removeDupWordsFromStr_1("Rohaaan")); 23 | 24 | 25 | // Remove duplicate words from string separated by a comma and a space and return the string containing only unique words - the below solution will NOT remove duplicate characters from a string, its only for words. 26 | 27 | removeDupWordsFromStrAlt = (str) => { 28 | return str.split(',').filter((item, index, array) => { 29 | return index === array.indexOf(item); 30 | }).join(','); 31 | } 32 | 33 | // console.log(removeDupWordsFromStrAlt("spanner, span, spaniel, span")); // => spanner, span, spaniel 34 | // console.log(removeDupWordsFromStrAlt("Rohaaaaan")); // => Rohaaaaan 35 | 36 | // remove duplicates from string with the new Set method of ES6 37 | 38 | removeDupWordsFromStr = (str) => { 39 | return Array.from(new Set(str.split(','))).toString(); 40 | } 41 | 42 | // console.log(removeDupWordsFromStr("spanner, span, spaniel, span")); -------------------------------------------------------------------------------- /General-JS-Problems/repeatedly-add-digits-till-sum-is-single.js: -------------------------------------------------------------------------------- 1 | // Given a non-negative number, repeatedly add all its digits until the result has only one digit. 2 | 3 | addDigits3 = num => { 4 | 5 | num += '' // This is just converting the number to string, should be equivalent to num.toString() 6 | 7 | while (num.length !==1 ) { 8 | 9 | let sum = 0; 10 | 11 | for (let i = 0; i < num.length; i++) { 12 | sum += parseInt(num[i]); 13 | } 14 | 15 | // Now once the first sum is calculate for the first set of digits, now reset the original num to be equal to sum. So for the next while loop, that number's digits can be summed up 16 | 17 | num = '' + sum; 18 | } 19 | return parseInt(num); 20 | } 21 | 22 | console.log(addDigits3(38)); // => 2 -------------------------------------------------------------------------------- /General-JS-Problems/reverseArray-of-numbers.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | // reversing an array using a temporary var 4 | var reverseArray = function (arr) { 5 | var reverse = []; 6 | for (i = arr.length; i >= 0; i--) { 7 | reverse.push(arr[i]) 8 | } 9 | return reverse; 10 | }; 11 | 12 | // reversing an array without using a temporary var 13 | /* In below, the map() method creates a new array with the results of calling a provided function on every element in the calling array. 14 | 15 | A> So, in the callback function, I am just pulling the last element of the given original array, and returning it first. As for the last element the part arr.[arr.length - 1 - index] is arr.[arr.length - 1 - 0] - which is the last element of the array. 16 | 17 | (and the argument index is the index of the current element being processed, ie. it will start form index=0 of the given original array). 18 | 19 | B> Then for the second loop, index will be 1, i.e. I am pulling the element (arr.length - 1 - 1) i.e. the second last element, and returning it to be placed as the second element of the new array to be created. 20 | 21 | C> And this way, for the last loop, I will be pulling arr[(arr.((length -1)-(length-1)))] element, i.e. the arr[0] element of the original array, and place it to be the last 22 | */ 23 | var reverseArray = function(arr) { 24 | return arr.map(function(item, index) { 25 | return arr[arr.length-1-index]; 26 | }); 27 | }; 28 | // ES6 version 29 | function reverseArray (arr) { 30 | return arr.map((item, index) => arr[arr.length-1-index]); 31 | } 32 | 33 | // Another alternative to reverse an array without using temp variable. While does not require a temp variable, but runs at O(n^2) time. 34 | // Use splice to replace consecutive elements of the array, starting from index=0 with the last element of the array. So in each loop I pop() the last element of the array and take that element to replace the i-th element of the array starting from left-most begining. 35 | function inPlaceReverse(arr) { 36 | var i = 0; 37 | while (i < arr.length - 1 ) { 38 | arr.splice(i, 0, arr.pop()); 39 | i++; 40 | } 41 | return arr; 42 | } 43 | console.log(inPlaceReverse([2, 3, 4])); -------------------------------------------------------------------------------- /General-JS-Problems/search-string-heighlight.html: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | 10 | Searching for string 11 | 17 | 18 | 19 |
20 | 22 |

23 | Search pattern: 24 |

25 |
26 | 27 |
28 | 29 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /General-JS-Problems/setTimeOut-As-Callback.js: -------------------------------------------------------------------------------- 1 | // Use setTimeOut function to print something after 1 second . But this settime out should come as a callback function to some other function, which lets say we call asyncSetTimeOut 2 | 3 | logSetTimeOut = (cb) => { 4 | setTimeout(() => { 5 | cb() 6 | }) 7 | }; 8 | 9 | asyncSetTimeOut = () => console.log("Hello World") 10 | 11 | logSetTimeOut(asyncSetTimeOut); -------------------------------------------------------------------------------- /General-JS-Problems/shuffle-array-so-all-zeros-are-at-beginning.js: -------------------------------------------------------------------------------- 1 | /* I am trying to sort an array so that all the zeros are at the beginning. However, I don't want the list to be numerically sorted, all the numbers above zero should stay in the same order. 2 | using .sort() was wrong in this instance as all the non-zero number will retain their order*/ 3 | 4 | isNotZero = num => { 5 | return num > 0 6 | } 7 | 8 | isZero = num => { 9 | return num === 0 10 | } 11 | 12 | placeZeroAtBeginning = arr => { 13 | return arr.filter(isZero).concat(arr.filter(isNotZero)) 14 | } 15 | 16 | console.log(placeZeroAtBeginning([9,0,9,1,0,2,0,1,1,0,3,0,1,9,9,0,0,0,0,0])); -------------------------------------------------------------------------------- /General-JS-Problems/small-snippets.js: -------------------------------------------------------------------------------- 1 | // Find power of a number without using native JS function 2 | function power (base, exponent) { 3 | var result = 1; 4 | for(var i=1; i<=exponent; i++) { 5 | result = result * base; 6 | } 7 | return result; 8 | } 9 | // console.log(power(2,3)); 10 | 11 | function factorial (num) { 12 | let result = 1; 13 | for (var i = 0; i < num; i++) { 14 | result = result * (num - i); 15 | } 16 | return result; 17 | } 18 | 19 | // console.log(factorial(5)); 20 | 21 | function factorialRecursively (n) { 22 | if (n < 2) { 23 | return 1; 24 | } else { 25 | return n * factorial (n - 1); 26 | } 27 | } 28 | 29 | // Find square-root of a number without using native JS function 30 | var squrt = function (num) { 31 | var sroot = 1; 32 | while (sroot < num) { 33 | if ( sroot * sroot == num) { 34 | return sroot; 35 | } else { 36 | sroot++ 37 | } 38 | } 39 | }; 40 | // console.log(squrt(25)); 41 | 42 | // Check if a number is any power of 2. Its the same logic as checking if a number is power of 4 (see my file ifPowerOfFour.js ). 43 | /* Notes - Keep dividing the number by two, i.e, do n = n/2 iteratively until n becomes 1. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2. */ 44 | var isPowerOfTwo = function (num) { 45 | while ( num != 1) { 46 | num = (num / 2); 47 | 48 | if ( num % 2 != 0 && num != 1) { 49 | return false; 50 | } 51 | }; 52 | return true; 53 | }; 54 | // console.log(isPowerOfTwo(12)); 55 | -------------------------------------------------------------------------------- /General-JS-Problems/sort-array-of-objects.js: -------------------------------------------------------------------------------- 1 | // Sorting an array of JavaScript objects 2 | 3 | // Problem statement - Create a function to sort the objects by the price property in ascending order 4 | 5 | var homes = [ 6 | { 7 | "h_id": "3", 8 | "city": "Dallas", 9 | "state": "TX", 10 | "zip": "75201", 11 | "price": "162500" 12 | }, { 13 | "h_id": "4", 14 | "city": "Bevery Hills", 15 | "state": "CA", 16 | "zip": "90210", 17 | "price": "319250" 18 | }, { 19 | "h_id": "5", 20 | "city": "New York", 21 | "state": "NY", 22 | "zip": "00010", 23 | "price": "962500" 24 | } 25 | ]; 26 | 27 | sortedHome = arr => { 28 | return arr.sort((a, b) => { 29 | return parseFloat(a.price) - parseFloat(b.price) 30 | }) 31 | } 32 | 33 | // console.log(sortedHome(homes)); 34 | 35 | /* Given the price is mentioned as a string, I have to use parseFloat() 36 | 37 | The parseFloat() function parses a string and returns a floating point number. 38 | 39 | This function determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.*/ 40 | 41 | // Alternative - I could also use Number 42 | sortedHome1 = arr => { 43 | return arr.sort((a, b) => Number(a.price) - Number(b.price)) 44 | } 45 | 46 | console.log(sortedHome(homes)); -------------------------------------------------------------------------------- /General-JS-Problems/sum-large-numbers.js: -------------------------------------------------------------------------------- 1 | /* Add 2 very large numbers - 2 | 3 | First check whats is the maximum limit that JS can handle - 4 | https://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin 5 | 6 | Note that all the positive and negative integers whose magnitude is no greater than 253 are representable in the Number type (indeed, the integer 0 has two representations, +0 and −0). 7 | 8 | They are 64-bit floating point values, the largest exact integral value is 253-1, or 9007199254740991. In ES6, this is defined as Number.MAX_SAFE_INTEGER. 9 | 10 | Once I cross this limit, funny things starts to happen 11 | 12 | Math.pow(2, 53) == Math.pow(2, 53) + 1 13 | >> true 14 | */ 15 | 16 | /* Algo - https://www.geeksforgeeks.org/sum-two-large-numbers/ 17 | The idea is based on school mathematics. We traverse both strings from end, one by one add digits and keep track of carry. To simplify the process, we do following: 18 | 1) Reverse both strings. 19 | 2) Keep adding digits one by one from 0’th index (in reversed strings) to end of smaller string, append the sum % 10 to end of result and keep track of carry as sum/10. 20 | 3) Finally reverse the result. 21 | 22 | Understand the problem with below basic example 23 | 24 | 6 6 4 6 6 4 25 | 26 | 2 9 1 3 9 1 27 | ========= ========= 28 | 9 5 5 1 0 5 5 29 | 30 | */ 31 | 32 | function largeNumSum (a, b) { 33 | 34 | let re = /^0/ ; // remove all z 35 | 36 | a = a.replace(re, '').split('').reverse(); 37 | b = b.replace(re, '').split('').reverse(); 38 | 39 | let sum = []; 40 | let maxLength = Math.max(a.length, b.length); 41 | 42 | for (carry = 0, i = 0; i < maxLength; i++) { 43 | 44 | let thisResult = parseInt(a[i] || 0) + parseInt(b[i] || 0) + carry; 45 | 46 | sum[i] = thisResult % 10; 47 | 48 | carry = (thisResult - sum[i]) / 10; 49 | } 50 | 51 | // After the above operations are all done under the if function, if I am still left with more carry - then just push that carry to the array 52 | 53 | if (carry) { 54 | sum.push(carry); 55 | } 56 | return sum.reverse().join(''); 57 | } 58 | 59 | let c = "45555555555555555555555555555555555555777777772222222222222222222222222222222222222222222"; 60 | let d = "99999998888888888888888888888888888888888888888888888888888888899"; 61 | 62 | let a = "664"; 63 | let b = "491"; 64 | 65 | // console.log(c + d); 66 | 67 | console.log(largeNumSum(a, b)); 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /Imp-TECHNIQUES/convert-String-Arr-to-IntArray.js: -------------------------------------------------------------------------------- 1 | var stringArray = new Array('20','120','111','215','54','78'); 2 | 3 | // let's convert it to a real array of numbers, not of strings : 4 | var intArray = stringArray.map(Number); 5 | 6 | console.log(stringArray); 7 | console.log(intArray); -------------------------------------------------------------------------------- /Imp-TECHNIQUES/do-While-loop-Guessing-Game.js: -------------------------------------------------------------------------------- 1 | /* Write a script that will generate a random integer between 1 and 10. You have to guess the number by making guesses until the number you choose matches with the number that script chose. 2 | Given I will be using prompt() this game will only run in-browser. 3 | */ 4 | 5 | const MIN = 1; 6 | const MAX = 10; 7 | 8 | const secretNum = Math.floor(Math.random() * (MAX - MIN + 1) + MIN); 9 | let hint = '' // To string to show hint so the next guess can be narrowed down 10 | let guesses = 0; 11 | 12 | do { 13 | 14 | let input = prompt(`Please enter a number between ${MIN} and ${MAX}` + hint) 15 | 16 | guessedNum = parseInt(input); 17 | 18 | guesses++ 19 | 20 | if (guessedNum < secretNum) { 21 | hint = `and hint is the number should be greater than ${guessedNum}` 22 | } else if (guessedNum > secretNum) { 23 | hint = `and hint is the number should be smaller than ${guessedNum}` 24 | } else { 25 | alert(`Congrats !! you guessed correctly after ${guesses} guesses`) 26 | } 27 | 28 | } while (secretNum !== guessedNum) -------------------------------------------------------------------------------- /Imp-TECHNIQUES/generate-2-D-array-on-the-fly-inside-a-program.js: -------------------------------------------------------------------------------- 1 | /* VERY IMP - Note, the line < chunkedArr.push([arr[i]]) > I am wrapping arr[i] inside an array literal so, that takes cares of pushing the next element as a new inner nested array in this 2-D array structure. 2 | 3 | BUT, for the line < lastChunk.push(arr[i]) > I am NOT doing that, because here, I am not creating a new Array, instead pushing an element to an existing array. So the below is how it works ( a mechanism of creating on-the-fly 2-D array ) */ 4 | 5 | let arr = [1, 2, 3] 6 | arr.push(4) 7 | console.log(arr) // => 1, 2, 3, 4 ] 8 | 9 | let arr1 = [1, 2, 3] 10 | arr1.push([4]) 11 | console.log(arr1) // => [ 1, 2, 3, [ 4 ] ] 12 | 13 | 14 | /* LETS LOOK AT A BEAUTIFUL APPLICATION - PROBLEM - Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array 15 | 16 | Create an empty array to hold the chunks called chunked_arr 17 | Iterate through the given array, for each element in the given array 18 | Pull out the last element of the chunked_arr (a chunk) 19 | If the last element does not exist or its size is equal to size 20 | Push a new chunk into the chunked_arr with the current element 21 | Else add the current element into the chunk */ 22 | 23 | chunk = (arr, chunkSize) => { 24 | 25 | let chunkedArr = [] 26 | 27 | // Now traverse the array, and for each element, check the status of the current chunk. 28 | // Note, current chunk will also be the last element of the chunkedArr. As I am building it from left to right 29 | // If current chunk is full build the next chunk or else push next element this chunk 30 | 31 | for (let i = 0; i < arr.length; i++) { 32 | 33 | // And this last element will be recalculated for each iteration of the given array 34 | const lastChunk = chunkedArr[chunkedArr.length - 1] 35 | 36 | // for the start of the array there will be no lastChunk, as I am starting with an empty array 37 | if (!lastChunk || lastChunk.length === chunkSize ) { 38 | chunkedArr.push([arr[i]]); 39 | } else { 40 | lastChunk.push(arr[i]); 41 | } 42 | } 43 | return chunkedArr; 44 | } 45 | 46 | console.log(chunk([1, 2, 3, 4, 5], 2)) 47 | 48 | 49 | -------------------------------------------------------------------------------- /Imp-TECHNIQUES/generate-array-on-the-fly.js: -------------------------------------------------------------------------------- 1 | // Cool version with code-golfing. Create array on the fly 2 | 3 | const isPrime_cool = n => ![...Array(n).keys()].slice(2).map(i => (n % i)).includes(false) && ![0, 1].includes(n) 4 | 5 | 6 | /* Explanation - 7 | A> [...Array(5)] // => Creates an array on-the-fly with 5 elements each set as 'undefined' 8 | 9 | B> [...Array(5).keys()] // => returns [ 0, 1, 2, 3, 4 ] - i.e. the index no of each of the elements. In this case, I get all the numbers upto the previous value of 5 10 | 11 | C> [...Array(5).keys()].slice(2) // => Returns [ 2, 3, 4 ] - the sliced array starting at index 2. So for this case, I exclude the values 0 and 1, which are by definition NOT prime numbers. 12 | 13 | D> Then with < map(i => (n % i)) > I return an array containing ONLY the remainder after dividing n by each of the array element. As below 14 | 15 | console.log([...Array(5).keys()].slice(2).map(i => 5 % i)); // => [ 1, 2, 1 ] 16 | 17 | That is, if the number is prime (like 5 is indeed a prime) - 5 % i will always return a positive integer. And Zero will never be returned for the case of Prime. 18 | 19 | E> And so then , with the includes() I check if the array includes any 'false' (i.e. 0) 20 | 21 | include() method determines whether an array includes a certain element, returning true or false as appropriate. 22 | 23 | So upto this part is one boolean condition. And after && the next boolean condition 24 | 25 | F> ![0, 1].includes(n) => Means if n is either 0 or 1 return false. That is the first condition of the iterative way to find isPrime 26 | 27 | */ 28 | 29 | console.log(isPrime_cool(19)); -------------------------------------------------------------------------------- /Imp-TECHNIQUES/method_chaining.js: -------------------------------------------------------------------------------- 1 | /* Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results. 2 | 3 | I would like to implement jquery style chain functions ( Methods) using pure javaScript. in Jquery we can do 4 | 5 | $('.class').addClass('new').removeClass('old'). 6 | 7 | we can achieve similar chaining using pure javascript. */ 8 | 9 | // To start with it we going to create an object which is a function. If You know in Javascript functions are also objects. Now will create a public property called i for that we can use the keyword this and assign a value 0. Also we will add a public function add() which will add a number to the i by passing an argument in add(i) function. 10 | // VERY IMPORTANTLY THE ARROW FUNCTION SYNTAX WILL NOT WORK IN THE BELOW 11 | 12 | 13 | var obj = function(){ 14 | 15 | this.i = 0; // public property 16 | 17 | this.add = function(i){ // public function add() 18 | this.i += i; // Add The value 19 | return this; // return's entire object 20 | }; 21 | 22 | this.subtract = function(i){ // public function substract() 23 | this.i -= i; // Subtract's the value 24 | return this; // return's entire object 25 | }; 26 | 27 | this.print = function(){ // public function print() 28 | return this.i ; // Prints the value 29 | }; 30 | console.log(this) 31 | } 32 | 33 | let x = new obj() 34 | 35 | console.log(x.add(3).subtract(2).print()); // => 1 36 | 37 | console.log(obj.this) 38 | 39 | /* OUTPUT 40 | obj { i: 0, add: [Function], subtract: [Function], print: [Function] } 41 | 42 | */ -------------------------------------------------------------------------------- /Imp-TECHNIQUES/parse-Int-toString.js: -------------------------------------------------------------------------------- 1 | // Bascic parseInt() and toString() operations 2 | 3 | console.log((123).toString()); // => "123" 4 | 5 | console.log(typeof (123).toString()); // => string 6 | 7 | console.log(parseInt("123")); // => 123 8 | 9 | console.log(typeof parseInt("123")); // => number 10 | 11 | console.log((parseInt("text"))); // Nan 12 | 13 | console.log(parseFloat("1.234")); // => 1.234 14 | 15 | 16 | 1 + 1 //2 17 | "1" + "1" //"11" 18 | 1 + "1" //"11" -------------------------------------------------------------------------------- /Most-Popular/Prime-Num/find_Prime_factors.js: -------------------------------------------------------------------------------- 1 | // Problems - How could you find all prime factors of a number? 2 | 3 | /* 4 | Run a while loop. start dividing by two and if not divisible increase divider. 5 | 6 | Algorithm - 7 | 1> A Prime Number can be divided evenly only by 1 or itself. 8 | 2> we start the divisor to be the smallest prime number, which is 2. 9 | 3> With a while loop I shall decrease the given number by a factor till it reaches >2 condition. 10 | 4> With the while loop, with each value of n, the divisor is incremented by one. 11 | 12 | Example 1: What are the prime factors of 12 ? 13 | so let's check: 14 | 15 | 12 ÷ 2 = 6 Yes, it divided evenly by 2. So push 2 to the empty array factors[] 16 | 17 | In the next loop, n becomes 6, so we divide 6 by 2 again: 6 ÷ 2 = 3 and so push 2 agian to the factors[] array. 18 | 19 | In the third iteration, first we divide 3 (as now n has become 3) by 2. Being non-divisible, we increment the divisor by 1 and get 3. And then we divide n (i.e. 3) by 3 and its divisible. So, we push 3 to the array factor[] 20 | 21 | 12 = 2 × 2 × 3 22 | 23 | */ 24 | 25 | function primeFactors(n) { 26 | var factors = []; 27 | var divisor = 2; 28 | 29 | while (n > 2) { 30 | if (n % divisor == 0 ) { 31 | factors.push(divisor); 32 | n = n / divisor ; 33 | } 34 | else { 35 | divisor++ 36 | } 37 | } 38 | return factors; 39 | } 40 | 41 | 42 | console.log(primeFactors(12)); 43 | -------------------------------------------------------------------------------- /Most-Popular/Prime-Num/prime-Find-nth-Prime-Number.js: -------------------------------------------------------------------------------- 1 | // Find the n-th Prime number 2 | // First code to check for primes - Decrease complexity of algorithm from O(n) to O(sqrt(n)) by running the loop until square root of number 3 | 4 | isPrime = num => { 5 | 6 | if (isNaN(num) || !isFinite(num) || (num % 1 !== 0) || num < 2) { 7 | return false; 8 | } 9 | 10 | /* Explanation of (num % 1 !== 0) - This is the standard way to check if a number is a decimal - The logic for (num % 1 !== 0) >>>> ( num % 1 ) will return 0 only if the num is an integer (whole number) but will return a non-zero for all decimal. And so immediately return false in this program. 11 | 12 | console.log(19 % 1) // => 0 13 | console.log(19.2 % 1) // => 0.19999999999999993 14 | */ 15 | 16 | let maxNumToCheckForPrimeness = Math.sqrt(num); 17 | 18 | for (let i = 2; i <= maxNumToCheckForPrimeness; i++ ) 19 | if (num % i === 0) { return false }; 20 | return true; 21 | } 22 | 23 | console.log(isPrime(19)); // => true 24 | 25 | findnthPrime = n => { 26 | let counter = 0; 27 | 28 | for (i = 0; i <= 1000; i++) { 29 | if (isPrime(i)) { 30 | counter++ 31 | } 32 | if (counter === n) { 33 | return i; 34 | break; 35 | } 36 | } 37 | } 38 | 39 | console.log(findnthPrime(10)); // => 29 40 | -------------------------------------------------------------------------------- /Most-Popular/Prime-Num/prime-generation-between-Range.js: -------------------------------------------------------------------------------- 1 | // SOLUTION-1 - Print all primes between range - faced this in Techolution Interview on 21-June-2018 2 | 3 | isPrime = (num) => { 4 | 5 | // Treaditionally/Conventionally prime number starts from 2 6 | if (isNaN(num) || !isFinite(num) || num % 1 || num < 2) { 7 | return false; 8 | } 9 | 10 | let maxNumToCheck = Math.sqrt(num); 11 | 12 | for (let i = 2; i <= maxNumToCheck; i++) { 13 | if (num % i === 0) { 14 | return false; 15 | } 16 | } 17 | return true; 18 | } 19 | 20 | console.log(isPrime(8)); 21 | 22 | generatePrime = (a, b) => { 23 | 24 | // in case the range is given in the format whre large no is first and then the small no 25 | let start = ( a <= b ) ? a : b; 26 | let end = ( b > a ) ? b : a; 27 | 28 | primes = [] 29 | 30 | for (let i = start; i <= end; i++) { 31 | if(isPrime(i)) { 32 | primes.push(i); 33 | } 34 | } 35 | return primes; 36 | } 37 | 38 | console.log(generatePrime(1, 10)); 39 | 40 | // SOLUTION-2 41 | 42 | allPrimes = n => { 43 | let range = [...Array(n + 1).keys()].slice(2); 44 | return range.filter(p => isPrime2(p)) 45 | } 46 | 47 | isPrime2 = n => { 48 | for (let i = 2; i <= Math.sqrt(n); i++) { 49 | if ( n % i === 0) return false; 50 | } return true; 51 | } 52 | 53 | console.log(allPrimes(10)); 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Most-Popular/Prime-Num/prime-num-between-range.js: -------------------------------------------------------------------------------- 1 | isPrime = num => { 2 | 3 | if (isNaN(num) || !isFinite(num) || (num % 1 !== 0) || num < 2) { 4 | return false; 5 | } 6 | 7 | /* Explanation of (num % 1 !== 0) - This is the standard way to check if a number is a decimal - The logic for (num % 1 !== 0) >>>> ( num % 1 ) will return 0 only if the num is an integer (whole number) but will return a non-zero for all decimal. And so immediately return false in this program. 8 | 9 | console.log(19 % 1) // => 0 10 | console.log(19.2 % 1) // => 0.19999999999999993 11 | */ 12 | 13 | let maxNumToCheckForPrimeness = Math.sqrt(num); 14 | 15 | for (let i = 2; i <= maxNumToCheckForPrimeness; i++ ) 16 | if (num % i === 0) { return false }; 17 | return true; 18 | } 19 | 20 | primeInRange = (min, max) => { 21 | 22 | let primes = [] 23 | 24 | for (let i = min; i <= max; i++ ) { 25 | if (isPrime(i)) { 26 | primes.push(i) 27 | } 28 | } 29 | return primes; 30 | } 31 | 32 | console.log(primeInRange(2, 12)); -------------------------------------------------------------------------------- /Most-Popular/Prime-Num/prime_palindrome.js: -------------------------------------------------------------------------------- 1 | //Write a program which determines the largest prime palindrome less than 1000. 2 | 3 | function isPrime (number) 4 | { 5 | if (number < 2) return false; 6 | 7 | //An integer is prime if it is not divisible by any prime less than or equal to its square root 8 | 9 | var q = Math.floor(Math.sqrt(number)); 10 | 11 | for (var i = 2; i <= q; i++) 12 | { 13 | if (number % i == 0) 14 | { 15 | return false; 16 | } 17 | } 18 | 19 | return true; 20 | } 21 | 22 | var isPalindrome = function (number) { 23 | var numToString = number.toString(); 24 | var checkPalindrome = numToString.split('').reverse().join(''); 25 | 26 | if (numToString === checkPalindrome) { 27 | return true; 28 | }else { 29 | return false; 30 | } 31 | }; 32 | 33 | for (var i = 1000; true; i--){ 34 | if (isPalindrome(i) && isPrime(i)){ 35 | console.log(i); 36 | break; 37 | } 38 | } -------------------------------------------------------------------------------- /Most-Popular/String/reverseArray-of-numbers.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | // reversing an array using a temporary var 4 | var reverseArray = function (arr) { 5 | var reverse = []; 6 | for (i = arr.length; i >= 0; i--) { 7 | reverse.push(arr[i]) 8 | } 9 | return reverse; 10 | }; 11 | 12 | // reversing an array without using a temporary var 13 | /* In below, the map() method creates a new array with the results of calling a provided function on every element in the calling array. 14 | 15 | A> So, in the callback function, I am just pulling the last element of the given original array, and returning it first. As for the last element the part arr.[arr.length - 1 - index] is arr.[arr.length - 1 - 0] - which is the last element of the array. 16 | 17 | (and the argument index is the index of the current element being processed, ie. it will start form index=0 of the given original array). 18 | 19 | B> Then for the second loop, index will be 1, i.e. I am pulling the element (arr.length - 1 - 1) i.e. the second last element, and returning it to be placed as the second element of the new array to be created. 20 | 21 | C> And this way, for the last loop, I will be pulling arr[(arr.((length -1)-(length-1)))] element, i.e. the arr[0] element of the original array, and place it to be the last 22 | */ 23 | var reverseArray = function(arr) { 24 | return arr.map(function(item, index) { 25 | return arr[arr.length-1-index]; 26 | }); 27 | }; 28 | // ES6 version 29 | function reverseArray (arr) { 30 | return arr.map((item, index) => arr[arr.length-1-index]); 31 | } 32 | 33 | // Another alternative to reverse an array without using temp variable. While does not require a temp variable, but runs at O(n^2) time. 34 | // Use splice to replace consecutive elements of the array, starting from index=0 with the last element of the array. So in each loop I pop() the last element of the array and take that element to replace the i-th element of the array starting from left-most begining. 35 | function inPlaceReverse(arr) { 36 | var i = 0; 37 | while (i < arr.length - 1 ) { 38 | arr.splice(i, 0, arr.pop()); 39 | i++; 40 | } 41 | return arr; 42 | } 43 | console.log(inPlaceReverse([2, 3, 4])); -------------------------------------------------------------------------------- /Most-Popular/count-vowels.js: -------------------------------------------------------------------------------- 1 | /* Find the count of Vowels in the given string using match method and regular expression in JS 2 | */ 3 | 4 | //The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object. 5 | 6 | function countVowels(str) { 7 | const re = /(a|e|i|o|u)/g; 8 | 9 | let vowelCounter = 0; 10 | 11 | for (let i of str) { 12 | if (i.match(re)) { 13 | vowelCounter++; 14 | } 15 | } 16 | return vowelCounter; 17 | } 18 | 19 | // console.log(countVowels("Paul")); // => 2 20 | 21 | // Alternative - 2 22 | countVowels2 = str => { 23 | let vowelCounter = str.match(/[aeiou]/gi); 24 | return vowelCounter === null 25 | ? "No vowels in the given string" 26 | : vowelCounter.length; 27 | }; 28 | 29 | // console.log(countVowels2("Psfsfl")); 30 | 31 | countVowels3 = str => { 32 | return (vowelCounter = str.match(/[aeiou]/gi).length); 33 | }; 34 | 35 | // console.log(countVowels3("Paul")); 36 | 37 | countVowels4 = str => { 38 | return Array.from(str).filter(vowelsInStr => "aeiou".includes(vowelsInStr)) 39 | .length; 40 | }; 41 | 42 | // The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate. 43 | 44 | console.log(countVowels4("Paul")); 45 | -------------------------------------------------------------------------------- /Most-Popular/counting-zeros-in-number.js: -------------------------------------------------------------------------------- 1 | /* Question: Count Total number of zeros from 1 upto n ? 2 | 3 | Answer: If n = 100. number of 0 would be 11 (0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100). Please note that 100 has two 0. This one looks simple but little tricky 4 | 5 | */ 6 | 7 | /* My Note - If I have a number 1 to 50 the value is 5. which is 50 divided by 10. However, if the value is 100. the value is 11. you will get by 100/10 = 10 and 10/10. Thats how you will get in the more zeros in one number like (100, 200, 1000) 8 | 9 | The idea is to traverse all numbers from 1 to n. For every traversed number, traverse through its digits, if any digit is 0, increment count. Below is the implementation of the above idea : 10 | 11 | https://www.geeksforgeeks.org/count-numbers-0-digit/ 12 | 13 | Refer below post for optimized solution. - https://www.geeksforgeeks.org/count-numbers-having-0-as-a-digit/ 14 | 15 | */ 16 | 17 | const countZero = num => { 18 | let counter = 0 19 | 20 | while (num) { 21 | // Count the first no of count of zeros 22 | counter += Math.floor(num / 10) 23 | 24 | // console.log(Math.floor(102 / 10)); => 10 25 | 26 | // then reduce the original number for the next loop 27 | num = Math.floor(num / 10) 28 | /* If I don't user Math.floor() then division by 10 will create decimal numbers and the number of iterations will way higher 29 | Note console.log(Math.floor(0.1)) => 0 30 | console.log(Math.floor(102 / 10)); => 10 31 | */ 32 | } 33 | 34 | return counter 35 | } 36 | 37 | console.log(countZero(107)) 38 | -------------------------------------------------------------------------------- /Most-Popular/quick-sort-with-Counter.js: -------------------------------------------------------------------------------- 1 | /* Implement a quick-sort along with the no of comparisons made 2 | */ 3 | 4 | let counterOuter = 0; 5 | let counterInner = 0; 6 | 7 | function quickSort (arr) { 8 | counterOuter++; 9 | if (arr.length < 2) { 10 | return arr; 11 | } 12 | 13 | let pivot = arr[0]; 14 | let rightArr = []; 15 | let leftArr = []; 16 | 17 | for (let i = 1; i < arr.length; i++) { 18 | counterInner++; 19 | if (arr[i] > pivot) { 20 | rightArr.push(arr[i]); 21 | } else { 22 | leftArr.push(arr[i]); 23 | } 24 | } 25 | 26 | /* But the above steps are what I have to build-up going again and again over the array recursively, and return only the last resursive call. */ 27 | 28 | return quickSort(leftArr).concat(pivot, quickSort(rightArr)); 29 | 30 | } 31 | 32 | function getRandomInt(min, max) { 33 | return Math.floor(Math.random() * (max - min + 1)) + min; 34 | } 35 | 36 | var myArr = []; 37 | 38 | for (var i = 0; i < 10; i++) { //initialize a random integer unsorted array 39 | myArr.push(getRandomInt(1, 20)); 40 | } 41 | 42 | console.log("Unsorted array: "); 43 | console.log(myArr); //printing unsorted array 44 | 45 | myArr = quickSort(myArr, 0, myArr.length - 1); 46 | console.log("Sorted array: "); 47 | console.log(myArr); 48 | console.log(quickSort(myArr.slice())); 49 | 50 | console.log('outer:', counterOuter, 'inner:', counterInner); -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/Delete-Prop-with-numbers-as-keys-regulal-destructuring-wont-work.js: -------------------------------------------------------------------------------- 1 | const omit = require("lodash.omit"); 2 | // import produce from "immer"; 3 | const { produce } = require("immer"); 4 | 5 | const myObj = { 6 | "0": { 7 | index: 0, 8 | creditcardnumber: "8726-4123-8697-2698" 9 | }, 10 | "1": { 11 | index: 1, 12 | creditcardnumber: "1234-5639-3200-7945" 13 | } 14 | }; 15 | 16 | // The below assignment wont work 17 | // const { "0", ...rest } = myObj 18 | // console.log(rest); 19 | 20 | // With lodash 21 | // console.log(omit(myObj, ["0"])); 22 | 23 | // console.log(produce(delete myObj[0])); 24 | 25 | const deletedTodosObj = produce(myObj, draft => { 26 | delete draft[0]; 27 | }); 28 | 29 | console.log(deletedTodosObj); 30 | // console.log(myObj); 31 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/Object-of-arrays-with-further-nested-array-return-an-element-meeting-condition.js: -------------------------------------------------------------------------------- 1 | // From the below object of arrays get the full single object with id === 2 2 | const roles = { 3 | globalRoles: [ 4 | { 5 | id: 1, 6 | shop_id: null, 7 | global: true, 8 | name: "owner" 9 | }, 10 | { 11 | id: 2, 12 | shop_id: null, 13 | global: true, 14 | name: "admin" 15 | }, 16 | { 17 | id: 3, 18 | shop_id: null, 19 | global: true, 20 | name: "super admin" 21 | } 22 | ], 23 | customRoles: [ 24 | { 25 | id: 4, 26 | shop_id: 1, 27 | global: false, 28 | name: "custom user 1" 29 | }, 30 | { 31 | id: 5, 32 | shop_id: 1, 33 | global: false, 34 | name: "custom user 2" 35 | } 36 | ] 37 | }; 38 | 39 | const requiredData = Object.values(roles) 40 | .reduce((acc, arr) => acc.concat(arr), []) 41 | .find(role => role.id === 2); 42 | 43 | console.log(requiredData); 44 | 45 | // Output => { id: 2, shop_id: null, global: true, name: 'admin' } 46 | 47 | /*Explanation 48 | 49 | Step A> The Object.values(roles) will return an array of values, which in this case will be 2 arrays as elements. As values are arrays here. 50 | And they will be wrapped in anoteher array as Object.values return an array. 51 | 52 | console.log(Object.values(roles)); 53 | 54 | Will return 55 | 56 | [ [ { id: 1, shop_id: null, global: true, name: 'owner' }, 57 | { id: 2, shop_id: null, global: true, name: 'admin' }, 58 | { id: 3, shop_id: null, global: true, name: 'super admin' } ], 59 | [ { id: 4, shop_id: 1, global: false, name: 'custom user 1' }, 60 | { id: 5, shop_id: 1, global: false, name: 'custom user 2' } ] ] 61 | 62 | 63 | Step B> The reduce method will ONLY flatten the 2-d array generated in the first step 64 | 65 | console.log(Object.values(roles).reduce((acc, arr) => acc.concat(arr), [])); 66 | 67 | Will return 68 | 69 | [ { id: 1, shop_id: null, global: true, name: 'owner' }, 70 | { id: 2, shop_id: null, global: true, name: 'admin' }, 71 | { id: 3, shop_id: null, global: true, name: 'super admin' }, 72 | { id: 4, shop_id: 1, global: false, name: 'custom user 1' }, 73 | { id: 5, shop_id: 1, global: false, name: 'custom user 2' } ] 74 | 75 | Step C> Nnow only simple job left is to return the element with id === 1 76 | 77 | */ 78 | 79 | // console.log(requiredData); 80 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/Object.assign.md: -------------------------------------------------------------------------------- 1 | ### Object.assign(target, ...sources) 2 | 3 | The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object. 4 | 5 | Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones. 6 | 7 | The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties. 8 | 9 | #### Simple use-case for merging multiple objects 10 | 11 | `Object.assign(target, source_1, ..., source_n)` 12 | 13 | This function modifies target and returns it: it first copies all enumerable own properties of source_1 to target, then those of source_2, etc. 14 | 15 | ```js 16 | // Latest ES6 17 | const obj1 = { 18 | a: 1, 19 | b: 2, 20 | } 21 | 22 | const obj2 = { 23 | c: 3, 24 | d: 4, 25 | } 26 | 27 | const merged = { ...obj1, ...obj2 } 28 | 29 | // console.log(merged); // => { a: 1, b: 2, c: 3, d: 4 }s 30 | ``` 31 | 32 | #### The following example uses the Object.assign() method to clone an object. 33 | 34 | ```js 35 | let widget = { 36 | color: "red", 37 | } 38 | 39 | let clonedWidget = Object.assign({}, widget) 40 | 41 | console.log(clonedWidget) 42 | /* Output 43 | 44 | { 45 | color: "red" 46 | } */ 47 | ``` 48 | 49 | #### Adding a method to an object 50 | 51 | ```js 52 | MyClass.prototype.foo = function(arg1, arg2) { 53 | ... 54 | } 55 | ``` 56 | 57 | ECMAScript 6 has a more concise syntax for methods [3]. Thanks to Object.assign(), you don’t have to abandon that syntax: 58 | 59 | ```js 60 | Object.assign(MyClass.prototype, { 61 | foo(arg1, arg2) { 62 | ... 63 | } 64 | }) 65 | 66 | ``` 67 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/array-map-like-function-for-Objects.js: -------------------------------------------------------------------------------- 1 | /* I have an object: 2 | 3 | myObject = { 'a': 1, 'b': 2, 'c': 3 } 2 4 | 5 | Implement a method similar to Array.prototype.map that would be used as follows: 6 | 7 | newObject = myObject.map(function (value, label) { 8 | return value * value; 9 | }); 10 | 11 | newObject is now { 'a': 1, 'b': 4, 'c': 9 } 12 | */ 13 | 14 | // There's no map() native function for objects, so here's a similar implementation 15 | 16 | myObject = { a: 1, b: 2, c: 3 }; 17 | console.log(myObject); 18 | 19 | mapForObject = obj => { 20 | Object.keys(obj).map(key => (obj[key] = obj[key] * 2)); 21 | return obj; 22 | }; 23 | 24 | // console.log(mapForObject(myObject)); // => { a: 2, b: 4, c: 6 } 25 | 26 | /* SOLUTION-2 (WITHOUT MUTATING) the previous methods do not return a new object, but rather operate on the object itself. So, this below solution returns a new object and leaves the original object as it is: */ 27 | 28 | mapFunctionForObject = obj => { 29 | return Object.keys(obj).reduce((accum, curr) => { 30 | accum[curr] = obj[curr] * 2; 31 | return accum; 32 | }, {}); 33 | }; 34 | 35 | console.log(mapFunctionForObject(myObject)); // => { a: 2, b: 4, c: 6 } 36 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/array-of-objects-1.js: -------------------------------------------------------------------------------- 1 | /* You will need to track carbs and fat for each type of food. Then you will need to summarize it all at the end so you can figure out how many grams you consumed in each category. Here is our foods object with fake nutritional values. 2 | */ 3 | 4 | let foods = [ 5 | { name: "steak", calories: 800, carbs: 10, fat: 30 }, 6 | { name: "fruit", calories: 200, carbs: 20, fat: 0 }, 7 | { name: "salad", calories: 100, carbs: 0, fat: 5 }, 8 | { name: "chips", calories: 300, carbs: 10, fat: 10 }, 9 | { name: "ice cream", calories: 700, carbs: 20, fat: 20 } 10 | ]; 11 | 12 | // The output required is a single object, with key-value pairs for calories, carbs and fat with their corresponding total numbers. 13 | 14 | let totalFromFoods = foods.reduce((bucket, item) => { 15 | bucket["calories"] += item.calories; 16 | bucket["carbs"] += item.carbs; 17 | bucket["fat"] += item.fat; 18 | 19 | delete bucket.name; 20 | return bucket; 21 | }); 22 | 23 | console.log(totalFromFoods); 24 | 25 | /* 26 | OUTPUT 27 | 28 | { name: 'steak', calories: 2100, carbs: 60, fat: 65 } 29 | 30 | */ 31 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/cloninng_deep-2.js: -------------------------------------------------------------------------------- 1 | // THIS FILE IS NOT WORKING, AND THE THIS PARTICULAR THIRD-PARTY PACKAGE IS FOR REACT APPS 2 | 3 | import update from 'immutability-helper'; 4 | 5 | // import update from '../node_modules/immutability-helper/index.d.ts' 6 | 7 | const myObj_1 = { 8 | a: 2, 9 | b: 5, 10 | c: { 11 | x: 7, 12 | y: 4, 13 | }, 14 | } 15 | 16 | 17 | let clonedObj = update({ a: 2, b: 5, c: { x: {$set: 27}, y: 4 } }) 18 | 19 | console.log(myObj_1); 20 | 21 | console.log(clonedObj) -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/convert-arr-of-obj-to-arr-of-arr-removing-some-fields-useful-external-api.js: -------------------------------------------------------------------------------- 1 | /*From below data retrun the following format of data for rendering with highchart 2 | 3 | formattedData = [ [ '2019-03-26', 117.910004 ], [ '2019-03-27', 116.769997 ] ] 4 | 5 | */ 6 | 7 | const omit = require("lodash.omit"); 8 | const R = require("ramda"); 9 | 10 | const data = [ 11 | { 12 | Date: "2019-03-26", 13 | Open: 118.620003, 14 | High: 118.709999, 15 | Low: 116.849998, 16 | Close: 117.910004 17 | }, 18 | { 19 | Date: "2019-03-27", 20 | Open: 117.879997, 21 | High: 118.209999, 22 | Low: 115.519997, 23 | Close: 116.769997 24 | } 25 | ]; 26 | 27 | // Alt-1 28 | const formattedDataForHighCharts = data => { 29 | let result = []; 30 | data.map((obj, index) => { 31 | for (key in obj) { 32 | if (obj.hasOwnProperty("Date") && obj.hasOwnProperty("Close")) { 33 | result[index] = [obj["Date"], obj["Close"]]; 34 | } 35 | } 36 | }); 37 | return result; 38 | }; 39 | 40 | // console.log(formattedDataForHighCharts(data)); 41 | 42 | // Alt-2 - Using Lodash 43 | const formattedDataForHighChartsLodash = data => { 44 | return data.map(obj => { 45 | let omittedObject = omit(obj, ["Open", "High", "Low"]); 46 | return Object.values(omittedObject); 47 | }); 48 | }; 49 | 50 | // console.log(formattedDataForHighChartsLodash(data)); 51 | 52 | // Alt-3 - Using Ramda 53 | const formattedDataForHighChartsRamda = data => { 54 | return data.map(obj => { 55 | let omittedObject = R.omit(["Open", "High", "Low"], obj); 56 | return Object.values(omittedObject); 57 | }); 58 | }; 59 | 60 | const resultData = formattedDataForHighChartsRamda(data); 61 | 62 | console.log(resultData); 63 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/convert-arr-of-objects-into-another-dynamically-add-field-useful-for-api-request.js: -------------------------------------------------------------------------------- 1 | /* ************* FIRST USE CASE ******************** 2 | 3 | Here, I have to convert an array of objects to array of objects adding new fields dynamically 4 | 5 | Original data received from API 6 | 7 | suggestions = [ 8 | { label: "Afghanistan" }, 9 | { label: "Aland Islands" }, 10 | { label: "Albania" }, 11 | { label: "Algeria" } 12 | ] 13 | 14 | BUT I need data in following format 15 | 16 | [ { value: 'Afghanistan', label: 'Afghanistan' }, 17 | { value: 'Aland Islands', label: 'Aland Islands' }, 18 | { value: 'Albania', label: 'Albania' }, 19 | { value: 'Algeria', label: 'Algeria' } ] 20 | 21 | */ 22 | 23 | const suggestions = [ 24 | { label: "Afghanistan" }, 25 | { label: "Aland Islands" }, 26 | { label: "Albania" }, 27 | { label: "Algeria" } 28 | ].map(suggestion => ({ 29 | value: suggestion.label, 30 | label: suggestion.label 31 | })); 32 | 33 | // console.log(suggestions); 34 | 35 | /* ************* SECOND USE CASE ******************** 36 | 37 | Here, I have to convert an array of arrays to array of objects adding new fields dynamically 38 | 39 | Original data received from API 40 | 41 | [["2019-04-01", 21.66], ["2019-03-01", 21.27]]; 42 | 43 | 44 | BUT I need data in following format 45 | 46 | const Requireddata = [ 47 | { date: "2010-06-10T07:00:00.000Z", close: 250.51 }, 48 | { date: "2010-06-11T07:00:00.000Z", close: 253.51 } 49 | ] 50 | 51 | */ 52 | 53 | const originalData = [["2019-04-01", 21.66], ["2019-03-01", 21.27]]; 54 | 55 | const requiredData = originalData.map(i => ({ 56 | date: i[0], 57 | close: i[1] 58 | })); 59 | 60 | console.log(requiredData); 61 | 62 | console.log(requiredData.reverse()); 63 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/convert-obj-of-key-value-pairs-to-arrays-DeNormalization.js: -------------------------------------------------------------------------------- 1 | /* Sometimes, you might find that it’s easier to use an array for your list of items. For example, when you are rendering a list. It’s easier to have an array, use a map and create the element in each iteration. 2 | 3 | This has an easy solution. Instead of accessing directly the state, use a function. What is also known as a selector. 4 | 5 | A selector is a function that takes some state and returns the data you need. 6 | 7 | This is the opposite of what Redux normalization would do - i.e. normalization of Redux state means converting an array-of-objects to objects-of-objects 8 | 9 | */ 10 | 11 | // object 12 | const comments = { 13 | "1": { id: "1", text: "please add code examples" }, 14 | "2": { id: "2", text: "examples would be great for this article" }, 15 | "3": { id: "3", text: "hi there" }, 16 | } 17 | 18 | /* But I need the data in the below format 19 | 20 | [ { id: '1', text: 'please add code examples' }, 21 | { id: '2', text: 'examples would be great for this article' }, 22 | { id: '3', text: 'hi there' } ] 23 | 24 | */ 25 | 26 | const commentsSelector = commentObj => { 27 | return Object.keys(commentObj).map(commentKey => commentObj[commentKey]) 28 | } 29 | 30 | console.log(commentsSelector(comments)) 31 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/convert-obj-of-nested-obj-to-arr-of-arr-worldtrading-data-api-with-vx-chart.js: -------------------------------------------------------------------------------- 1 | // From the API I have received the following data for the S&P Index price 2 | const data = { 3 | "2019-03-29": { 4 | open: "2828.27", 5 | close: "2834.40", 6 | high: "2836.03", 7 | low: "2819.23", 8 | volume: "0" 9 | }, 10 | "2019-03-28": { 11 | open: "2809.40", 12 | close: "2815.44", 13 | high: "2819.71", 14 | low: "2798.77", 15 | volume: "0" 16 | } 17 | }; 18 | 19 | /* BUT I need the following structure of data 20 | 21 | [ { date: '2019-03-29', close: '2834.40' }, 22 | { date: '2019-03-28', close: '2815.44' } ] 23 | */ 24 | 25 | const getDateAndClosingPrice = obj => { 26 | let result = []; 27 | for (let key in obj) { 28 | if (obj.hasOwnProperty(key)) { 29 | result.push([key, obj[key].close]); 30 | } 31 | } 32 | return result.map(i => ({ 33 | date: i[0], 34 | close: i[1] 35 | })); 36 | }; 37 | 38 | console.log(getDateAndClosingPrice(data)); 39 | 40 | // **************** ANOTHER SLIGHT RESTRUCTURING FOR HIGHCAHRTS OF THE SAME DATA ************* 41 | /* For Highcharts, I need the data in the below format. Where the first element is the xAxis and second element is 42 | 43 | [ [ '2019-03-29', '2019-03-28' ], [ '2834.40', '2815.44' ] ] 44 | 45 | */ 46 | 47 | const getDateAndClosingPrice = obj => { 48 | let xAxis = []; 49 | let yAxis = []; 50 | for (let key in obj) { 51 | if (obj.hasOwnProperty(key)) { 52 | xAxis.push(key); 53 | yAxis.push(parseInt(obj[key].close)); 54 | } 55 | } 56 | return [xAxis, yAxis]; 57 | }; 58 | 59 | console.log(getDateAndClosingPrice(data)); 60 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/convert-plain-object-to-array-of-objects-useful-external-api.js: -------------------------------------------------------------------------------- 1 | /* Understanding the setState mechanism - Basically I have to convert and plain object to an array of objects AND CREATE 2 NEW fields TO BE ATTACHED TO THE OBJECTS ('date' and 'close') 2 | 3 | A> From Coindesk API - I will get the below data 4 | 5 | const data = { 6 | bpi: { 7 | "2019-03-26": 3945.325, 8 | "2019-03-27": 4051.9033, 9 | "2019-03-28": 4039.0017, 10 | "2019-03-29": 4119.0183, 11 | "2019-03-30": 4117.8483 12 | }, 13 | disclaimer: 14 | "This data was produced from the CoinDesk Bitcoin Price Index. BPI value data returned as USD.", 15 | time: { 16 | updated: "Apr 26, 2019 00:03:00 UTC", 17 | updatedISO: "2019-04-26T00:03:00+00:00" 18 | } 19 | }; 20 | 21 | B> But I need the data (i.e. my state) in the below format 22 | 23 | [ { date: '2019-03-26', close: 3945.325 }, 24 | { date: '2019-03-27', close: 4051.9033 }, 25 | { date: '2019-03-28', close: 4039.0017 }, 26 | { date: '2019-03-29', close: 4119.0183 }, 27 | { date: '2019-03-30', close: 4117.8483 } ] 28 | 29 | C> Hence, first I get all the dates from the API-data with Object.keys() which will return me all the keys of the original received objects as an array 30 | 31 | this.setState({ 32 | data: Object.keys(data.bpi).map(item => { 33 | return { 34 | date: item, 35 | close: data.bpi[item] 36 | }; 37 | }) 38 | }); 39 | */ 40 | 41 | const data = { 42 | bpi: { 43 | "2019-03-26": 3945.325, 44 | "2019-03-27": 4051.9033, 45 | "2019-03-28": 4039.0017, 46 | "2019-03-29": 4119.0183, 47 | "2019-03-30": 4117.8483 48 | }, 49 | disclaimer: 50 | "This data was produced from the CoinDesk Bitcoin Price Index. BPI value data returned as USD.", 51 | time: { 52 | updated: "Apr 26, 2019 00:03:00 UTC", 53 | updatedISO: "2019-04-26T00:03:00+00:00" 54 | } 55 | }; 56 | 57 | const stateData = Object.keys(data.bpi).map(item => { 58 | return { 59 | date: item, 60 | close: data.bpi[item] 61 | }; 62 | }); 63 | 64 | console.log(stateData); 65 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/copy-one-object-to-another-object.js: -------------------------------------------------------------------------------- 1 | // copy-one-object-to-another-object 2 | 3 | let myObject = { apple: "a", orange: "o" }; 4 | 5 | // 1st solution to copy 6 | let secondObject = Object.assign({lemon: "1"}, myObject) 7 | 8 | console.log(secondObject); // => { lemon: '1', apple: 'a', orange: 'o' } 9 | 10 | // 2-nd solution to copy using ES6 spread ... operator 11 | 12 | let secondObject2 = {lemon: "1", ...myObject} 13 | 14 | console.log(secondObject2); // => { lemon: '1', apple: 'a', orange: 'o' } 15 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/delete_Properties_with_rest_spread.js: -------------------------------------------------------------------------------- 1 | const myObject = { 2 | a: 1, 3 | b: 2, 4 | c: 5, 5 | d: 4 6 | }; 7 | 8 | // const { a, b, ...restProps } = myObject; 9 | // console.log(restProps); // => { c: 5, d: 4 } 10 | 11 | /* 12 | https://codeburst.io/use-es2015-object-rest-operator-to-omit-properties-38a3ecffe90 13 | 14 | */ 15 | 16 | // Now write a function to do the same (useful if I have to dispatch a function from redux stroe) 17 | const deleteProp = obj => { 18 | const { a, b, ...restProps } = obj; 19 | return restProps; 20 | }; 21 | 22 | console.log(deleteProp(myObject)); 23 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/flatten-2d-arrays-picking-only-second-element-highcharts.js: -------------------------------------------------------------------------------- 1 | const givenData = [ 2 | ["2019-04-01", 21.66], 3 | ["2019-03-01", 21.27], 4 | ["2019-02-01", 21.09], 5 | ["2019-01-01", 19.66] 6 | ]; 7 | // 8 | // const givenData = [ 9 | // {"2019-04-01", 21.66}, 10 | // {"2019-02-01", 21.09}, 11 | // {"2019-03-01", 21.27}, 12 | // {"2019-01-01", 19.66} 13 | // ]; 14 | 15 | const _ = require("lodash"); 16 | 17 | /* I need following output 18 | 19 | const requiredDate = [ 20 | 21.66, 21 | 21.27, 22 | 21.09, 23 | 19.66 24 | ] 25 | 26 | */ 27 | 28 | const result = _.flatten( 29 | givenData.map(i => { 30 | return i.slice(1, 2); 31 | }) 32 | ); 33 | 34 | console.log(result); 35 | 36 | /* Very true, and on top of that, they had to resort to Github to send this message, when FB, Twitter are blocked or censored */ 37 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/flatten-objects-plain-js-recursive.js: -------------------------------------------------------------------------------- 1 | /* 2 | I wanted to flatten my deep object to one level depth. 3 | 4 | My input: 5 | */ 6 | 7 | const input = { 8 | user: { 9 | key_value_map: { 10 | CreatedDate: "123424", 11 | Department: { 12 | Name: "XYZ", 13 | }, 14 | }, 15 | }, 16 | } 17 | 18 | /* Expected output: 19 | 20 | { 21 | "user.key_value_map.CreatedDate": "123424", 22 | "user.key_value_map.Department.Name": "XYZ" 23 | } 24 | My note - Mostly all solutions will involve some implementation of recursion here 25 | */ 26 | const flattenObject = obj => { 27 | let flattened = {} 28 | for (let i in obj) { 29 | if (!obj.hasOwnProperty(i)) continue // ie. if the object does not have the 'i' property as its own property, ie. the object does not have any property to enumerate 30 | 31 | if (typeof obj[i] === "object" && obj[i] !== null) { 32 | var flatObject = flattenObject(obj[i]) 33 | for (let j in flatObject) { 34 | if (!flatObject.hasOwnProperty(j)) continue 35 | flattened[i + "." + j] = flatObject[j] 36 | } 37 | } else { 38 | flattened[i] = obj[i] 39 | } 40 | } 41 | return flattened 42 | } 43 | 44 | console.log(flattenObject(input)) 45 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/getting-key-with-max-value-from-object.js: -------------------------------------------------------------------------------- 1 | // given an key-value pair object get the key with max value 2 | 3 | let myObj = { "1": 2, "2": 1, "3": 2, "5": 3, "8": 1 } 4 | 5 | // Case when I have multiple maximum value 6 | let myObj2 = { "1": 3, "2": 1, "3": 2, "5": 3, "8": 1 } 7 | 8 | // SOL-1 9 | getMaxKey_1 = obj => 10 | Object.keys(obj).reduce((a, b) => (obj[a] > obj[b] ? a : b)) 11 | 12 | console.log(getMaxKey_1(myObj)) // => 5 13 | 14 | console.log(getMaxKey_1(myObj2)) // => 5 // Does not give the first key with max value i.e. 1 15 | 16 | // SOL-2 17 | getMaxKey_2 = obj => { 18 | // the variable max is the highest value that I have in the entire object 19 | let max = Math.max(...Object.keys(obj).map(i => obj[i])) 20 | 21 | // So, now I have to find the key given this highest value 22 | return Object.keys(obj).filter(i => obj[i] === max)[0] 23 | } 24 | 25 | // console.log(getMaxKey_2(myObj)); // => 5 26 | 27 | // In case you have many equal values and not only one maximum: 28 | // The below will return the first key with max value i.e. 1 for input object = { '1': 3, '2': 1, '3': 2, '5': 3, '8': 1 } 29 | getMaxKey_3 = obj => { 30 | return Object.keys(obj).filter(i => { 31 | return obj[i] === Math.max(...Object.values(obj)) 32 | })[0] 33 | } 34 | 35 | console.log(getMaxKey_3(myObj)) 36 | 37 | console.log(getMaxKey_3(myObj2)) 38 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/json-accessing-json-objects.js: -------------------------------------------------------------------------------- 1 | // SOLULTION - 1 SIMPLE STRAIGHT-FORWARD METHOD - The below is a JSON String 2 | var data1 = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}'; 3 | 4 | 5 | // JSON.parse() function of Javascript to convert JSON String into Javascript JSON object. 6 | var json = JSON.parse(data1); 7 | 8 | console.log(json.name); 9 | 10 | // SOLUTION - 2 - If however, the data is in the following format, and simpley JSON.parse() is not giving me the desired result - MOST PROBABLY BECAUSE - "it is most likely not a JSON string anymore, but already a JavaScript object." - THEN FIRST USE stringify() 11 | // https://stackoverflow.com/questions/38380462/syntaxerror-unexpected-token-o-in-json-at-position-1 12 | 13 | var data = { 14 | "name": "mkyong", 15 | "age": 30, 16 | "address": { 17 | "streetAddress": "88 8nd Street", 18 | "city": "New York" 19 | }, 20 | "phoneNumber": [ 21 | { 22 | "type": "home", 23 | "number": "111 111-1111" 24 | }, 25 | { 26 | "type": "fax", 27 | "number": "222 222-2222" 28 | } 29 | ] 30 | } 31 | 32 | // JSON.stringify() converts a JavaScript object to a string representation of it, which is the opposite of what JSON.parse() does. I was getting the SyntaxError ( "Unexpected token o in JSON at position 1" - while directly applying JSON.parse() ) - because you were trying to parse something that was already an object. 33 | // the first parameters of function JSON.parse should be a JSON String, and your data is a JavaScript object, so it will convert to a String [object object], you should use JSON.stringify before pass the data 34 | var newData = JSON.stringify(data) 35 | 36 | var json = JSON.parse(newData); 37 | 38 | console.log(json.name); -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/map-Implementation-On-Objects.js: -------------------------------------------------------------------------------- 1 | // The map() method creates a new array with the results of calling a provided function on every element in this array. 2 | 3 | // Problem - 1 We’ve an array of products, that has two properties: `id` and `name`. I want to get all ids, wih map() method: 4 | 5 | let products = [ 6 | { 7 | id: 0, 8 | name: 'Product 1' 9 | }, 10 | { 11 | id: 1, 12 | name: 'Product 2' 13 | } 14 | ]; 15 | 16 | let productsIds = products.map((item) => { 17 | return item.id; 18 | }) 19 | 20 | // console.log(productsIds); 21 | 22 | /* Problem-2 23 | 24 | The map() mehod's syntax is as below 25 | 26 | let newArr = oldArr.map((val, index, arr) => { 27 | // return element to new Array 28 | }); 29 | 30 | newArr — the new array that is returned 31 | oldArr — the array to run the map function on 32 | val — the current value being processed 33 | index — the current index of the value being processed 34 | arr — the original array 35 | 36 | Create an object from a given array and the given array is as below 37 | [1,2,3,4]; 38 | 39 | */ 40 | 41 | let arr = [1,2,3,4]; 42 | 43 | let obj = arr.map((val, index, arr) => { 44 | return { 45 | VALUE : val, 46 | INDEX: index 47 | } 48 | }) 49 | 50 | // console.log(obj); 51 | 52 | // Problem-2 - Using map() return full name from the given array 53 | var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}]; 54 | 55 | let newArr = []; 56 | 57 | oldArr.map((item, index) => { 58 | item.full_name = [item.first_name, item.last_name].join(' '); 59 | return item; 60 | }); 61 | console.log(oldArr); -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/map-over-arr-of-objects-to-return-value-conditionally-as-an-ar.js: -------------------------------------------------------------------------------- 1 | /* Problem - I have the data1 and data2, both arrays. 2 | 3 | But from data1, I need only the _id field names in the below format which has a correponding 'name' field that matches data2's elements. 4 | 5 | So in this example given data2 I need from data1 the following format 6 | 7 | 8 | [ { _id: '5e38719e0a31f475afc236b7' }, 9 | { _id: '5e39801f158ee52f86cede99' } ] 10 | 11 | As these are the _id's which has a name field that matches the name field I have got from data2 array 12 | 13 | Very important when mapping between multiple mongo data schemas. 14 | 15 | */ 16 | 17 | 18 | const data1 = [ 19 | { 20 | _id: "5e39801f158ee52f86cede99", 21 | stopId: 4, 22 | name: "TTy", 23 | latitude: 20.123, 24 | longitude: 12.325 25 | }, 26 | { 27 | _id: "5e397c3e2291ca26fc13d507", 28 | stopId: 3, 29 | name: "test nagar", 30 | latitude: 10.1212, 31 | longitude: 11.1212 32 | }, 33 | { 34 | _id: "5e3871a80a31f475afc236b8", 35 | stopId: 2, 36 | name: "Stop - 22", 37 | latitude: 19.101978, 38 | longitude: 72.884701 39 | }, 40 | { 41 | _id: "5e38719e0a31f475afc236b7", 42 | stopId: 1, 43 | name: "Stop - 1", 44 | latitude: 19.101978, 45 | longitude: 72.884701 46 | } 47 | ]; 48 | 49 | const data2 = ["Stop - 1", "TTy"]; 50 | 51 | const getArrOfObjectIds = (data1, data2) => { 52 | let newArr = []; 53 | data2.map(i => { 54 | data1.map(j => { 55 | if (i === j.name) { 56 | const item = { _id: j._id }; 57 | newArr.push(item); 58 | } 59 | }); 60 | }); 61 | return newArr; 62 | }; 63 | 64 | console.log(getArrOfObjectIds(data1, data2)); 65 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/map-recduce-filter.js: -------------------------------------------------------------------------------- 1 | var personnel = [ 2 | { 3 | id: 5, 4 | name: "Luke Skywalker", 5 | pilotingScore: 98, 6 | shootingScore: 56, 7 | isForceUser: true, 8 | }, 9 | { 10 | id: 82, 11 | name: "Sabine Wren", 12 | pilotingScore: 73, 13 | shootingScore: 99, 14 | isForceUser: false, 15 | }, 16 | { 17 | id: 22, 18 | name: "Zeb Orellios", 19 | pilotingScore: 20, 20 | shootingScore: 59, 21 | isForceUser: false, 22 | }, 23 | { 24 | id: 15, 25 | name: "Ezra Bridger", 26 | pilotingScore: 43, 27 | shootingScore: 67, 28 | isForceUser: true, 29 | }, 30 | { 31 | id: 11, 32 | name: "Caleb Dume", 33 | pilotingScore: 71, 34 | shootingScore: 85, 35 | isForceUser: true, 36 | }, 37 | ]; 38 | 39 | // PROBLEM STATEMENT - get the total score of force users only. The ans would be 420 40 | 41 | let forceSum = personnel.filter(item => item.isForceUser) 42 | .map(item => item.pilotingScore + item.shootingScore) 43 | .reduce((accum, current) => accum + current, 0) 44 | 45 | 46 | console.log(forceSum); 47 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/max-min-from-array-of-objects.js: -------------------------------------------------------------------------------- 1 | /*Finding Minimum and Maximum values in an Array of Objects 2 | 3 | We have an array of objects like below in the variable called data 4 | 5 | [ 6 | {x: 1, y: 14830}, 7 | {x: 2, y: 85055}, 8 | {x: 3, y: 03485}, 9 | {x: 4, y: 57885}, 10 | // ... 11 | ] 12 | 13 | Build two function calls — one for the minimum Y value, and one for the maximum Y value. 14 | 15 | */ 16 | 17 | // first create the variable data which is an array of objects with random set of 1000 records 18 | 19 | const data = []; 20 | for (let x = 0; x < 1000; x++) { 21 | data.push({ x: x, y: Math.floor(Math.random() * 1000) }); 22 | } 23 | // console.log(data); 24 | 25 | // Note in the below function the accumulator is the the variable minY and the first value of this is set to be data[0].y 26 | 27 | function getMinYValue () { 28 | return data.reduce((minY, thisObj) => thisObj.y < minY ? thisObj.y : minY, data[0].y) 29 | } 30 | 31 | function getMaxYValue() { 32 | return data.reduce((maxY, thisObj) => thisObj.y > maxY ? thisObj.y : maxY, data[0].y); 33 | } 34 | 35 | // Using Map and spread operaton. First get all the y values from each of the objects within data. 36 | 37 | function getYOnly () { 38 | return data.map( YVal => YVal.y ); 39 | } 40 | 41 | 42 | function getMinValueAlt () { 43 | return Math.min(...getYOnly()); 44 | } 45 | 46 | function getMaxValueAlt () { 47 | return Math.max(...getYOnly()); 48 | } 49 | 50 | console.log(getMaxValueAlt()); 51 | 52 | console.log(getMinValueAlt()); -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/merge-objects-with-spread-operator.js: -------------------------------------------------------------------------------- 1 | // Latest ES6 2 | const obj1 = { 3 | a: 1, 4 | b: 2, 5 | } 6 | 7 | const obj2 = { 8 | c: 3, 9 | d: 4, 10 | } 11 | 12 | const merged = { ...obj1, ...obj2 } 13 | 14 | // console.log(merged); // => { a: 1, b: 2, c: 3, d: 4 }s 15 | 16 | /** There's no limit to the number of objects you can merge. 17 | * Later properties overwrite earlier properties with the same name i.e. if a key-name is same the right-to-left priority takes over. */ 18 | const allRules = { ...obj1, ...obj2, ...obj3 } 19 | 20 | // ECMAScript 2015 (ES6) Standard Method 21 | 22 | Object.assign(obj1, obj2) 23 | 24 | /** There's no limit to the number of objects you can merge. 25 | * All objects get merged into the first object. 26 | * Only the object in the first argument is mutated and returned. 27 | * Later properties overwrite earlier properties with the same name. */ 28 | const allRules = Object.assign({}, obj1, obj2, obj3, etc) 29 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/nested-object-prob-1.js: -------------------------------------------------------------------------------- 1 | // Let’s take this nested object as an example. 2 | 3 | const user = { 4 | id: 101, 5 | email: 'jack@dev.com', 6 | personalInfo: { 7 | name: 'Jack', 8 | address: { 9 | line1: 'westwish st', 10 | line2: 'washmasher', 11 | city: 'wallas', 12 | state: 'WX' 13 | } 14 | } 15 | } 16 | // To access the name of the our user, we’ll write 17 | 18 | const name = user.personalInfo.name; 19 | console.log(name); 20 | const userCity = user.personalInfo.address.city; 21 | console.log(userCity); 22 | 23 | // But, for some reason, if our user's personal info is not available, the object structure will be like this, 24 | 25 | const user1 = { 26 | id: 101, 27 | email: 'jack@dev.com' 28 | } 29 | // console.log(user1.personalInfo.name); //=> TypeError: Cannot read property 'name' of undefined 30 | 31 | // Then to access the name property and also not throw "Cannot read property 'name' of undefined." - do the following in plain vanilla js 32 | 33 | const name1 = user1 && user1.personalInfo ? user1.personalInfo.name : null; 34 | // console.log(name1); // => null 35 | 36 | // This is okay if your nested structure is simple, but if you have your data nested 5 or 6 levels deep, then your code will look really messy like this, 37 | 38 | let city; 39 | if ( 40 | data && data.user && data.user.personalInfo && 41 | data.user.personalInfo.addressDetails && 42 | data.user.personalInfo.addressDetails.primaryAddress 43 | ) { 44 | city = data.user.personalInfo.addressDetails.primaryAddress; 45 | } 46 | 47 | // Oliver Steele's Nested Object Access Pattern - for the same data above, if I have to access the 'name' property and not throw any error. But ofcourse with each more nesting level the parenthesis will continue to grow. 48 | 49 | const name2 = (((user1 || {}).personalInfo) || {}).name; 50 | console.log(name2); 51 | 52 | /* Explanation - 53 | With this notation, you'll never run into Cannot read property 'name' of undefined. You basically check if user exists, if not, you create an empty object on the fly. This way, the next level key will always be accessed from an object that exists or an empty object, but never from undefined. 54 | 55 | Unfortunately, you cannot access nested arrays with this trick 56 | */ -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/nested-objects-4.js: -------------------------------------------------------------------------------- 1 | // Problems statement - from the below json, print only the products versions in an arry 2 | 3 | var myData = 4 | { 5 | "abc": 6 | [ 7 | [ 8 | {"prod_ver" : "prod-1_ver 1"}, 9 | {"prod_ver" : "prod-1_ver 2"}, 10 | ], 11 | [ 12 | {"prod_ver" : "prod-2_ver 1"}, 13 | {"prod_ver" : "prod-2_ver 2"}, 14 | ], 15 | [ 16 | {"prod_ver" : "prod-3_ver 1"}, 17 | {"prod_ver" : "prod-3_ver 2"}, 18 | ] 19 | ] 20 | }; 21 | 22 | printVersion = (myJSONObject) => { 23 | var versions = []; 24 | 25 | for (let i = 0; i < myJSONObject.abc.length; i++) { 26 | 27 | // assign variable for the current product 28 | let product = myJSONObject.abc[i] 29 | 30 | for (let j = 0; j < product.length; j++) { 31 | versions.push(product[j].prod_ver); 32 | } 33 | } 34 | return versions; 35 | } 36 | 37 | console.log(printVersion(myData)); -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/nested-objects-prob-2.js: -------------------------------------------------------------------------------- 1 | const userInfo = { 2 | firstName: 'Avi', 3 | lastName: 'Flombaum', 4 | 5 | company: { 6 | name: 'Flatbook Labs', 7 | jobTitle: 'Developer Apprentice' 8 | }, 9 | 10 | friends: [{ 11 | firstName: 'Joe', 12 | lastName: 'Burgess', 13 | company: { 14 | name: 'Flatbook Labs', 15 | jobTitle: 'Developer Apprentice' 16 | } 17 | }, 18 | { 19 | firstName: 'Gabe', 20 | lastName: 'Jackson', 21 | company: { 22 | name: 'Flatbook Labs', 23 | jobTitle: 'Lead Developer' 24 | } 25 | }], 26 | 27 | projects: [{ 28 | title: 'Flatbook', 29 | description: 'The premier Flatiron School-based social network in the world.' 30 | }, 31 | { 32 | title: 'Scuber', 33 | description: 'A burgeoning startup helping busy parents transport their children to and from all of their activities on scooters.' 34 | }] 35 | }; 36 | 37 | // Whats the first name of his first friend: 38 | const a = userInfo.friends[0].firstName; 39 | console.log(a); // => Joe 40 | 41 | // Whats the title of his second project: 42 | const b = userInfo.projects[1].title; 43 | console.log(b); 44 | 45 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/number-as-key-in-obj-is-it-allowed.md: -------------------------------------------------------------------------------- 1 | First look at the below 2 | 3 | ```js 4 | var obj = { 5 | a: "b", 6 | c: "d" 7 | }; 8 | 9 | var obj1 = { 10 | 1: "b", 11 | 2: "d" 12 | }; 13 | 14 | console.log(obj.a); 15 | console.log(obj1."1"); // SyntaxError: missing ) after argument list 16 | console.log(obj1."1"); // SyntaxError: Unexpected string 17 | console.log(obj1."1"); // b 18 | 19 | ``` 20 | 21 | ### Is there any way to use a numeric type as an object key? 22 | 23 | No, this is not possible. The key will always be converted to a string. See Property Accessor docs 24 | 25 | Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method. 26 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/object-with-nested-arrays-values.js: -------------------------------------------------------------------------------- 1 | var foo = { 2 | bar: ['foo', 'bar', 'baz'] 3 | }; 4 | 5 | // access 6 | 7 | console.log(foo.bar[2]); // => 'baz' 8 | 9 | console.log(foo['bar'][2]); // => 'baz' 10 | 11 | // to dynamically iterate over the nested array 'bar' 12 | let array = foo.bar; 13 | for (let i of array) { 14 | console.log(i); 15 | } 16 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/push-nested-array-of-objects-to-another-2.js: -------------------------------------------------------------------------------- 1 | /* A slightly different version of the other push-nested Arraay case - Interview question faced on 14-July-2018- at Thrymer Software, Hyderabad 2 | 3 | myProjectsArr is an array of objects, within which I also have the property 'employee' which is also an array of objects. 4 | 5 | Write a function to push 2 employees to each of the project with myProjectsArr . 6 | 7 | Note, unlike the other implementation, here the myEmployeeArr alreay has a property for projId, so I will only push to those porjects which matches this projId. 8 | 9 | Also note, that 10 | 11 | */ 12 | 13 | var myProjectsArr = [{ 14 | projId: '1', 15 | projName: 'A', 16 | employee: [] 17 | 18 | }, 19 | { 20 | projId: '2', 21 | projName: 'B', 22 | employee: [] 23 | 24 | } 25 | ] 26 | 27 | var myEmployeeArr = [{ 28 | employeeId: 1, 29 | employeeName: 'abc', 30 | projId: '1' 31 | }, 32 | { 33 | employeeId: 2, 34 | employeeName: 'cde', 35 | projId: '1' 36 | }, 37 | { 38 | employeeId: 3, 39 | employeeName: 'abc', 40 | projId: '2' 41 | }, 42 | { 43 | employeeId: 4, 44 | employeeName: 'cde', 45 | projId: '2' 46 | } 47 | ] 48 | 49 | console.log(myProjectsArr[0].employee); // => [] 50 | console.log(myProjectsArr[1].employee); // => [] 51 | 52 | // Generic function to add the nested array (which is itself an array of objects ) to the outer projectsArr ( which is and arr of objects ) 53 | 54 | addEmployee = (projectsArr, employeesArr) => { 55 | 56 | for (let i in projectsArr) { 57 | 58 | let nestedEmployeeArr = projectsArr[i].employee; 59 | 60 | for (let j of employeesArr) { 61 | if (j.projId === projectsArr[i].projId) { 62 | nestedEmployeeArr.push(j) 63 | } 64 | } 65 | } 66 | return projectsArr; 67 | } 68 | 69 | // Execute the function on my set of data 70 | 71 | addEmployee(myProjectsArr, myEmployeeArr); 72 | 73 | console.log(myProjectsArr[0].employee); 74 | console.log(myProjectsArr[1].employee); -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/push-nested-array-of-objects-to-another.js: -------------------------------------------------------------------------------- 1 | // Interview question faced on 14-July-2018- at Thrymer Software, Hyderabad 2 | // myProjectsArr is an array of objects, within which I also have the property 'employee' which is also an array of objects. 3 | // Write a function to push 2 employees to each of the project with myProjectsArr 4 | 5 | var myProjectsArr = [{ 6 | projId: '1', 7 | projName: 'A', 8 | employee: [] 9 | }, 10 | { 11 | projId: '2', 12 | projName: 'B', 13 | employee: [] 14 | } 15 | ] 16 | 17 | var myEmployeeArr = [{ 18 | employeeId: 1, 19 | employeeName: 'abc' 20 | }, 21 | { 22 | employeeId: 2, 23 | employeeName: 'cde' 24 | }, 25 | { 26 | employeeId: 3, 27 | employeeName: 'abc' 28 | }, 29 | { 30 | employeeId: 4, 31 | employeeName: 'cde' 32 | } 33 | ] 34 | 35 | console.log(myProjectsArr[0].employee); 36 | console.log(myProjectsArr[1].employee); 37 | 38 | // Generic function to add the nested array (which is itself an array of objects ) to the outer projectsArr ( which is and arr of objects ) 39 | 40 | addEmployee = (projectsArr, employeesArr ) => { 41 | 42 | for (let i in projectsArr) { 43 | 44 | let nestedEmployeeArr = projectsArr[i].employee; 45 | 46 | nestedEmployeeArr.push(employeesArr.splice(0, 2)) 47 | } 48 | return projectsArr; 49 | } 50 | 51 | // Execute the function on my set of data 52 | 53 | addEmployee(myProjectsArr, myEmployeeArr); 54 | 55 | console.log(myProjectsArr[0].employee); 56 | console.log(myProjectsArr[1].employee); 57 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/pushing_new_key_value_pair_to_existing_obj.js: -------------------------------------------------------------------------------- 1 | var obj = { key1: "value1", key2: "value2" }; 2 | // console.log(Object.assign(obj, { key3: "value3" })); 3 | 4 | /* 5 | Output - 6 | 7 | { key1: 'value1', key2: 'value2', key3: 'value3' } 8 | 9 | */ 10 | 11 | /* Notes and Explanation of this very important Object.assign() method 12 | 13 | Object.assign(dest, src1, src2, ...) merges objects. 14 | 15 | It overwrites dest with properties and values of (however many) source objects, then returns dest. 16 | 17 | The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. 18 | 19 | 20 | */ 21 | 22 | // ES-6 way - Note , here ever 'let' will NOT work, as it will not let me change 'obj' again 23 | 24 | var obj = { key1: "value1", key2: "value2" }; 25 | var pair = { key3: "value3" }; 26 | obj = { ...obj, ...pair }; 27 | console.log(obj); 28 | -------------------------------------------------------------------------------- /Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/sort-array-of-objects.js: -------------------------------------------------------------------------------- 1 | // Sorting an array of JavaScript objects 2 | 3 | // Problem statement - Create a function to sort the objects by the price property in ascending order 4 | 5 | var homes = [ 6 | { 7 | h_id: "3", 8 | city: "Dallas", 9 | state: "TX", 10 | zip: "75201", 11 | price: "162500", 12 | }, 13 | { 14 | h_id: "4", 15 | city: "Bevery Hills", 16 | state: "CA", 17 | zip: "90210", 18 | price: "319250", 19 | }, 20 | { 21 | h_id: "5", 22 | city: "New York", 23 | state: "NY", 24 | zip: "00010", 25 | price: "962500", 26 | }, 27 | ] 28 | 29 | sortedHome = arr => { 30 | return arr.sort((a, b) => { 31 | return parseFloat(a.price) - parseFloat(b.price) 32 | }) 33 | } 34 | 35 | // console.log(sortedHome(homes)); 36 | 37 | /* Given the price is mentioned as a string, I have to use parseFloat() 38 | 39 | The parseFloat() function parses a string and returns a floating point number. 40 | 41 | This function determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.*/ 42 | 43 | // Alternative - I could also use Number 44 | sortedHome1 = arr => { 45 | return arr.sort((a, b) => Number(a.price) - Number(b.price)) 46 | } 47 | 48 | console.log(sortedHome(homes)) 49 | -------------------------------------------------------------------------------- /Promise-Notes/callback-hell-examples.js: -------------------------------------------------------------------------------- 1 | 2 | setTimeout((changeMaker) => { 3 | let list = changeMaker + ', '; 4 | 5 | setTimeout((changeMaker) => { 6 | list += changeMaker + ', '; 7 | 8 | setTimeout((changeMaker) => { 9 | list += changeMaker + ', '; 10 | 11 | setTimeout((changeMaker) => { 12 | list += changeMaker + ', '; 13 | 14 | setTimeout((changeMaker) => { 15 | list += changeMaker 16 | 17 | console.log(list); 18 | }, 1, 'Travis Kalanick'); 19 | }, 1, 'MarkZuckerberg'); 20 | }, 1, 'SteveWoz'); 21 | }, 1, 'SteveJobs'); 22 | }, 1, 'BillGates'); 23 | 24 | 25 | /* Looking at the above, setTimeout gets a callback function that executes after one millisecond. The last parameter just feeds the callback with data, i.e the argument 'changeMaker' . This is like an Ajax call except the return 'changeMaker' parameter would come from the server. 26 | 27 | I am gathering a list of changeMakers through asynchronous code. Each callback gives me a single 'changeMaker' name and I append that to the list. */ 28 | 29 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | Collection of common JavaScript problems, for my own learning and practicing 2 | -------------------------------------------------------------------------------- /Regexp/pigLatin-with-match.js: -------------------------------------------------------------------------------- 1 | /* 2 | Problem - Translate the provided string to pig latin. 3 | 4 | Pig Latin takes the first consonant (or consonant cluster), which may occur at any place in the word, of an English word, moves it to the end of the word and suffixes an "ay". 5 | 6 | SO, If the first character is a vowel, then take that whole word and add 'way' at the end. Otherwise comes the tricky part, take the consonant(s) before the first vowel and move it to the end and add 'ay'. 7 | 8 | If a word begins with a vowel you just add "way" to the end. 9 | 10 | translatePigLatin("california") should return "aliforniacay". 11 | translatePigLatin("paragraphs") should return "aragraphspay". 12 | translatePigLatin("glove") should return "oveglay". 13 | translatePigLatin("algorithm") should return "algorithmway". 14 | translatePigLatin("eight") should return "eightway". 15 | Should handle words where the first vowel comes in the end of the word. 16 | Should handle words without vowels. 17 | */ 18 | 19 | translatePigLatin = str => { 20 | 21 | const re = /[aeiou]/ig 22 | 23 | if (str[0].match(re)) { 24 | return str + 'way' 25 | } 26 | // now the case when at least on vowel are there in the string 27 | else if ( str.match(re) !== null ) { 28 | let firstVowelIndex = str.indexOf(str.match(re)[0] || 0) 29 | return ( str.substr(firstVowelIndex) + str.substr(0, firstVowelIndex) + 'ay' ) 30 | } 31 | // the case when there's no vowel at all in the string, then just append 'ay' at the end 32 | else { 33 | return str + 'ay' 34 | } 35 | } 36 | 37 | 38 | // TESTS 39 | 40 | console.log(translatePigLatin("california") === "aliforniacay" ) 41 | console.log(translatePigLatin("paragraphs") === "aragraphspay" ) 42 | console.log(translatePigLatin("glove") === "oveglay" ) 43 | console.log(translatePigLatin("algorithm") === "algorithmway" ) 44 | console.log(translatePigLatin("eight") === "eightway" ) 45 | // the below is the case of word where there is no vowels 46 | console.log(translatePigLatin("rbght") === "rbghtay") 47 | 48 | /* 1. RETURN VALUE OF match() - If the string matches the expression, it will return an Array containing the entire matched string as the first element, followed by any results captured in parentheses. If there were no matches, null is returned. 49 | 50 | let str2 = "Fame is the thirst of youth"; 51 | 52 | let result = str2.match(/the/i); 53 | 54 | console.log(result); // => [ 'the', index: 8, input: 'Fame is the thirst of youth' ] 55 | 56 | */ -------------------------------------------------------------------------------- /Regexp/regExp-Method-Impotant-for-String.js: -------------------------------------------------------------------------------- 1 | /* PROB-1 search() 2 | 3 | str.search() returns the position of the first match or -1 if none found: 4 | So if Only a vowel is found in position-index-0 of the string, then '0' is returned. If the vowel is found in position-index-2 then '2' is returned. 5 | 6 | */ 7 | 8 | let str1 = 'My Name is Rohan' 9 | 10 | var vowelSearchResult = str1.search(/[aeiuo]/); 11 | 12 | // console.log(vowelSearchResult) // => 4 13 | 14 | 15 | -------------------------------------------------------------------------------- /Regexp/replace-method-basics.js: -------------------------------------------------------------------------------- 1 | /* replace() - Meaning of $1 $2 $3 etc.. 2 | https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter 3 | 4 | $n - Where n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. Note that this is 1-indexed. 5 | 6 | \w+ - Matches 0 or more word(s) ( captured by (\w+) ) . 7 | 8 | (\w+) - The regular braces in "(\w+)" is called capturing parentheses, and this match in the replace() is called "parenthesized-submatch" - this will make the match and remembers the match. 0 or more word(s) 9 | 10 | Meaning, when I have one of more parenthesized-submatch in my regular expression, then $1 will capture the first parenthesized-submatch, then $2 will capture the second parenthesized-submatch 11 | 12 | */ 13 | 14 | // super basic implementation of $n - Switching words in a string - given "Rohan Paul" output "Paul, Rohan" 15 | 16 | switchWords = str => str.replace(/(\w+)\s(\w+)/, `$2, $1`) 17 | 18 | console.log(switchWords("Rohan Paul")) -------------------------------------------------------------------------------- /Regexp/search-method-basics.js: -------------------------------------------------------------------------------- 1 | let aString = 'Mozilla'; 2 | 3 | console.log(aString.search(/[aeiou]/)); // => 1 4 | 5 | -------------------------------------------------------------------------------- /Regexp/test-method-basics.js: -------------------------------------------------------------------------------- 1 | // The test() method executes a search for a match between a regular expression and a specified string. Returns true or false. test() returns a boolean, unlike the String.prototype.search() method, which returns the index (or -1 if not found). 2 | // Simple example that tests if "hello" is contained at the very beginning of a string, returning a boolean result. 3 | 4 | var str = 'hello world!'; 5 | 6 | var result = /^hello/.test(str); 7 | 8 | console.log(result); // true 9 | 10 | /* 11 | ^ Matches the position at the beginning of the input string. If the RegExp object's Multiline property is set, ^ also matches the position following '\n' or '\r'. See the opposite functionality of this function - check-if-String-has-only-numbers.js 12 | 13 | 14 | PAUL VERY IMP - The same '^' char is used for as A negative range characters. Matches any character not in the specified range. For example, '[^a-z]' matches any character not in the range 'a' through 'z'. BUT NOTICE TO USE IT AS A NEGATIVE-RANGE-CHARACTER, I HAVE TO PUT IT INSIDE THE SQUARE BRACKET. */ -------------------------------------------------------------------------------- /String/frequency-of-occurance-of-letters.js: -------------------------------------------------------------------------------- 1 | // Problem - Given a string output a hashMap showing index positions of each letter occuring in the string. And the index positions should be an array 2 | 3 | letterFrequencyMap = str => { 4 | 5 | let letterMap = {} 6 | 7 | str.forEach((letter, index) => { 8 | 9 | letterMap[letter] = letterMap[letter] || []; 10 | letterMap[letter].push(index); 11 | }) 12 | 13 | return letterMap; 14 | } 15 | 16 | let str = "rohhanr".split('') 17 | 18 | console.log(str); 19 | 20 | console.log(letterFrequencyMap(str)); 21 | 22 | /*Output 23 | 24 | [ 'r', 'o', 'h', 'h', 'a', 'n', 'r' ] 25 | 26 | { r: [ 0, 6 ], o: [ 1 ], h: [ 2, 3 ], a: [ 4 ], n: [ 5 ] } 27 | 28 | */ -------------------------------------------------------------------------------- /String/longest_Substring-of-two-strings.js: -------------------------------------------------------------------------------- 1 | /*The function, named lcs (longest common substring) , will return a string as small as a single character. "123" and "345" will return "3" 2 | 3 | Algo >> A> Initialize the longestSubStr to be an empty string. For each letter of s1, check each of letters of s2. So run 2 for loops 4 | 5 | B> And for each matching letter found between s1 and s2 - run a while loop to check how far that match goes. 6 | 7 | C> From within the while loop, return the max-matched-string and update the initial longestSubStr each a time longer substr is found from running the while loop 8 | 9 | */ 10 | 11 | longestSubstring = (s1, s2) => { 12 | 13 | let longestSubstring = "", tempLongestSubsStr = ""; 14 | 15 | for (let i = 0; i < s1.length; i++) { 16 | 17 | for (let j = 0; j < s2.length; j++) { 18 | 19 | if (s1[i] === s2[j]) { 20 | 21 | tempLongestSubsStr = s1[i]; 22 | 23 | let subLength = 1; 24 | 25 | // run a while loop to check how far that match goes. Keep going until the corresponding letters matches 26 | 27 | while (i + subLength < s1.length && j + subLength < s2.length && s1[i+subLength] === s2[j+subLength]) { 28 | 29 | tempLongestSubsStr += s1[i+subLength] 30 | 31 | subLength++; 32 | } 33 | 34 | // If this tempLongestSubStr is longer than longestSubstring, update longestSubstring before running the next iteration of the for loop 35 | if (tempLongestSubsStr.length > longestSubstring.length) { longestSubstring = tempLongestSubsStr} 36 | 37 | } 38 | } 39 | } 40 | return longestSubstring; 41 | } 42 | 43 | console.log(longestSubstring("rohan", "bichan")); -------------------------------------------------------------------------------- /String/no-of-occurance-of-char-in-string.js: -------------------------------------------------------------------------------- 1 | /* count the number of occurances of a character in a string 2 | The best option, which should also be the fastest is using RegExp - owing to the native RegEx engine*/ 3 | 4 | // count no of times "o" occurs in the below str 5 | 6 | // SOL-1 7 | let myStr = "this is foo bar" 8 | 9 | let count1 = myStr.match((/o/g) || []).length; 10 | 11 | console.log(count1); // => 2 12 | 13 | 14 | // SOL-2 15 | let count2 = myStr.split("o").length - 1 16 | 17 | // console.log(myStr.split("o")); // => [ 'this is f', '', ' bar' ] 18 | 19 | console.log(count2); // => 2 20 | 21 | 22 | // SOL-3 23 | let count3 = 0 24 | 25 | for (let i = 0; i < myStr.length; i++) { 26 | if (myStr[i] === "o") { count3++ } 27 | } 28 | console.log(count3); // => 2 29 | 30 | // SOL-4 31 | let count4 = 0; 32 | 33 | myStr.split('').map(s => s === "o" ? count4++ : count4) 34 | 35 | console.log(count4); // => 2 36 | 37 | // SOL - 5 38 | let count5 = myStr.split('').map((s, i) => { 39 | if ( s === "o" ) return i 40 | }).filter(Boolean).length; 41 | 42 | console.log(count5); // => 2 43 | 44 | // SOL-6 45 | let count6 = myStr.length - myStr.replace(/o/g, '').length; 46 | 47 | console.log(count6); // => 2 -------------------------------------------------------------------------------- /String/padded-Number.js: -------------------------------------------------------------------------------- 1 | /* Padded Number 2 | In this challenge, an array is provided and stored in a variable, create a function which evaluates the strings in the array by adding a preceding 0 to single numbers (6 => 06, 5 => 05). Double figures remain as is. */ 3 | 4 | const paddingNum = arr => { 5 | return arr.map(num => { 6 | return +num < 10 ? `0${num}` : num 7 | }) 8 | } 9 | 10 | let nums = ['2', '4', '25', '10', '3']; 11 | 12 | console.log(paddingNum(nums)); -------------------------------------------------------------------------------- /String/shift-each-letter-by-number.-of-position.js: -------------------------------------------------------------------------------- 1 | /* how to shift each letter in the given string N places down in the alphabet? Punctuation, spaces, and capitalization should remain intact. For example if the string is "ac" and num is 2 the output should be "ce". */ 2 | 3 | CaesarCipher = (str, num) => { 4 | 5 | str = str.toUpperCase(); 6 | 7 | let resultStr = ''; 8 | let charAfterNumShift = 0; 9 | 10 | for (let i = 0; i < str.length; i++) { 11 | 12 | charAfterNumShift = (str[i].charCodeAt()) + num 13 | 14 | resultStr += String.fromCharCode(charAfterNumShift); 15 | } 16 | 17 | return resultStr; 18 | } 19 | 20 | /* The fromCharCode function doesn't operate on strings, it operates on the global String object. like so 21 | String.fromCharCode(65, 66, 67); // "ABC" */ 22 | 23 | console.log(CaesarCipher('ac', 2)); // => ce 24 | 25 | 26 | /* SOLUTION-2 - Note - Unicode for English letters A-Z ranges from 65 (for A) to 90 (for Z) ( https://unicodelookup.com/ ) 27 | 28 | */ 29 | 30 | CaesarCipher2 = (str, num) => { 31 | 32 | str = str.toUpperCase(); 33 | let charAfterNumShift = 0; 34 | 35 | return str.split('').map(elem => { 36 | charAfterNumShift = elem.charCodeAt() + num; 37 | 38 | /* Now I need to take into account fact of shifting last letters in alphabet back to beginning. So, for (Z + 1 )-th number from the above result, I should return A. For (Z+2)-th number, I should return B and so on and so forth. 39 | Meaning, if I get 91 I have to convert that back to 65, If I get 92, I have to convert that back to 66 and so on. So, for 91, the conversiton calculation is >> 65 + ( 91 - 90 -1) giving me 65 40 | For 92 >> 65 + ( 92 - 90 - 1) giving me 66 41 | */ 42 | if (charAfterNumShift > 90) { 43 | charAfterNumShift = 65 + (charAfterNumShift - 90 - 1); 44 | } 45 | 46 | return String.fromCharCode(charAfterNumShift); 47 | }).join('') 48 | } 49 | 50 | console.log(CaesarCipher2('ac', 2)); // => ce 51 | console.log(CaesarCipher2('yz', 2)); // => ce -------------------------------------------------------------------------------- /String/string-related-misc-problems.js: -------------------------------------------------------------------------------- 1 | /* Problem Statement 1 - 2 | You have a string with several sentences, one of which includes a list of items. The list begins with a colon (:) and ends with a period (.), and each item is separated by a comma. You want to extract just the list. 3 | 4 | Before: 5 | This is a list of items: cherries, limes, oranges, apples. 6 | After: 7 | ['cherries','limes','oranges','apples'] 8 | */ 9 | 10 | var sentence = 'This is one sentence. This is a sentence with a list of items:' + 11 | 'cherries, oranges, apples, bananas. That was the list of items.'; 12 | 13 | var start = sentence.indexOf(':'); 14 | var end = sentence.indexOf('.', start + 1); 15 | 16 | var extractedList = sentence.substring((start + 1), end).split(','); 17 | 18 | extractedList.forEach(function(elmnt, indx, arry) { 19 | arry[indx] = elmnt.trim(); 20 | }) 21 | 22 | console.log(extractedList); 23 | 24 | // Problem Statement 2 - swap names so the last name is first 25 | var name = "Abe Lincoln"; 26 | var re = /(\S+)\s(\S+)/; 27 | 28 | // Alternatively, I could also define re as /^(\w+)\s(\w+)$/; 29 | var swappedName = name.replace(re, "$2, $1"); 30 | console.log(swappedName); 31 | 32 | // Alternative solution to Problem-2 33 | var name = "abe Lincoln"; 34 | var re = /^(\w+)\s(\w+)$/; 35 | var result = re.exec(name); 36 | var swappedName = result[2] + ", " + result[1]; 37 | -------------------------------------------------------------------------------- /String/string-splice-method.js: -------------------------------------------------------------------------------- 1 | // Adding A Splice() Method To The Javascript String Prototype 2 | 3 | /* Algo 4 | 5 | String.split( "" ) - String to character array. 6 | Array.join( "" ) - Character array to string. 7 | 8 | Convert string to character array. 9 | Perform array-based splicing. 10 | Convert character array back to string. 11 | */ 12 | 13 | // it's a good idea to at least check for the presence of the property before adding it, 14 | 15 | if (!("splice" in String.prototype)) { 16 | String.prototype.splice = function (startIndex, noOfcharToDelete, stringToInsert) { 17 | 18 | var stringCharArr = this.split(''); 19 | 20 | // NOTE: Because splice() mutates the actual array (and 21 | // returns the removed values), we need to apply it to 22 | // an existing array to which we have an existing 23 | // reference. 24 | Array.prototype.splice.apply(stringCharArr, arguments) 25 | 26 | return stringCharArr.join('') 27 | } 28 | } 29 | 30 | // Test case - 31 | 32 | var myStr = "Katie is sort of cool."; 33 | 34 | var strToDel = "sort of cool"; 35 | 36 | var splicedStr = myStr.splice( 37 | myStr.indexOf( strToDel ), 38 | strToDel.length, 39 | "crazy-insane kinds of hot" 40 | ); 41 | 42 | console.log( 43 | "New str:", 44 | splicedStr 45 | ); -------------------------------------------------------------------------------- /String/title-To-Camel.js: -------------------------------------------------------------------------------- 1 | /* Convert a text in titlecase to camelcase. 2 | 3 | Note that words would be converted in pairs 4 | 5 | Input: "These Words Should Go In Pairs" 6 | 7 | Output : "theseWords shouldGo inPairs" 8 | 9 | */ 10 | 11 | /* ALGO - 12 | 13 | Trim > Convert the sentence to lowercase > and split into an array. 14 | 15 | Run a for Loop over every two words by making the jump ( increment the counter 'i' by 2 elements instead of 1 ) 16 | 17 | Inside the above for loop, upperCase the first letter of the second word 18 | 19 | Push the pairs into an empty array. 20 | 21 | Convert the array to a string. */ 22 | 23 | titleToCamel = s => { 24 | 25 | let wordPairs = []; 26 | 27 | let words = s.trim().toLowerCase().split(' ') 28 | 29 | // Now while traversing the words array, I dont want to traverse through each of the elements of the array. 30 | // Rather I want traverse the second element (index-1) then jump to fourth-elemen (index-3) and so on, as I push each pair of two words into the new array 31 | for (let i = 1; i <= words.length; i += 2) { 32 | 33 | const firstWordIndex = i - 1; 34 | const firstWord = words[firstWordIndex]; 35 | 36 | let secondWord = words[i] 37 | 38 | // Uppercase the first letter of the seocond word 39 | secondWord = `${secondWord[0].toUpperCase()}${secondWord.slice(1)}` 40 | 41 | wordPairs.push(`${firstWord}${secondWord} `) 42 | } 43 | 44 | return wordPairs.join(' ').trim(); 45 | } 46 | 47 | 48 | // Test case for the function 49 | const newTitle = "These Words Should Go In Pairs" 50 | 51 | console.log(titleToCamel(newTitle)) -------------------------------------------------------------------------------- /String/toLocalString-Application.js: -------------------------------------------------------------------------------- 1 | var number = 123456.789; 2 | 3 | // India uses thousands/lakh/crore separators 4 | console.log(number.toLocaleString("en-IN")); // => 12,345,678.896 5 | 6 | // console.log(number.toLocaleString()) 7 | // 8 | 9 | -------------------------------------------------------------------------------- /String/tweet-word-limits.js: -------------------------------------------------------------------------------- 1 | /*Problem : Implement a twitter like twit-box component which limits the feed to 140 characters. 2 | 3 | Logic: Key point is, once a sentence is more than 140, and the 141-st character is actually in between a word, I can not return the broken word. Rather, I have to return upto the point, where the previous full word ended. 4 | If the length of the string is greater than 140 characters, then one of two things will happen - 5 | - If the 141th character is a space then return first 140 characters 6 | - Else if that character is not a space, then start moving backwards from the 140th character and find the first space then return the string starting from the first index to the index where space was found. */ 7 | 8 | 9 | cropTweeterSentence = str => { 10 | 11 | console.log('140-th character is ' + str.charAt(139)); 12 | 13 | if (str.length > 140) { 14 | 15 | if (str.charAt(140) === " ") { 16 | 17 | str = str.substring(0, 140); 18 | } else { 19 | // start the below for loop from 139-th position, because, I already know that the 140-th position is not as single space, so 20 | // there's no further point to search again at 140-th position for a single space 21 | for (let i = 139; i >=0; i--) { 22 | if (str[i] === " ") { 23 | // In below I am doing (i + 1), because substring() will not catch the end-position. But I want to finally return including the ending space 24 | str = str.substring(0, i + 1) 25 | 26 | // After finding and returning the sentence just once, I need to break the function permenently 27 | break; 28 | } 29 | } 30 | } 31 | } 32 | return str; 33 | } 34 | 35 | console.log(cropTweeterSentence('Foooo ')); 36 | console.log('\n'); 37 | 38 | console.log(cropTweeterSentence('Foooo kdnfs asfdnks sdfn asfnas fasdfk asflk saf sfm asfd mlmaf asf saf asfsafd dfdsf fdsf dsf sdf fffffffffffffffffffffffffff ffffff hhhXY f ')); 39 | console.log('\n'); 40 | 41 | console.log(cropTweeterSentence('Foooo kdnfs asfdnks sdfn asfnas fasdfk asflk saf sfm asfd mlmaf asf saf asfsafd dfdsf fdsf dsf sdf fffffffffffffffffffffffffff ffffff hhh XYf ')); 42 | console.log('\n'); 43 | 44 | console.log(cropTweeterSentence('Foooo kdnfs asfdnks sdfn asfnas fasdfk asflk saf sfm asfd mlmaf asf saf asfsafd dfdsf fdsf dsf sdf fffffffffffffffffffffffffff ffffff hhhXYf ')); 45 | console.log('\n'); 46 | -------------------------------------------------------------------------------- /date-conversion-comparison-moment/convert-string-date-from-MUI-pickert-to-YYYY-MM-DD.js: -------------------------------------------------------------------------------- 1 | /* The problem - I was using "material-ui-pickers" package for making a date-picker in the vollowing project - 2 | 3 | /home/paul/codeLap/React/Stock-Dashboard-PARSING-csv/1-Stock-Dashboard-PARSING-csv/src/Components/StockAnalytics/StockAnalyticsDashBoard.js 4 | 5 | Which is saving data as - "Thu May 09 2019 16:13:00 GMT+0530" 6 | 7 | But for an external API I need the date as - 09-05-2019 8 | 9 | */ 10 | 11 | const moment = require("moment"); 12 | 13 | const str = "Thu May 09 2019 16:13:00 GMT+0530"; 14 | 15 | // Alt - 1 16 | var myDate = moment(new Date(str.substr(0, 16))); 17 | // console.log(myDate.format("DD-MM-YYYY")); 18 | // console.log(myDate); 19 | 20 | // Alt - 2 21 | var event = new Date(str); 22 | let stringifiedDate = JSON.stringify(event); 23 | console.log(stringifiedDate); 24 | date = stringifiedDate.slice(1, 11); 25 | console.log(date); 26 | 27 | // Alt - 3 28 | convert = str => { 29 | const date = new Date(str); 30 | const month = ("0" + (date.getMonth() + 1)).slice(-2); 31 | const day = ("0" + date.getDate()).slice(-2); 32 | console.log("original converted date is ", date); 33 | console.log("date is ", date.getMonth()); 34 | console.log("date is ", date.getMonth()); 35 | console.log(month); 36 | console.log(day); 37 | return [date.getFullYear(), month, day].join("-"); 38 | }; 39 | 40 | convert(str); // => 2019-05-09 41 | 42 | /* 43 | slice(-2) extracts the last two elements in the sequence. 44 | */ 45 | -------------------------------------------------------------------------------- /date-conversion-comparison-moment/mongo-Date-Comparison-with-current-date.js: -------------------------------------------------------------------------------- 1 | /* Problem Statement - I have to compare curent date-time with the one saved in mongo's ISO format for checking if a password-reset uid has expired. So if the 'resetPasswordExpires' is earlier than the current-time, I will consider that uid invalid. Normal checking was giving erroneous result. Here's the solution. 2 | 3 | CAUTIONARY NOTE - WHILE THIS CODE WORKS PERFECTLY IN A STANDALONE .js FILE, I HAVE HAD FEW CASES WITHIN AN ACTUAL APP, WHERE IT FAILED TO WORK 4 | */ 5 | 6 | const actualMongoDB_data = [ 7 | { 8 | "status" : "pending", 9 | "_id" : ObjectId("5c8fab3052373723e5a2a0f2"), 10 | "uid" : "2e55cc00-498a-11e9-85d3-3df872f29c7b", 11 | "resetPasswordExpires" : ISODate("2019-03-18T14:29:04.820Z") 12 | }, 13 | { 14 | "status" : "pending", 15 | "_id" : ObjectId("5c8fab9c52373723e5a2a0f3"), 16 | "uid" : "6ea1e910-498a-11e9-85d3-3df872f29c7b", 17 | "resetPasswordExpires" : ISODate("2019-03-18T14:30:52.693Z") 18 | }, 19 | { 20 | "status" : "pending", 21 | "_id" : ObjectId("5c8fabd6ec281d25536fb49f"), 22 | "uid" : "917be080-498a-11e9-ab80-5bd21f444459", 23 | "resetPasswordExpires" : ISODate("2019-03-18T15:31:50.665Z") 24 | }, 25 | { 26 | "status" : "pending", 27 | "_id" : ObjectId("5c8fad500256be2611d28c54"), 28 | "uid" : "72f98df0-498b-11e9-8097-fd83c313130d", 29 | "resetPasswordExpires" : ISODate("2019-03-18T15:38:08.975Z") 30 | } 31 | ] 32 | 33 | 34 | 35 | let localCurrentTime = new Date(Date.now()).toLocaleTimeString('en-IN'); 36 | 37 | let mongoTime = new Date("2019-03-18T15:38:08.975Z").toLocaleTimeString('en-IN') 38 | 39 | console.log(localCurrentTime); 40 | console.log(mongoTime); 41 | 42 | if (mongoTime < localCurrentTime) { 43 | console.log('LOWER'); 44 | } else { 45 | console.log('LATER'); 46 | } 47 | 48 | // Reading - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString 49 | -------------------------------------------------------------------------------- /numbers/summing-digits-of-a-number-subtracting-first-digit-if-negative.js: -------------------------------------------------------------------------------- 1 | /* Problem: Given a number, write a function sumDigits that returns the sum of all its digits. If the number is negative, the first digit should count as negative. For example sumDigits(-316)) should return 4 */ 2 | 3 | // SOLUTION-1 - Little ugly way 4 | sumDigits = num => { 5 | //create array of number char 6 | let numArr = num.toString().split(""); 7 | 8 | // If the original number given was a negative number, only the first character will be negative symbol ( i.e. "-" ), which will also be the first element of the numArr after split. So, in that case, I have to add that symbol to the second element of the above array to make it a negative number. And then remove the first element of numArr (which is that negative symbol "-" ) 9 | if (numArr[0] === "-") { 10 | numArr[1] = "-" + numArr[1]; 11 | numArr.shift(); 12 | } 13 | 14 | // Now convert the array of string chars to array of numbers. 15 | return numArr.map(str => Number(str)).reduce((accum, curr) => accum + curr); 16 | }; 17 | 18 | console.log(sumDigits(-316)); // => 4 19 | 20 | // SOLUTION-2 - Better - Instead of splitting the string character-by-character, capture the digits, such that the first digit might be negative. 21 | 22 | sumDigits2 = num => { 23 | return num 24 | .toString() 25 | .match(/-?\d/g) 26 | .map(s => parseInt(s)) 27 | .reduce((accum, curr) => accum + curr); 28 | }; 29 | 30 | console.log(sumDigits2(-316)); // => 4 31 | 32 | /* A) match() with global flag will return an array of all the matches like below - 33 | 34 | console.log("-234".match(/-?\d/g)) // => [ '-2', '3', '4' ] 35 | 36 | But before applying match() - I have to convert to string 37 | 38 | B) parseInt() will take a string and convert to integer. And while converting a negative number will be converted to a negative number. 39 | 40 | */ 41 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "js-small-code-snippets", 3 | "version": "1.0.0", 4 | "description": "This repo is just a collection of my JavaScript codes purely for my own learning and practicing random codes", 5 | "main": "testing-code-3.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "" 12 | }, 13 | "author": "", 14 | "license": "ISC", 15 | "bugs": { 16 | "url": "https://github.com/rohan-paul/JS-CookBook-and-Random-JS-Code-For-Practicing/issues" 17 | }, 18 | "homepage": "https://github.com/rohan-paul/JS-CookBook-and-Random-JS-Code-For-Practicing#readme", 19 | "dependencies": { 20 | "bcrypt": "^5.0.0", 21 | "chai": "^4.1.2", 22 | "data-forge": "^1.7.1", 23 | "data-forge-fs": "0.0.6", 24 | "data-forge-indicators": "^0.2.4", 25 | "data-forge-plot": "^0.6.3", 26 | "es6-promise": "^4.2.4", 27 | "flat": "^4.1.0", 28 | "immer": "^3.1.3", 29 | "immutability-helper": "^2.7.1", 30 | "immutable": "^4.0.0-rc.12", 31 | "isomorphic-fetch": "^2.2.1", 32 | "lodash": "^4.17.19", 33 | "lodash.differencewith": "^4.5.0", 34 | "lodash.flatten": "^4.4.0", 35 | "lodash.isequal": "^4.5.0", 36 | "lodash.map": "^4.6.0", 37 | "lodash.omit": "^4.5.0", 38 | "lodash.partialright": "^4.2.1", 39 | "lodash.pick": "^4.4.0", 40 | "mocha": "^5.2.0", 41 | "moment": "^2.24.0", 42 | "moving-averages": "^4.0.5", 43 | "normalizr": "^3.6.0", 44 | "ramda": "^0.26.1", 45 | "rxjs": "^6.6.0", 46 | "ts-loader": "^8.0.1", 47 | "underscore": "^1.9.1", 48 | "z": "0.0.5" 49 | }, 50 | "devDependencies": { 51 | "babel-preset-es2015": "^6.24.1", 52 | "babel-register": "^6.26.0", 53 | "tslint": "^6.1.2", 54 | "typescript": "^4.0.0-beta" 55 | }, 56 | "babel": { 57 | "presets": [ 58 | "es2015" 59 | ], 60 | "sourceMaps": true, 61 | "retainLines": true 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /reWrite-JS-Function/every-myOwn-custom-callback.js: -------------------------------------------------------------------------------- 1 | /*The every() method tests whether all elements in the array pass the test implemented by the 2 | provided function.*/ 3 | 4 | Array.prototype.myEvery = function (callback, context) { 5 | 6 | for (let i = 0; i < this.length; i++) { 7 | if (!callback.call(context, this[i], i, this)) { 8 | return false; 9 | } 10 | } 11 | return true; 12 | } 13 | 14 | /*Note on why I have to return false inside the for loop and the final boolean value of true outside the for loop - 15 | 16 | https://codeburst.io/javascript-what-is-the-return-statement-97d8b11a1a0c 17 | 18 | The return statement ends function execution. Using return causes your code to short-circuit and stop executing immediately. 19 | Consider this example where we have two return statements in our test function: 20 | 21 | function test(){ 22 | return true; 23 | return false; 24 | }; 25 | test(); // => true 26 | 27 | The first return statement immediately stops execution of our function and causes our function to return true. The code on line three: return false; is never executed. 28 | ********************* 29 | * 30 | So, in above case, for myEvery() - which is exact same implementation of the isPrime() - the whole function will stop executing further as soon as the first 'return' word is encountered. So, I want to make it such a way, that as soon any of the elements fails the test in the callback, I return from the function by returning false. 31 | 32 | But, if after traversing all the array elements, I still did not encounter a failing case, i.e. did not encounter a 'return' statement, only then I come to the final return OUTSIDE OF THE FOR LOOP and return true 33 | */ 34 | 35 | // Test case-1 36 | 37 | var array1 = [1, 30, 39, 29, 10, 43]; 38 | 39 | function isBelowThreshold(currentValue) { 40 | return currentValue < 40; 41 | } 42 | 43 | let result = array1.myEvery(isBelowThreshold); 44 | 45 | console.log(result); -------------------------------------------------------------------------------- /reWrite-JS-Function/filter-myOwn-custom-callback.js: -------------------------------------------------------------------------------- 1 | /* filter - Implement the filter function. 2 | 3 | filter([1, 2, 3, 4], n => n < 3) // [1, 2] 4 | 5 | Basically I have to make this function to take a callback and return the output that satisfies the callback 6 | */ 7 | 8 | filter = (arr, func) => { 9 | 10 | let filteredList = []; 11 | 12 | for (let i of arr) { 13 | if (func(i)) { 14 | filteredList.push(i) 15 | } 16 | } 17 | return filteredList; 18 | } 19 | 20 | console.log(filter([1, 2, 3, 4], n => n < 3)); 21 | 22 | // Using Prototype 23 | 24 | Array.prototype.myFilter = function(callback, context) { 25 | 26 | arr = []; 27 | 28 | for (let i = 0; i < this.length; i++) { 29 | if (callback.call(context, this[i], i, this)) { 30 | arr.push(this[i]) 31 | } 32 | } 33 | return arr; 34 | } 35 | 36 | // Test cases 37 | let numbers = [1, 20, 30, 80, 2, 9, 3]; 38 | 39 | let filteredNum = numbers.myFilter(n => !(n % 2)) 40 | // I only want the even numbers - which means n % 2 should be zero. But zero is false, which would NOT be returned. So, making it to true by !(n % 2) 41 | 42 | console.log(filteredNum); // => [ 20, 30, 80, 2 ] 43 | -------------------------------------------------------------------------------- /reWrite-JS-Function/forEach-myOwn-custom-callback.js: -------------------------------------------------------------------------------- 1 | // forEach - Implement your owen Array.prototype.map function 2 | // Solution - 1 3 | 4 | Array.prototype.myForEach = function (callback) { 5 | 6 | arr = [] 7 | 8 | for (let i = 0; i < this.length; i++) { 9 | 10 | arr.push(callback(this[i], i, this)); 11 | } 12 | return arr; 13 | } 14 | 15 | // Test cases 16 | let numbers = [ 1, 4, 9 ] ; 17 | 18 | let squareRoot = numbers.myForEach(i => Math.sqrt(i)) 19 | 20 | console.log(squareRoot); // => [ 1, 2, 3 ] 21 | 22 | 23 | // Without using Array.prototype 24 | 25 | myForEach2 = (array, callback) => { 26 | 27 | let arr = []; 28 | 29 | for (let i = 0; i < array.length; i++) { 30 | arr.push(callback(array[i], i, this)) 31 | } 32 | return arr; 33 | } 34 | 35 | let squareRoot1 = myForEach2(numbers, (num) => { 36 | return Math.sqrt(num) 37 | }) 38 | 39 | console.log(squareRoot1); // => [ 1, 2, 3 ] -------------------------------------------------------------------------------- /reWrite-JS-Function/indexOf-myOwn-custom-callback.js: -------------------------------------------------------------------------------- 1 | /* indexOf - Implement the indexOf function for arrays. 2 | 3 | indexOf([1, 2, 3], 1) // 0 4 | indexOf([1, 2, 3], 4) // -1 */ 5 | 6 | indexOf_firstPrinciple = (arr, elem) => { 7 | for (let i = 0; i < arr.length; i++) { 8 | if (arr[i] === elem) { 9 | return i; 10 | } 11 | } 12 | return -1 13 | } 14 | 15 | console.log(indexOf_firstPrinciple([1, 2, 3], 1)); -------------------------------------------------------------------------------- /reWrite-JS-Function/map-myOwn-custom-callback.js: -------------------------------------------------------------------------------- 1 | // filter - Implement your owen Array.prototype.map function 2 | // Solution - 1 3 | // VERY IMPORTANTLY REMEMBER I CAN NOT USE ARROW FUNCTION HERE, AS ARROW WILL NOT BIND TO 'this' 4 | Array.prototype.myMap = function(callback) { 5 | // here this means the array on which the myMap will be called 6 | 7 | arr = [] 8 | 9 | for (let i = 0; i < this.length; i++) { 10 | arr.push(callback(this[i], i, this)) 11 | } 12 | return arr 13 | } 14 | 15 | let numbers = [1, 4, 9] 16 | 17 | let squareRoot = numbers.myMap(i => Math.sqrt(i)) 18 | 19 | console.log(squareRoot) // => [ 1, 2, 3 ] 20 | 21 | // Without using Array.prototype 22 | 23 | myMap2 = (array, callback) => { 24 | let arr = [] 25 | 26 | for (let i = 0; i < array.length; i++) { 27 | arr.push(callback(array[i], i, this)) 28 | } 29 | return arr 30 | } 31 | 32 | let squareRoot1 = myMap2(numbers, num => { 33 | return Math.sqrt(num) 34 | }) 35 | 36 | console.log(squareRoot1) // => [ 1, 2, 3 ] 37 | -------------------------------------------------------------------------------- /reWrite-JS-Function/some-myOwn-custom-callback.js: -------------------------------------------------------------------------------- 1 | /*The some() method tests whether at least one element in the array passes the test implemented by the provided function.*/ 2 | 3 | Array.prototype.mySome = function(callback, context) { 4 | 5 | for (let i = 0; i < this.length; i++) { 6 | if (callback.call(context, this[i], i, this)) { 7 | return true; 8 | } 9 | } 10 | return false; 11 | } 12 | 13 | let passed = [12, 5, 8, 130, 44].mySome(elem => elem < 100); 14 | 15 | console.log(passed); // => true --------------------------------------------------------------------------------