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

Tuesday, January 8, 2013

Javascript Object/Variable type detection


            This articles discusses about discovering the type of variables/objects in javascript, we can also look into Javascript (and Ecmascript)basics. A loosely type programming language is one which does not require us to define a type for a variable to hold values.

var a;
a = 1;       
alert(a);    // 1
a = "Test";
alert(a);   //  Test
a=null;
alert(a);   //  null

The above example shows us that javascript is a loosely typed language. So now this gives the freedom to easily assign values to those variable without having to care about their type. But we do face situations where we need to know the type of the variable we are dealing with, so how does javascript handle the situation ?

There are many ways of doing this, lets look upon them one by one

1) instanceof

The very basic method is to use the 'instanceof' operator. It is used to test whether the argument supplied to  it belongs to a particular type. It returns either true or false. It works well for variables created by constructors but not for most literals.

new String('test') instanceof String     //true
'abc' instanceof String                  //false

new Number(10) instanceof Number         //true
10 instanceof Number                     //false

new Boolean('true') instanceof Boolean   //true
true instanceof boolean                  //false

2) typeof

The next method is to use 'typeof'. The typeof operator takes an argument in front and returns the type of the argument as a response string.

typeof 999          // Number
typeof 'test'       // String
typeof function(){} // Function
typeof true         // boolean

But the disadvantage with typeof operator is that

It fails with Arrays
typeof ['abc', 'def', 'ghij', 21]; // "object"
It returns only 'object' for all instance of the object which is not useful
typeof new String('test'); // "object"
typeof new Date();         // "object"
typeof new Number(999);    // "object"
typeof new Boolean(true);  // "object"
It fails with most of the core objects
typeof Math;    // "object"
typeof Array;   // "function"
typeof Number;  // "function"
typeof Object;  // "function"

Note:
typeof operator on null returns object. This is because it the result specified in the standard table for null. Brendan Eich felt that 'null' mostly used with object unlike 'undefined' and hence added this entry to the standard table to return 'object' although ECMA-262-3 standard defines type of null as Null.

3) duck typing

The 'typeof' and 'instanceof' are of not too useful and thus has forced us to follow 'duck typing'.

Wikipedia states 'duck typing is a style of dynamic typing in which an object's methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface'

Duck testing -  If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.

Similarly if the object can identified by testing if it responds to particular methods. This requires us to define unique methods for every object to identify them easily,
for ex:
In java script

function isString(arg) {
  return arg.charAt !== undefined;
}
function isArray(arg) {
return arg.pop !== undefined;
}

We pass the argument and test if the object contain the properties, and return the corresponding results. This is a better way of testing for objects types than instanceof or typeof.
However if we resort to duck typing we may have to write a function for every different type or if we have a single function to check for types, we may have to add new checks for new classes. This is a disadvantage of duck typing when we want to have a generic solution.

4) Object prototype method -toString(args)

One of the best and recommended ways to discover variable type is to use the core object, Object's prototype method - toString(arg). It checks and returns the type of the argument.

Object.prototype.toString('abc'); // "[object String]"
Unlike 'typeof' it works both with instances of core objects (created with constructors) and with literals
Object.prototype.toString(new String('test')); // " [object String]"
Object.prototype.toString('test'); // "[object String]"

Object.prototype.toString(new Number(999)); // " [object Number]"
Object.prototype.toString(999); // " [object Number]"

Unlike 'typeof' it can also (native) objects such as Math and Date

Object.prototype.toString(Math);       // " [object Math]"
Object.prototype.toString(new Date()); // " [object Date]"

Unlike duck typing we need not add functions or new checks for classes as we can have a single function that takes any arguments and returns the get the type of the  returned.

Thus core object, Object's prototype method - toString(args) proves to be a better solution when we need to determine the type of a javascript variable/object.

Note:
Ecmascript has totally 9 datatypes, out of which only 6 are directly accessible in the language,
  1. Undefined
  2. Null
  3. String
  4. boolean
  5. Number
  6. Object
