Advertisement
amt

Qs

amt
Jan 29th, 2021 (edited)
921
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. / * ========================================================================
  2. how to find common ancestor of 2 html elements */
  3.  
  4. function findCommonAncestor(el1, el2) {
  5.     const ancestors = new Set();
  6.    
  7.     // Traverse up and store ancestors of el1
  8.     while (el1) {
  9.         ancestors.add(el1);
  10.         el1 = el1.parentElement;
  11.     }
  12.  
  13.     // Traverse up el2 and find the first common ancestor
  14.     while (el2) {
  15.         if (ancestors.has(el2)) return el2;
  16.         el2 = el2.parentElement;
  17.     }
  18.  
  19.     return null; // No common ancestor found (unlikely in a valid DOM)
  20. }
  21.  
  22. // Example usage:
  23. const elem1 = document.getElementById("child1");
  24. const elem2 = document.getElementById("child2");
  25. const commonAncestor = findCommonAncestor(elem1, elem2);
  26. console.log(commonAncestor); // Logs the common ancestor node
  27.  
  28. /* ========================================================================
  29. In javascript give example of a function taking 2 dimensional arrays outputing a tree like output with - in front of child
  30.  
  31. Example Input:
  32. const data = [
  33.   ["root", null],
  34.   ["child1", "root"],
  35.   ["child2", "root"],
  36.   ["subchild1", "child1"],
  37.   ["subchild2", "child1"],
  38.   ["subchild3", "child2"]
  39. ];
  40.  
  41. Expected Output:
  42. root
  43. - child1
  44. -- subchild1
  45. -- subchild2
  46. - child2
  47. -- subchild3
  48.  
  49. Time & Space Complexity:
  50. Time Complexity:  O(N) — Each node is processed once.
  51. Space Complexity: O(N) — A dictionary stores parent-child relationships.
  52. */
  53. function buildTree(array) {
  54.     const tree = {};
  55.    
  56.     // Build a mapping of parent -> children
  57.     array.forEach(([child, parent]) => {
  58.         if (!tree[parent]) tree[parent] = [];
  59.         tree[parent].push(child);
  60.     });
  61.  
  62.     // Recursive function to print tree
  63.     function printTree(node, level) {
  64.         console.log("-".repeat(level) + (level > 0 ? " " : "") + node);
  65.         if (tree[node]) {
  66.             tree[node].forEach(child => printTree(child, level + 1));
  67.         }
  68.     }
  69.  
  70.     // Find root nodes (nodes with no parent)
  71.     array.forEach(([child, parent]) => {
  72.         if (parent === null) {
  73.             printTree(child, 0);
  74.         }
  75.     });
  76. }
  77.  
  78. // Example usage
  79. const data = [
  80.     ["root", null],
  81.     ["child1", "root"],
  82.     ["child2", "root"],
  83.     ["subchild1", "child1"],
  84.     ["subchild2", "child1"],
  85.     ["subchild3", "child2"]
  86. ];
  87.  
  88. buildTree(data);
  89.  
  90.  
  91.  
  92.  
  93. / * ======================================================================== * /
  94. function largestUniqueSubstring(s) {
  95.     let start = 0;  // Start pointer of the sliding window
  96.     let maxLength = 0;  // Store the maximum length of substring without duplicates
  97.     let maxSubstring = "";  // Store the substring corresponding to maxLength
  98.     let charSet = new Set();  // A set to store unique characters in the current window
  99.  
  100.     for (let end = 0; end < s.length; end++) {
  101.         while (charSet.has(s[end])) {
  102.             // If duplicate found, shrink the window by removing the leftmost character
  103.             charSet.delete(s[start]);
  104.             start++;
  105.         }
  106.         // Add the current character to the set
  107.         charSet.add(s[end]);
  108.  
  109.         // Update maximum length and substring if needed
  110.         if (end - start + 1 > maxLength) {
  111.             maxLength = end - start + 1;
  112.             maxSubstring = s.substring(start, end + 1);
  113.         }
  114.     }
  115.  
  116.     return maxSubstring;
  117. }
  118.  
  119. // Example usage:
  120. console.log(largestUniqueSubstring("abcabcbb"));  // Output: "abc"
  121. console.log(largestUniqueSubstring("bbbbb"));     // Output: "b"
  122. console.log(largestUniqueSubstring("pwwkew"));    // Output: "wke"
  123.  
  124. /*
  125. To find the largest substring in a string without duplicate characters, we can use the sliding window technique. The idea is to use two pointers (start and end) to track a window of the substring that does not contain duplicates, and to keep expanding this window while updating a set of seen characters. If a duplicate is found, we shrink the window from the left side until the duplicate is removed.
  126.  
  127. Explanation:
  128. Sliding Window: We use two pointers (start and end) to represent the current window of characters that contain no duplicates.
  129. Set: A set (charSet) is used to keep track of the characters in the current window.
  130. Loop: As we expand the window with the end pointer:
  131. If the current character (s[end]) is already in the set (i.e., a duplicate is found), we shrink the window by moving the start pointer until there are no duplicates.
  132. If no duplicate is found, we update the maximum length and the corresponding substring.
  133. Example Walkthrough (largestUniqueSubstring("abcabcbb")):
  134. Initial: start = 0, end = 0, charSet = {}, maxSubstring = ""
  135. Expand to 'a': charSet = {a}, maxSubstring = "a"
  136. Expand to 'b': charSet = {a, b}, maxSubstring = "ab"
  137. Expand to 'c': charSet = {a, b, c}, maxSubstring = "abc"
  138. Duplicate 'a' found, shrink window until no duplicate: start = 1, charSet = {b, c}
  139. Repeat the process for the remaining characters, but the max substring remains "abc".
  140. Time Complexity:
  141. O(n): We visit each character at most twice (once when expanding the window, once when shrinking it), so the time complexity is linear with respect to the length of the string.
  142. Space Complexity:
  143. O(min(n, m)): n is the length of the string, and m is the size of the character set (which is at most 26 for lowercase English letters). The space complexity is determined by the size of the set charSet, so it's O(min(n, m)).
  144. */
  145. / * ======================================================================== * /
  146.  
  147. function largestTwo(arr) {
  148.     if (arr.length < 2) {
  149.         console.log("Array needs at least two elements");
  150.         return;
  151.     }
  152.  
  153.     let largest = -Infinity;
  154.     let secondLargest = -Infinity;
  155.  
  156.     for (let i = 0; i < arr.length; i++) {
  157.         if (arr[i] > largest) {
  158.             secondLargest = largest;  // update second largest to be the previous largest
  159.             largest = arr[i];  // update largest
  160.         } else if (arr[i] > secondLargest && arr[i] !== largest) {
  161.             secondLargest = arr[i];  // update second largest if it's smaller than largest but greater than the current second largest
  162.         }
  163.     }
  164.  
  165.     return [largest, secondLargest]
  166.  
  167.     console.log("Largest:", largest);
  168.     console.log("Second Largest:", secondLargest);
  169. }
  170.  
  171. // Example usage:
  172. console.log(largestTwo([-20, 20, 5, 8, 7, 3, -4])); // [20, 8]
  173. // Time Complexity O(n). Space Complexity O(1).
  174.  
  175. / * ======================================================================== * /
  176.  
  177.  
  178. function promiseAll(promises) {
  179.   return new Promise((resolve, reject) => {
  180.     // Check if the input is an iterable
  181.     if (!Array.isArray(promises)) {
  182.       return reject(new TypeError('Argument is not iterable'));
  183.     }
  184.    
  185.     let results = [];
  186.     let completedPromises = 0;
  187.  
  188.     // Iterate over the promises array
  189.     promises.forEach((promise, index) => {
  190.       // Ensure each item is a promise by wrapping with Promise.resolve
  191.       Promise.resolve(promise)
  192.         .then(value => {
  193.           results[index] = value;
  194.           completedPromises += 1;
  195.  
  196.           // If all promises have been resolved, resolve the outer promise
  197.           if (completedPromises === promises.length) {
  198.             resolve(results);
  199.           }
  200.         })
  201.         .catch(error => {
  202.           // If any promise rejects, reject the outer promise immediately
  203.           reject(error);
  204.         });
  205.     });
  206.  
  207.     // Handle the case of an empty iterable
  208.     if (promises.length === 0) {
  209.       resolve([]);
  210.     }
  211.   });
  212. }
  213.  
  214. // Example usage:
  215. const promise1 = Promise.resolve(3);
  216. const promise2 = 42;
  217. const promise3 = new Promise((resolve, reject) => {
  218.   setTimeout(resolve, 100, 'foo');
  219. });
  220.  
  221. promiseAll([promise1, promise2, promise3]).then((values) => {
  222.   console.log(values); // Output: [3, 42, 'foo']
  223. }).catch((error) => {
  224.   console.error(error);
  225. });
  226.  
  227. / * ======================================================================== * /
  228.  
  229. function promiseRace(promises) {
  230.   return new Promise((resolve, reject) => {
  231.     // Loop through each promise in the iterable
  232.     promises.forEach(promise => {
  233.       // Attach `then` and `catch` handlers to each promise
  234.       Promise.resolve(promise)
  235.         .then(resolve)
  236.         .catch(reject);
  237.     });
  238.   });
  239. }
  240.  
  241. // Example usage:
  242. const promise1 = new Promise((resolve) => setTimeout(resolve, 500, 'one'));
  243. const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'two'));
  244.  
  245. promiseRace([promise1, promise2]).then((value) => {
  246.   console.log(value); // Output: 'two'
  247. }).catch((error) => {
  248.   console.log(error);
  249. });
  250.  
  251.  
  252. export default  ReturnOnce ( num) {
  253.  
  254.    function internal (){
  255. let calledTimes = 0;
  256. if(calledTimes) {return num}
  257. else return;
  258.    }
  259.  
  260.    internal();
  261.  
  262. }
  263.  
  264. / * ======================================================================== * /
  265.  
  266.    
  267. //Write a function (getEvenAndSort) that can be
  268. // called on any array, and it returns the
  269. //subarray of only the even numbers, but
  270. //sorted.[12,3,2,1,7,6].getEvenAndSort()
  271.  
  272. getEvenAndSort(arr) {
  273.   unsortedArr = arr.filter((element)=>{
  274.     (element%2) == 0;
  275.   });
  276. return unsortedArr.sor();
  277. }
  278.  
  279. getEvenAndSort([12,3,2,1,7,6]);
  280.  
  281. ===============================================================
  282.  
  283. let prom = new Promise(function(myResolve, myReject) {
  284.   //setTimeout(function(){ alert("Hello"); }, 3000);
  285.   setTimeout(function(){ resolve("prom"); }, 1000);
  286.   setTimeout(function(){ reject(new Error("!prom")); }, 1000);
  287.  
  288. });
  289.  
  290. prom.then(function(arg) {
  291.   console.log(arg);
  292. new Promise(function(myResolve, myReject) {
  293. });
  294. });
  295.  
  296. ============================================================
  297. function foo(a){
  298. let returnValue = "";
  299. try {
  300. if(a=="bar"){
  301. throw new Error("qux");
  302. }
  303. returnValue = "try";
  304. } catch (err){
  305. returnValue = "catch";
  306. } finally {
  307. returnValue = "finally";
  308. }
  309. return returnValue;
  310. }
  311. console.log(foo('bar'));
  312. finally
  313. console.log(foo('zzz'));
  314. finally
  315. =============================================================
  316. function sayHi(fullName, callback){
  317. console.log(`Hi, ${fullName}!`);
  318. if(typeof callback === 'function'){
  319. callback();
  320. }
  321. }
  322.  
  323. function sayBye(fullName, callback){
  324. console.log(`Bye, ${fullName}!`);
  325. callback();
  326. }
  327.  
  328. function printMessage(firstName, lastName, callback){
  329. const fullName = `${firstName} ${lastName}`;
  330. if(typeof callback === 'function'){
  331. callback(fullName);
  332. }
  333. }
  334.  
  335. printMessage('John', 'Doe', x => console.log(x));
  336. John Doe
  337.  
  338. printMessage('John', Snow, sayYouKnowNothing);
  339. Uncaught ReferenceError: Snow is not defined
  340.     at <anonymous>:1:22
  341.  
  342. printMessage('John', 'Doe', sayBye);
  343. Bye, John Doe!
  344. VM1494:10 Uncaught TypeError: callback is not a function
  345.     at sayBye (<anonymous>:10:1)
  346.     at printMessage (<anonymous>:16:1)
  347.     at <anonymous>:1:1
  348.  
  349. printMessage('John', 'Doe', sayHi);
  350. Hi, John Doe!
  351. ===============================================================
  352. const x = {};
  353. x['foo']= 'bar';
  354. x.bar = {
  355. 'first': 100,
  356. 'second': 200
  357. };
  358.  
  359. console.log(x.bar['first'] + x['bar'].second);
  360.  
  361. 300
  362. =================================================================
  363.  
  364. public class MyClass {
  365.  
  366.   private Map<String,Integer> map;
  367.  
  368.   public MyClass() {
  369.  
  370.     map = new HashMap<>();
  371.  
  372.     map.put("foo", 1);
  373.  
  374.     map.put("bar", 3);
  375.  
  376.   }
  377.  
  378.   public int getValue(String input, int numRetries) throws Exception {
  379.  console.log('called with imput ', input, 'and numRetries', numRetries)
  380.     try {
  381.  
  382.       return map.get(input);
  383.  
  384.     }
  385.  
  386.     catch (Exception e) {
  387.  
  388.       if (numRetries > 3) {
  389.  
  390.         throw e;
  391.  
  392.       }
  393.  
  394.       return getValue(input, numRetries + 1);
  395.  
  396.     }
  397.  
  398.   }
  399.  
  400. }
  401. getValue("foo",0);
  402. getValue("bar",1);
  403. getValue("foo",2);
  404. getValue("bar",3);
  405.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement