Javascript Questions Set3

1) What is event delegation?

Event delegation is when you bind an event listener to a parent (or ancestor) element rather than the element(s) you are particularly interested in. When the event is triggered you can check the event target to make sure it was actually the triggered on the element of interest.

Capturing and bubbling allow us to implement one of most powerful event handling patterns called event delegation. The idea is that if we have a lot of elements handled in a similar way, then instead of assigning a handler to each of them – we put a single handler on their common ancestor. In the handler we get event.target, see where the event actually happened and handle it.

Event bubbling provides the foundation for event delegation in browsers. Now you can bind an event handler to a single parent element, and that handler will get executed whenever the event occurs on any of its child nodes (and any of their children in turn). This is event delegation. Here’s an example of it in practice:

Let’s say that we have a parent UL element with several child elements:

    • Item 1

 

    • Item 2

 

    • Item 3

 

Let’s also say that something needs to happen when each child element is clicked. You could add a separate event listener to each individual LI element, but what if LI elements are frequently added and removed from the list? Adding and removing event listeners would be a nightmare, especially if addition and removal code is in different places within your app. The better solution is to add an event listener to the parent UL element. But if you add the event listener to the parent, how will you know which element was clicked?

Simple: when the event bubbles up to the UL element, you check the event object’s target property to gain a reference to the actual clicked node. Here’s a very basic JavaScript snippet which illustrates event delegation:

// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a list item
if(e.target && e.target.nodeName == "LI") {
    // List item found!  Output the ID!
    console.log("List item ", e.target.id.replace("post-"), " was clicked!");
       }
 });

2) What are the 3 ways to bind an event to an element ?
1) HTML Event Handlers
< input type=”text” id=”username” onblur=”checkUserName()”>
Not recommended any more. Better to separate JS and HTML

2) DOM Event Handlers
function checkUserName() { blah } ;
var el = document.getElementById(‘username’);
el.onblur = checkUserName;

Disadvantage is that you can only attach one function to each event Handler.

3) DOM Event Listeners
Advantage : They can deal with more than one function at a time.
var el = document.getElementById(‘username’);
el.addEventListener(‘blur’, checkUserName, false);

3) How do you convert arguments into an actual array. arguments are pseudo array in js.

var args = Array.prototype.slice.call(arguments);

4) How would you simulate Function.prototype.bind in older browser that don’t support it

Function.prototype.bind = Function.prototype.bind || function(context){
  var self = this;

  return function(){
    return self.apply(context, arguments);
  };
}

4) How to pass parameters to callback functions?

By default you cannot pass arguments to a callback function. For example:

function callback() {
  console.log('Hi human');
}

document.getElementById('someelem').addEventListener('click', callback);

But using closure concept you can do so :

function callback(a, b) {
  return function() {
    console.log('sum = ', (a+b));
  }
}

var x = 1, y = 2;
document.getElementById('someelem').addEventListener('click', callback(x, y));

5)  attribute vs. property:

https://lucybain.com/blog/2014/attribute-vs-property/

6) Explain the difference between: function Person(){}, var person = Person(), and var person = new Person()

First is a function declaration, second is a function expression, third is a function constructor

https://www.quora.com/In-Javascript-what-is-the-difference-between-function-Person-var-person-Person-var-person-new-Person

What are B-Trees

https://www.youtube.com/watch?v=k5J9M5_IMzg

a B-tree is a self-balancing tree data structure that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time. The B-tree is a generalization of a binary search tree in that a node can have more than two children (Comer 1979, p. 123). Unlike self-balancing binary search trees, the B-tree is optimized for systems that read and write large blocks of data. B-trees are a good example of a data structure for external memory. It is commonly used in databases and filesystems.

All terminal nodes are the same distance from the base

Sort Algorithms

Stable Sort: A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input unsorted array. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, Bubble Sort,

Complete Binary Tree: A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. A Binary Heap is a complete Binary Tree.

Heap Sort:
http://quiz.geeksforgeeks.org/heap-sort/
Karumanchi is also good for explanation , pg 180-185

// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i)
{
    int largest = i;  // Initialize largest as root
    int l = 2*i + 1;  // left = 2*i + 1
    int r = 2*i + 2;  // right = 2*i + 2
 
    // If left child is larger than root
    if (l < n && arr[l] > arr[largest])
        largest = l;
 
    // If right child is larger than largest so far
    if (r < n && arr[r] > arr[largest])
        largest = r;
 
    // If largest is not root
    if (largest != i)
    {
        swap(arr[i], arr[largest]);
 
        // Recursively heapify the affected sub-tree
        heapify(arr, n, largest);
    }
}
 
// main function to do heap sort
void heapSort(int arr[], int n)
{
    // Build heap (rearrange array)
    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(arr, n, i);
 
    // One by one extract an element from heap
    for (int i=n-1; i>=0; i--)
    {
        // Move current root to end
        swap(arr[0], arr[i]);
 
        // call max heapify on the reduced heap
        heapify(arr, i, 0);
    }
}