Everything except the object are represented in implementation directly on a low level in the language. They do not have any properties or constructors.
Objects on the other hand are collection of un ordered set of key, value pairs. Each object has properties and constructor. They are the only type that represents the Ecmascript objects. The keys represent the properties and the value can either be primitives, other objects or function (called as object's method).

the other 3 that can be realized in the language are
  1. Reference
  2. List
  3. Completion   
Reference is used during the use of operators such as 'delete', 'typeof' and consists of a base object.
List describes the behaviour of argument list, such as in new and function calls.
Collection type is used in explanation of break, continue, throw statments.


References and Sources -


Javascript vs Ecmascript - http://stackoverflow.com/questions/912479/what-is-the-difference-between-javascript-and-ecmascript
http://www.examplejs.com/?tag=object-prototype-tostring
http://www.youtube.com/watch?feature=player_embedded&v=v2ifWcnQs6M

Friday, January 4, 2013

Wednesday, January 2, 2013

Short JavaScript Quiz

Give the output of  the following and define the scope of variables

<script>


// a _____-scoped variable
var a=1;

// ______ scope
function one(){
    alert(a); 
}

// ______ scope
function two(a){
    alert(a);
}

// ______ scope
function three(){
  var a = 3;
  alert(a);
}

// Intermediate: 
Does javascript have a block scope ?
function four(){
    if(true){
        var a=4;
    }

    alert(a);
}


// Intermediate:  ______ ______ properties
function Five(){
    this.a = 5;
}


// Advanced: closure
var six = function(){
    var foo = 6;

    return function(){
        // javascript - "closure" means I have access to foo in here,
        // [ to be updated ]
        alert(foo);
    }
}()


// Advanced: __________ scope resolution
function Seven(){
  this.a = 7;
}

// [object].______ loses to [object].______ in the scope chain
Seven.prototype.a = -1; // ______ get reached, because __ is __ in the constructor above.
Seven.prototype.b = 8; // ______ get reached, even though __ is ___ set in the constructor.


one();
two(2);
three();
four();
alert(new Five().a);
six();
alert(new Seven().a);
alert(new Seven().b);


</script>
The best ever examples given by Triptych - on Stackoverflow.com
Source:
http://stackoverflow.com/questions/500431/javascript-variable-scope

Tuesday, January 1, 2013

Question 4


Given a Family Tree, (not necessarily a Binary Tree) print the details of all person in order of generation level.

                                         Jim
                                    /              \

                                /                     \

                             /                          \

                          /                                \

                       /                                     \
                  Martha                                Joe
                 /   |  \                                   /      \
            Sally Andrew Stewart       Kimmel   Walsh
            /
         Peter
       /   |   \
    Meg  Chris  Stewie

Note:[ There's no sibling pointer, each node points to its children]

Expected O/p:
Gen 1: Jim
Gen 2: Martha
       Joe
Gen 3: Sally
       Andrew
       Stewart
       Kimmel
       Walsh
Gen 4: Peter
Gen 5: Meg
       Chris
       Stewie

Comparing Objects in Java

In real world, we tend to compare everything around us. Mom's car is smaller than my car. His Xbox has more memory than my Xbox. He is more higher than me. In Object Oriented language like Java we can define our own logic to compare objects.

In Java, every class extends implicitly extends from Object class. There various ways of comparing objects, they are

 ==

'==' is used between reference variable. eg: { (a==b) , (a!=b) }
It compares only the references of the two variable, and returns true if they are same and returns false if they are different.
It does not compare the values of the objects.
It may be used for comparing two enum values. This works because there is only one object for each enum constant.
But in our real life scenario we may not need to compare objects only by checking reference, we might have to check based on business logic too.

In order to perform comparison between them we need to be able to compare objects based on the criteria  we need to compare them.

equals()

'equals' method is a instance method that is available for every class since they all extends from Object implicitly.
It can be used to check values for equality in classes, but however it doesn't perform any intelligent operation unless the class override this function. If not overridden it just checks the reference of the two Objects and returns true if they are same and false it they are not.
But if you want to implement equality based on logical way or a bussiness logic, JAVA requires us to override both equals and hashcode method.

In addition to this the object equal method has to satify the following properties too,

1) Reflexive : Any object must be equal to itself.
2) Symmetric : If a.equals(b) is true then b.equals(a) must also be true.
3) Transitive : If a.equals(b) is true and b.equals(c) is true then c.equals(a) must also be true.
4) Consistent : multiple invocation of equals() method must result same value until any of properties are modified. So if two objects are equals in Java they will remain equals until any of there property is modified.
5) Null comparison : comparing any object to null must be false and should not result in NullPointerException. For example a.equals(null) must be false

