Showing posts with label Technical Interview. Show all posts
Showing posts with label Technical Interview. Show all posts

Monday, May 20, 2013

Just for myself - JavaScript and Ajax

  1. XMLHttpRequest Object  (XHR)
XMLHttpRequest object is used to exchange data with a server behind the scenes.

With XHR we can
  1. Update a web page without reloading the page.
  2. Request a data from a server after the page has loaded.
  3. Receive data from a server after the page has loaded.
  4. Send data to a server in background
Remember: Update, Request, Receive, Send

To find more about XMLHttpRequest, visit  XMLHttpRequest


  • A synchronous XHR example  : The code snippet below illustrates synchronous XHR call. It reads text from a text file named 'data.txt' and presents in the browser. 
    var request = new XMLHttpRequest();
    request.open('GET', 'data.txt', false);
    request.send();
    console.log(request);
    document.writeln(request.responseText);
  • Asynchronous XHR example: The code snippet below illustrates asynchronous XHR call. It reaqds text from a text file named 'data.txt' and presents in the browser. It also takes in consideration the browser type, e.g. it uses XHR request for browsers like Safari, Chrome, Firefox etc and uses ActiveX for Internet explorer.
var request;
/*
If the browser API has XHR object, then set request variable to new XHR object.. for Safari, FireFox, Chrmoe
*/
if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
}
else request = new ActiveXObject("Microsoft.XMLHTTP");     // else... for IE
// This makes the script compatible to all browsers
request.open('GET', 'data.txt');  // by default, third parameter is true
request.onreadystatechange = function () {
    if( (request.readyState === 4) && (request.status === 200))
    {
        console.log(request);
        document.writeln(request.responseText);
    }
}
request.send();
Both of the request example above simply writes to a console of a browser.
But we can do the same to modify any part of a web element.


  • getElementById:
    Lets say we have a div element as shown below
    <div id = "heading">
    we can use following DOM command to replace its content as document.getElementById(heading).innerHTML = request.responseText
  • getElementsByTagName:
    Lets say we have some collection of elements, e.g. unordered list as shown below

    <ul>
         <li></li>
         <li></li>
         <li></li>
         <li></li>
         <li></li>
    </ul>


    And we only want to update the third list item, then we can achieve it as shown under.

    var result = document.getElementsByTagName("li");
    result[2].innerHTML = request.responseText



Balanced Parenthesis Algorithm using Recursive Function

Hi Friends,

Few days ago, I was asked to write a Parenthesis Balancing algorithm as a small test by one of the hiring company. I did it on time and have thought to share it with you guys.

The question goes as under.

Write a function which verifies parenthesis are balanced in a string. Each open parenthesis should have a corresponding close parenthesis and they should correspond correctly.

For example, the function should return true for the following strings:

  • (if (any? y) sum (/1 y))   
  • I said (it's not (yet) complete). (she didn't listen)
The function should return false for the following strings: 
  • :-)
  • ())(
Optional Bonus: Implement the solution as a recursive function with no mutation / side effects. 

Besides the question asking for only the small parenthesis, this program can work on any kind of parenthesis like  
i. < , >
ii. { , }
iii. [ , ]

All you have to do is provide the type of parenthesis as a second and third string parameter to the function. 

Here goes the code: 



private static bool Balanced(string input, string openParenthesis, string closedParenthesis)
        {
            
            try
            {
                if (input.Length > 0)
                {
                    //Obtain first character
                    string firstString = input.Substring(0, 1);

                    //Check if it is open parenthesis
                    //If it is open parenthesis push it to stack
                    //If it is closed parenthesis pop it
                    if (firstString == openParenthesis)
                        stack.Push(firstString);
                    else if (firstString == closedParenthesis)
                        stack.Pop();

                    //In next iteration, chop off first string so that it can iterate recursively through rest of the string
                    input = input.Substring(1, input.Length - 1);
                   Balanced(input, openParenthesis, closedParenthesis);   //this call makes the function recursive
                }

                if (stack.Count == 0 && !exception)
                    isBalanced = true;
            }
            catch (Exception ex)
            {
                exception = true;
            }

            return isBalanced;
        }


Lets call this function to prove the test cases provided by the question:

  1. Balanced("(if (any? y) sum (/1 y))", "(",  ")") 
  2. Balanced("I said (it's not (yet) complete). (she didn't listen)", "(",  ")") 
  3. Balanced(":-)", "(",  ")") 
  4. Balanced("())(", "(",  ")")  
Output:
  1. true
  2. true
  3. false
  4. false

   Good Luck