<div id="root">
<div id="answer">
<div>
<div id="a">
A
</div>
</div>
<div>
<div id="b">
B
</div>
</div>
</div>
</div>
<script>
const leastCommonAncestor = (root, a, b, visited = {}) => {
/* if (root === null) return root;
if (root === a) visited.v1 = true;
if (root === b) visited.v2 = true;
if (root === a || root === b) return root;
const left = (root.left, a, b, visited);
const right = (root.right, a, b, visited);
if (left !== null && right !== null && visited.v1 && visited.v2) {
return root;
}
return left === null ? right : left; */
let curr = a;
while (curr !== root) {
curr.dataset.visited = true;
curr = curr.parentElement;
}
curr = b;
while (curr !== root) {
if (curr.dataset.visited === 'true') return curr;
curr = curr.parentElement;
}
return null;
};
console.log(leastCommonAncestor(document.getElementById('root'), document.getElementById('a'), document.getElementById('b')).id);
/*
const findLCA = (root, a, b) => {
if (root === null) return;
if (root === a || root === b) return root;
const ret = [];
for (const child of [...root.children]) {
const val = findLCA(child, a, b);
if (val) {
ret.push(val);
}
}
if (ret.length === 2) return root;
return ret[0];
};
*/
</script>
-
setTimeout() polyfill
(function() { let count = 1; // Can be generated. const timers = {}; // Can use priority queue based on time. const caller = () => { for (const [key, val] of Object.entries(timers)) { const { t, cb } = val; if (Date.now() >= t) { cb(); myClearTimeout(key); } } requestIdleCallback(caller); }; window.mySetTimeout = (cb, delay) => { timers[count] = { t: Date.now() + delay, cb }; if (Object.keys(timers).length) requestIdleCallback(caller); return count++; } window.myClearTimeout = (id) => { if (id in timers) delete timers[id]; } })() // Immediately Invoked Function Expression (IIFE). const id = mySetTimeout(() => { console.log('test') }, 2000); const id2 = mySetTimeout(() => { console.log('test2'); }, 1000); myClearTimeout(id); -
Use Zoho Mail with AWS Route 53
You need to add the following record to your hosted zone:
Record name Type Routing Alias Value TTL yourdomain.com MX Simple No 10 mx.zoho.com.
20 mx2.zoho.com.
50 mx3.zoho.com.300 -
System Design for Software Engineers and Engineering Managers
For starters I would recommend, looking at system design primer and Hello Interview. If you want to read more in detail consider getting the Designing data-intensive applications book.
Here are some popular system design interview questions:
- ChatGPT
- Web Crawler
- TinyURL
- Youtube
- Google docs
- Facebook Newsfeed
- Uber
- Job Scheduler
- Robinhood
- Elevator
- Key-Value store
- Ticketmaster
- Netflix
- Leetcode
Make sure to have a system design framework that you follow regardless of the question
- Ask clarifying questions
- Requirements (Functional and Non-Functional)
- Storage and Bandwidth Estimates
- APIs
- Data Model
- Architecture Diagram
- Discuss Pros and Cons of approaches
- Failure Cases
Practise using tools like Excalidraw.
-
Add code highlighting to WordPress
Add the following code snippet to your functions.php file in your WordPress theme and save it and refresh your page.
add_action( 'wp_enqueue_scripts', 'enqueue_highlightjs_assets' ); function enqueue_highlightjs_assets() { // Enable the plugin only for singular posts // if ( ! is_singular() ) { // return; // } // You can update the theme file with default.min.css or any other theme. wp_enqueue_style( 'highlightjs-css', '//cdn.jsdelivr.net/gh/highlightjs/cdn-release@latest/build/styles/atom-one-dark.min.css' ); wp_enqueue_script( 'highlightjs', '//cdn.jsdelivr.net/gh/highlightjs/cdn-release@latest/build/highlight.min.js', 'latest', true); wp_add_inline_script( 'highlightjs', 'hljs.highlightAll();' ); } -
Promise.all() polyfill
Javascript
Promise.alll = promises => new Promise((resolve, reject) => { let count = 0; const responses = []; promises.forEach((promise, index) => { promise.then((response) => { responses[index] = response; if (++count === promises.length) { resolve(responses); } }).catch(reject); }) }); const promise1 = Promise.resolve(3); const promise2 = Promise.resolve(6); const promise3 = Promise.resolve(9); Promise.alll([promise1, promise2, promise3]).then((values) => { console.log(values); }).catch((error) => { console.log(error); });Output
[3, 6, 9] -
Invert Binary Tree
Javascript
/** * Definition for a binary tree node. */ class TreeNode { constructor(val, left, right) { this.val = (val === undefined ? 0 : val) this.left = (left === undefined ? null : left) this.right = (right === undefined ? null : right) } } /** * @param {TreeNode} root * @return {TreeNode} */ const invertTree = root => root !== null ? new TreeNode(root.val, invertTree(root.right), invertTree(root.left)) : null; // Alternate answer. function invert(node) { if (!node) return node; [node.right, node.left] = [invert(node.left), invert(node.right)]; return node; } -
Largest Rectangular Area in a Histogram
/** * @param {number[]} inp * @return {number} */ const largestRectangleArea = function(inp) { const s = []; let i = 0; let max = 0; while (i < inp.length) { const val = inp[i]; if (!s.length || val >= inp[s[s.length - 1]]) { s.push(i++); } else { const top = s.pop(); max = Math.max(s.length ? (i - s[s.length - 1] - 1) * inp[top] : i * inp[top], max); } } while (s.length) { const top = s.pop(); max = Math.max(s.length ? (i - s[s.length - 1] - 1) * inp[top] : i * inp[top], max); } return max; }; -
Improving React Performance with useMemo and useCallback Hooks
useMemoanduseCallbackare two React hooks that can help improve performance in your application by optimizing the rendering of your components.useMemois used to memoize a value and only recalculate it when one of its dependencies changes. This is useful when you have a costly calculation that you don’t want to perform on every render.useMemotakes two arguments: a function that returns the value to be memoized, and an array of dependencies. The value returned by the function will only be recalculated when one of the dependencies changes.const memoizedValue = useMemo(() => { // perform a costly calculation return result; }, [dependency1, dependency2]);useCallbackis similar touseMemo, but it is used to memoize a function instead of a value. This is useful when you have a function that you want to pass down to child components as a prop, but you don’t want it to be re-created on every render.useCallbacktakes two arguments: a function, and an array of dependencies. The function returned byuseCallbackwill only be re-created when one of the dependencies changes.const memoizedFunction = useCallback((arg1, arg2) => { // perform some logic }, [dependency1, dependency2]);In general, you should use
useMemoto memoize a value anduseCallbackto memoize a function. However, if you have a function that returns a value, you can useuseMemoinstead ofuseCallback. -
Understanding the Difference Between event.target and event.currentTarget in JavaScript
In JavaScript, when handling an event in the browser, there are two different ways to access the event target:
event.currentTargetandevent.target.event.targetrefers to the element on which the event was originally triggered. This may be the element that was clicked on or interacted with by the user.event.currentTargetrefers to the element that the event listener is attached to. This may be the parent element or some other ancestor of the element that was clicked on.Here’s an example to illustrate the difference between
event.targetandevent.currentTarget:<body> <div class="parent"> <button class="child">Click me</button> </div> </body> <script> const parent = document.querySelector('.parent'); const child = document.querySelector('.child'); parent.addEventListener('click', function(event) { console.log(`Current target: ${event.currentTarget.tagName}`); console.log(`Target: ${event.target.tagName}`); }); child.addEventListener('click', function(event) { console.log(`Current target: ${event.currentTarget.tagName}`); console.log(`Target: ${event.target.tagName}`); }); </script>In this example, we have a parent element with a child element inside it. We attach a click event listener to both the parent and child elements.
When we click on the child element, the event listener attached to the child element is triggered first. In this case, the current target and target are both the child element.
Next, the event listener attached to the parent element is triggered because the click event bubbles up from the child element to its parent. In this case, the current target is the parent element (because that’s where the event listener is attached), but the target is still the child element (because that’s where the click event originated).
So, in summary,
event.currentTargetrefers to the element that the event listener is attached to, whileevent.targetrefers to the element on which the event was originally triggered.