The contract between equals and hashcode method states that
1) If two objects are equal, then their hashcode should be the same
2) If two objects have the same hashcode, they may be equal or different

This contract has to be honored when overriding the equal method of custom classes with our own logic.

Usage:

-Used extensively in Java core library like they are used while inserting and retrieving Object in HashMap
-To avoid duplicates on HashSet and other Set implementation
-Whenever we need to compare objects

Comparable<T> interface

The Comparable interface is used for classes that have a natural ordering. Since helps us to order elements, it greatly used for sorting. It will allow us to compare values and tell us if they are less than, equal to or grater than the other value, thus making a class comparable.

In order to implement this, the class has to implement the Comparable<T> interface and define the method CompareTo(Object o). The method returns a int value of 0,negative or positive integer based on whether the value is less,equal or greater. The method any object as parameter to compare, but me make sure we do not compare unrelated objects like we can't compare a person with a bike. 

Usage:

- Sorting of strings in array can be done simply by java.util.Array's sort method 
- Sorting of strings in collections such as ArrayList can be done by java.util.Collection's sort method
- But if we have a custom defined class such as person which we need to sort we cannot do so with either java.util.Array's sort and java.util.collection's sort. We need to implement Comparable interface and defince the CompareTo(Object o) method in the class. Then we can use either of the sort method based on the data structure we store our values in. 

Comparator interface

 Often we may have to compare objects on different basis, so having just one CompareTo(Object o) may not suffice. For example, if we have a person class we could have comparison based on
(i) age
(ii)first name
(iii)lastname
This means we might need different comaparing functions. This could be achieved with the Comparator interface which is used to compare the value of two objects in many ways.
In order to create many version of the comparing functions we need to write class that implement Comparator interface and define the compare method which has the following signature

public int compare(Object o1,Object o2) 

The method returns negative or 0 or positive number based on whether the objects is less,equal or greater than the other.

Once these classes have been defined based on unique comparing logic, we can use them in our java.util.Array's and java.util.Collections's sort method

Array.sort( <array>, <comparator_class>)

Note:If your class have only one way of sorting like number, you may not need this.

Usage:

- Allows us to define multiple ways of comparing objects. eg: age,firstname, lastname
   Arrays.sort(persons, new LastNameComparator());
   Arrays.sort(persons, new FirstNameComparator());
   Arrays.sort(persons, new AgeComparator());
- Also used for providing comparator classes to methods that we have no control over, ex: If we wanted compare strings based on their length, we could write our own custom comparator and pass it to
   Array.sort( <string>, <string_length_comparator>) 
- Very useful in Strategy Design Pattern, where we store different algorithms as different objects, that can be used later on based on the situation.



Common errors:

When comparing two objects you should know when to use to == and equals.

Equals - Objects can be different but the properties are same (Values are same)
     == -      Objects are same [ both refer to same object in memory ]


Reference-

Friday, December 28, 2012

Question 3:

Given a text file that contains millions of (x,y) Co-ordinates, write an algorithm to find the 100 closest points to the origin.


Behind the browser

What actually happens behind the browser as we enter the URL that we need to access. I would like to explain the entire process as it happens Let's assume that we just we just did enter the url 'google.com' in our browser and pressed enter.


Step 1:
This step involves resolving the domain name to a IP address to which we could send our request for the webpage. This initial mapping of domain name to IP address is done via a application level protocol called the DNS or the Domain Name Service that maps the domain name to Ip address.
Initially the mapping is done as follows,

Browser cache -
                  The browser itself caches some of the DNS records, however the OS doesn't force any time to live or keep alive time for these DNS records.

OS Cache -  
                  In case the mapping is not available in Browser's cache, we search the OS cache, and this is done by 'gethostbyname' in Windows and in linux based machines.

Router's Cache -
                  In case the mapping is not available in OS's cache, we search the Router that we are connected to for DNS record that contains the mapping. Router also caches the DNS mapping for a certain period of time.

ISP's DNS server - 
                  In case the mapping is not available in Router's cache we directly contact the ISP's DNS server in order to get the mapping. Each Isp will have their own DNS server to help with the DNS requests.

Recursive DNS Search - 
                  In case the mapping is not available in ISP's DNS Server, we hit the root server and perform a recursive dns query



 This will provide us with the IP address we need to send our HTTP request to.

Step 2:
   We need to send the HTTP request to fetch the URL we need.
 [Note: I used the chrome's inbuilt developer's tool to view the request that was sent ]
 The browser forms the HTTP request and sends it to the IP address
GET http://google.com/ HTTP/1.1
Host: google.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
X-Chrome-Variations: CLu1yQEIhLbJAQigtskBCKW2yQEIqLbJAQiptskBCLq2yQEIu4PKAQ== Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: NID=67=pJorFW7 [...]

The HTTP request contains headers that provide all the information a server might need. Some of the important Headers are User-Agent - which indicates the client initiating this request, Accept - The type of response for this request, Accept-Encoding- the encoding method to be used for the response, Cookies. To learn more about HTTP Headers [...]

Step 3: The response from the server for this request is as follows


HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Fri, 28 Dec 2012 20:07:34 GMT
Expires: Sun, 27 Jan 2013 20:07:34 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN


The HTTP 301 indicates that a page has permanently moved. By giving a response with HTTP 301, the browser can issue a new request with to the url http://www.google.com instead of  the old url http://google.com/ . The reason behind this is that for search engines, we do not need two different url's pointing to the same resource. This might lead to page hit being split and causing lower ranking for the same resource. Search engines can understand redirect and will update the page hits directly to the new url.

Also if the same content is cached with different url's, it becomes cache non-friendly as we have multiple copies of the same content.

 According to HTTP/1.1 Status Code Definitions section of the Hypertext Transfer Protocol -- HTTP/1.1 RFC 2616, Fielding, et al, the HTTP 301 is described as follows
The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise. The new permanent URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s). If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued. Note: When automatically redirecting a POST request after receiving a 301 status code, some existing HTTP/1.0 user agents will erroneously change it into a GET request.
To learn more about HTTP 301 [...]
To learn more about HTTP 301 implementations in different platforms [...]

Step 4: The browser again issues a GET request to the new URL in the response


GET http://www.google.com/ HTTP/1.1
Host: www.google.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
X-Chrome-Variations: CLu1yQEIhLbJAQigtskBCKW2yQEIqLbJAQiptskBCLq2yQEIu4PKAQ==
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: NID=67=pJorFW7Q [....]

Step 5: The response returned for this request is a HTTP 302 Found status code


HTTP/1.1 302 Found
Location: https://www.google.com/
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=26fdae9d55c46b89:U=1ee158d5a202460c:FF=1:LD=en:NW=1:TM=1356672777:LM=1356725255:GM=1:SG=2:S=cDOs6qNFYgZICceY; expires=Sun, 28-Dec-2014 20:07:35 GMT; path=/; domain=.google.com
Date: Fri, 28 Dec 2012 20:07:35 GMT
Server: gws
Content-Length: 220
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

The HTTP 302 indicates resources temporarily resides under a different URI. Since the redirection might be altered when performing future requests, the browser should only use the request URI for future purposes. The  new URI to be used for the current response in the location field in the response.

RFC states that the response should contain a short hyperlink text to the new URI.

Also states that , In case the 302 was generated to a request other GET or HEAD, the user agent should not redirect by itself.



Step 6:
Now the browsers knows the correct URI to send the GET request to, so it forms the new HTTP GET request and send it to the correct URI

GET http://www.google.com/complete/search?sugexp=chrome,mod=11&client=chrome&hl=en-US&q=goo&sugkey=AIzaSyCLlKc60a3z7lo8deV-hAyDU7rHYgL4HZg HTTP/1.1
Host: www.google.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: NID=67=pJorFW7Qdq [...]


Step 7:
This request now reaches the server which will process it and provide it with a response.

The web server in itself comprises of the
Web server  - IIS , Apache  which handles all the incoming requests and host the web application. It receives the requests and forwards them to the appropriate web application. All the incoming requests are queued and each request can be handled in a separate thread or a single thread, which approach has its own advantages and  disadvantages [..] .
Web Application - These are the request handlers, that reads the request, observes the values of all the parameters, cookies. It process the request, also updates the databases and web server if needed and finally sends back a response to the client.

Step 8:
 The response generated by the server is as follows,

HTTP/1.1 200 OK
Date: Fri, 28 Dec 2012 20:07:35 GMT
Expires: Fri, 28 Dec 2012 20:07:35 GMT
Cache-Control: private, max-age=3600
Content-Type: text/javascript; charset=UTF-8
Content-Disposition: attachment
Content-Encoding: gzip
Server: gws
Content-Length: 173
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

� ����� ��VJ��W

The content encoding tells the browser that the content is encoded using the gzip algorithm. The browser needs to decompress it. The Content-type: indicate what type of content is carries in the response body. Here it of type javascript. The header also specifies it cookies are to be set, how to cache the page, any other information if needs to be set.

Step 9:
Once the response is received the browser starts to render the HTML page, even though all the necessary  resources (such as images, flash, video, etc..) may not be available. As it renders, the browser understand that it needs other resources to build the page which is indicated by the URI.

When I tried to fetch the google homepage the some of the following were downloaded with individual GET requests


Request URL: https://ssl.gstatic.com/gb/images/k1_a31af7ac.png
Request Method: GET
Status Code: 200 OK (from cache)

Request URL: https://www.google.com/images/nav_logo114.png
Request Method: GET
Status Code: 200 OK (from cache)

Each of these request follow the same process of fetching the HTML page. If you see some of the static resources such as images could be cache. So that these resources could be served from the cache.

When this resources was initially request, the response would have a Expire header which specifies the cache life time for this resource. In addition each response will have ETag which serves to be a version number for these resources. When the browser wants to get a resource it check ETag, if the resource is already available then it stop the request. This saves a lot of bandwidth in downloading files that are already available.

Step 10:
Once the page is rendered, the browser may still try to communicate  with the server. This is done with the help of 'Ajax' which stands for Asynchronous JavaScript and XML. With Ajax we have communication between  server and client without have to render the whole page. The response to Ajax request from client could be XML or a Java script.
For example the Google+ notification, might constantly poll and check for updates, since the HTTP is a request response protocol, the server cannot push messages to the client without a HTTP request. Hence the client needs to poll the server for updates.

This pattern could be used for chat purposes, where we need chat notifications from the server. Long polling is one of the techniques used to poll the server. [....]


This is the way the browser interacts with the server in order to render your page.




NOTE: Thanks to Igor Ostrovsky and his wonderful blog which helped me write this article



References:
http://igoro.com/archive/what-really-happens-when-you-navigate-to-a-url/
http://en.wikipedia.org/wiki/Push_technology
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
http://en.wikipedia.org/wiki/Domain_Name_System




Saturday, December 22, 2012

Question 2

What happens when you type in a url in your browser ?

http://interactioncloud.blogspot.com/2012/12/behind-browser.html

Tuesday, December 18, 2012

Question 1


Given co-ordinates (x1,y1),(x2,y2) and (x3,y3),(x4,4). Check if two rectangles overlap.

0 if they overlap
1 if they do not overlap

hint: no need to use distance formulae