Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- / * ========================================================================
- how to find common ancestor of 2 html elements */
- function findCommonAncestor(el1, el2) {
- const ancestors = new Set();
- // Traverse up and store ancestors of el1
- while (el1) {
- ancestors.add(el1);
- el1 = el1.parentElement;
- }
- // Traverse up el2 and find the first common ancestor
- while (el2) {
- if (ancestors.has(el2)) return el2;
- el2 = el2.parentElement;
- }
- return null; // No common ancestor found (unlikely in a valid DOM)
- }
- // Example usage:
- const elem1 = document.getElementById("child1");
- const elem2 = document.getElementById("child2");
- const commonAncestor = findCommonAncestor(elem1, elem2);
- console.log(commonAncestor); // Logs the common ancestor node
- /* ========================================================================
- In javascript give example of a function taking 2 dimensional arrays outputing a tree like output with - in front of child
- Example Input:
- const data = [
- ["root", null],
- ["child1", "root"],
- ["child2", "root"],
- ["subchild1", "child1"],
- ["subchild2", "child1"],
- ["subchild3", "child2"]
- ];
- Expected Output:
- root
- - child1
- -- subchild1
- -- subchild2
- - child2
- -- subchild3
- Time & Space Complexity:
- Time Complexity: O(N) — Each node is processed once.
- Space Complexity: O(N) — A dictionary stores parent-child relationships.
- */
- function buildTree(array) {
- const tree = {};
- // Build a mapping of parent -> children
- array.forEach(([child, parent]) => {
- if (!tree[parent]) tree[parent] = [];
- tree[parent].push(child);
- });
- // Recursive function to print tree
- function printTree(node, level) {
- console.log("-".repeat(level) + (level > 0 ? " " : "") + node);
- if (tree[node]) {
- tree[node].forEach(child => printTree(child, level + 1));
- }
- }
- // Find root nodes (nodes with no parent)
- array.forEach(([child, parent]) => {
- if (parent === null) {
- printTree(child, 0);
- }
- });
- }
- // Example usage
- const data = [
- ["root", null],
- ["child1", "root"],
- ["child2", "root"],
- ["subchild1", "child1"],
- ["subchild2", "child1"],
- ["subchild3", "child2"]
- ];
- buildTree(data);
- / * ======================================================================== * /
- function largestUniqueSubstring(s) {
- let start = 0; // Start pointer of the sliding window
- let maxLength = 0; // Store the maximum length of substring without duplicates
- let maxSubstring = ""; // Store the substring corresponding to maxLength
- let charSet = new Set(); // A set to store unique characters in the current window
- for (let end = 0; end < s.length; end++) {
- while (charSet.has(s[end])) {
- // If duplicate found, shrink the window by removing the leftmost character
- charSet.delete(s[start]);
- start++;
- }
- // Add the current character to the set
- charSet.add(s[end]);
- // Update maximum length and substring if needed
- if (end - start + 1 > maxLength) {
- maxLength = end - start + 1;
- maxSubstring = s.substring(start, end + 1);
- }
- }
- return maxSubstring;
- }
- // Example usage:
- console.log(largestUniqueSubstring("abcabcbb")); // Output: "abc"
- console.log(largestUniqueSubstring("bbbbb")); // Output: "b"
- console.log(largestUniqueSubstring("pwwkew")); // Output: "wke"
- /*
- 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.
- Explanation:
- Sliding Window: We use two pointers (start and end) to represent the current window of characters that contain no duplicates.
- Set: A set (charSet) is used to keep track of the characters in the current window.
- Loop: As we expand the window with the end pointer:
- 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.
- If no duplicate is found, we update the maximum length and the corresponding substring.
- Example Walkthrough (largestUniqueSubstring("abcabcbb")):
- Initial: start = 0, end = 0, charSet = {}, maxSubstring = ""
- Expand to 'a': charSet = {a}, maxSubstring = "a"
- Expand to 'b': charSet = {a, b}, maxSubstring = "ab"
- Expand to 'c': charSet = {a, b, c}, maxSubstring = "abc"
- Duplicate 'a' found, shrink window until no duplicate: start = 1, charSet = {b, c}
- Repeat the process for the remaining characters, but the max substring remains "abc".
- Time Complexity:
- 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.
- Space Complexity:
- 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)).
- */
- / * ======================================================================== * /
- function largestTwo(arr) {
- if (arr.length < 2) {
- console.log("Array needs at least two elements");
- return;
- }
- let largest = -Infinity;
- let secondLargest = -Infinity;
- for (let i = 0; i < arr.length; i++) {
- if (arr[i] > largest) {
- secondLargest = largest; // update second largest to be the previous largest
- largest = arr[i]; // update largest
- } else if (arr[i] > secondLargest && arr[i] !== largest) {
- secondLargest = arr[i]; // update second largest if it's smaller than largest but greater than the current second largest
- }
- }
- return [largest, secondLargest]
- console.log("Largest:", largest);
- console.log("Second Largest:", secondLargest);
- }
- // Example usage:
- console.log(largestTwo([-20, 20, 5, 8, 7, 3, -4])); // [20, 8]
- // Time Complexity O(n). Space Complexity O(1).
- / * ======================================================================== * /
- function promiseAll(promises) {
- return new Promise((resolve, reject) => {
- // Check if the input is an iterable
- if (!Array.isArray(promises)) {
- return reject(new TypeError('Argument is not iterable'));
- }
- let results = [];
- let completedPromises = 0;
- // Iterate over the promises array
- promises.forEach((promise, index) => {
- // Ensure each item is a promise by wrapping with Promise.resolve
- Promise.resolve(promise)
- .then(value => {
- results[index] = value;
- completedPromises += 1;
- // If all promises have been resolved, resolve the outer promise
- if (completedPromises === promises.length) {
- resolve(results);
- }
- })
- .catch(error => {
- // If any promise rejects, reject the outer promise immediately
- reject(error);
- });
- });
- // Handle the case of an empty iterable
- if (promises.length === 0) {
- resolve([]);
- }
- });
- }
- // Example usage:
- const promise1 = Promise.resolve(3);
- const promise2 = 42;
- const promise3 = new Promise((resolve, reject) => {
- setTimeout(resolve, 100, 'foo');
- });
- promiseAll([promise1, promise2, promise3]).then((values) => {
- console.log(values); // Output: [3, 42, 'foo']
- }).catch((error) => {
- console.error(error);
- });
- / * ======================================================================== * /
- function promiseRace(promises) {
- return new Promise((resolve, reject) => {
- // Loop through each promise in the iterable
- promises.forEach(promise => {
- // Attach `then` and `catch` handlers to each promise
- Promise.resolve(promise)
- .then(resolve)
- .catch(reject);
- });
- });
- }
- // Example usage:
- const promise1 = new Promise((resolve) => setTimeout(resolve, 500, 'one'));
- const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'two'));
- promiseRace([promise1, promise2]).then((value) => {
- console.log(value); // Output: 'two'
- }).catch((error) => {
- console.log(error);
- });
- export default ReturnOnce ( num) {
- function internal (){
- let calledTimes = 0;
- if(calledTimes) {return num}
- else return;
- }
- internal();
- }
- / * ======================================================================== * /
- //Write a function (getEvenAndSort) that can be
- // called on any array, and it returns the
- //subarray of only the even numbers, but
- //sorted.[12,3,2,1,7,6].getEvenAndSort()
- getEvenAndSort(arr) {
- unsortedArr = arr.filter((element)=>{
- (element%2) == 0;
- });
- return unsortedArr.sor();
- }
- getEvenAndSort([12,3,2,1,7,6]);
- ===============================================================
- let prom = new Promise(function(myResolve, myReject) {
- //setTimeout(function(){ alert("Hello"); }, 3000);
- setTimeout(function(){ resolve("prom"); }, 1000);
- setTimeout(function(){ reject(new Error("!prom")); }, 1000);
- });
- prom.then(function(arg) {
- console.log(arg);
- new Promise(function(myResolve, myReject) {
- });
- });
- ============================================================
- function foo(a){
- let returnValue = "";
- try {
- if(a=="bar"){
- throw new Error("qux");
- }
- returnValue = "try";
- } catch (err){
- returnValue = "catch";
- } finally {
- returnValue = "finally";
- }
- return returnValue;
- }
- console.log(foo('bar'));
- finally
- console.log(foo('zzz'));
- finally
- =============================================================
- function sayHi(fullName, callback){
- console.log(`Hi, ${fullName}!`);
- if(typeof callback === 'function'){
- callback();
- }
- }
- function sayBye(fullName, callback){
- console.log(`Bye, ${fullName}!`);
- callback();
- }
- function printMessage(firstName, lastName, callback){
- const fullName = `${firstName} ${lastName}`;
- if(typeof callback === 'function'){
- callback(fullName);
- }
- }
- printMessage('John', 'Doe', x => console.log(x));
- John Doe
- printMessage('John', Snow, sayYouKnowNothing);
- Uncaught ReferenceError: Snow is not defined
- at <anonymous>:1:22
- printMessage('John', 'Doe', sayBye);
- Bye, John Doe!
- VM1494:10 Uncaught TypeError: callback is not a function
- at sayBye (<anonymous>:10:1)
- at printMessage (<anonymous>:16:1)
- at <anonymous>:1:1
- printMessage('John', 'Doe', sayHi);
- Hi, John Doe!
- ===============================================================
- const x = {};
- x['foo']= 'bar';
- x.bar = {
- 'first': 100,
- 'second': 200
- };
- console.log(x.bar['first'] + x['bar'].second);
- 300
- =================================================================
- public class MyClass {
- private Map<String,Integer> map;
- public MyClass() {
- map = new HashMap<>();
- map.put("foo", 1);
- map.put("bar", 3);
- }
- public int getValue(String input, int numRetries) throws Exception {
- console.log('called with imput ', input, 'and numRetries', numRetries)
- try {
- return map.get(input);
- }
- catch (Exception e) {
- if (numRetries > 3) {
- throw e;
- }
- return getValue(input, numRetries + 1);
- }
- }
- }
- getValue("foo",0);
- getValue("bar",1);
- getValue("foo",2);
- getValue("bar",3);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement