Saturday, September 22, 2012

Closures in JavaScript

Closures is a kind of object which combines 2 things - a function and the environment in which this function is been created. In simple words when we define an inner function, and that inner function uses the any variable defined outside(say in its outer function), then it is known as closure. Because even if the outer function returns then also this local variable is still in use by the inner function.
Lets understand it step by step using examples -

    function Outer(){
        var local = 1;
        return function(){
            return local;
        }
    }
    var outVar = Outer();
    alert(outVar());
In the above example if you see once the outVar is defined, the Outer function get returns. Then also the value local is available via inner anonymous function, This is simplest example of closure.

check the following scenario -


  var outVar ;
    function Outer(){
        var local = 1;
        outVar =  function(){
            return local;
        }
    }
    alert(typeof outVar);//undefined
    Outer();
    alert(typeof outVar); //function
    alert(outVar()); //1
Above example is very much similar to the 1st one.


Lets complicate the above example a little bit -

    var outVar ;
    function Outer(){
        var local = 1;
        outVar =  function(){
            return local;
        }
        local = 2;
    }   
    Outer();  
    alert(outVar()); //2
If you notice in above example, after assignment we have modified the value of local to 2, and once you call the closure, it alerts 2 not 1. It means the inner function is actually using the same local object of outer function, it didn't create a local copy of it.
Lets check one more example to understand it little deeper -

    var outVar1,outVar2 ;
    function Outer(){
        var local = 1;
        return function(){
            local++;
            return local;
        }
    }
    outVar1 = Outer();
    outVar2 = Outer();
    outVar1();
    outVar2();
    alert(outVar1());//--1
    alert(outVar2());//--2
In the above example, what you think will be the alert in statement 1 and 2, as both outVar1 and 2 are assigned the same inner function. Well the answer is both of them will alert 3, as they have their own copy of local variable(because local is actually a local variable of outer function).

Analyze the following code -

    function make(){
        var i;
        var a=[];
        for(i=0;i<3 i="i" p="p">            a[i] = function(){
                return i;
            }
        }
        return a;
    }
    var funcs = make();
    alert(funcs[0]()); //--1
    alert(funcs[1]()); //--2
    alert(funcs[2]()); //--3
What you think will be the output of above code?
At first you will think it might be 1,2,3 ....but actually it will alert 3,3,3. This is because the inner function get bound with the local variable i, and once we assign it to array, it actually got assigned( not evaluated or not executed). Thus once we execute it, it actually refer to same i from its outer function, and as its state got changed to 3, thus it alerts 3.
Now how can we fix this problem? Here is the fix -

function make(){
        var i;
        var a=[];
        for(i=0;i<3 i="i" p="p">            a[i] = (function(input){
                return function(){
                    return input;
                };
            })(i);
        }
        return a;
    }
    var funcs = make();
    alert(funcs[0]());
    alert(funcs[1]());
    alert(funcs[2]());
If analyze the code we have created another function which takes input as i, and then pass it further down to another function. Now the inner function or the closure is actually not connected to i directly.
Above code is very important to understand, we see application of closure in our daily javascript coding. Here is an example on the same concept where we are using the same concept -


for(i=0;i<3 i="i" p="p">            document.getElementById('btn'+i).onclick = function(){
                alert(i);
            }
        }
it will have the same issue, it will alert only 3. Here is the corrected version -

 document.getElementById('btn'+i).onclick = (function(input){
                return function(){
                    alert(input);
                }
            })(i);






JavaScript- Basic Concepts

Java Script is not a subset of Java, its completely different language. It is scripting language. JS programs are delivered as source code, it is never compiled(like any other language). It also provide loose typing, although its always preferred to have strong compiler check while you program. There are no classes in JS, there are only objects. IT also supports lambda, which means function as first class member. There is not linker in JavaScript thus all variables are combined in common namespace(global).

JS has following types of values -
Number
String
Boolean
Objects
null
undefined

Number -
There is only one Number type in JS, no integer.
it is represented as 64 bit floating point also known as IEEE -754 (double)
Decimal arithmetic is not good in JS, which means
0.1 + 0.2 == 0.3 -> false. Thus while critical operation always convert the number to integer and then apply arithmatic.
Special type named as NaN(Not A Number).
It is result of undefined ot erroneous operations. Any operation having NaN as input will result as NaN. NaN is not equal to anything, not even equal to Itself. But if we check the type of NaN, it is Number.

Number function - Number(value) -Converts value into number.  It produces NaN if it has a problem. It similar to + prefix operator.
+"42" -> 42
Number("42") -> 42

parseInt(value,10) - specialized in converting values into integers. It stops at first non-digit character. The radix value is required.
parseint("08") - > 0 treated as octal
parseInt("08",10) -> 8

String -
It is sequence of 0 or more 16-bit characters. There is no separate character type in JS. String in JS are immutable. String literals can use single or double quotes, both are same.
String function - String(value), convert value into string(say number).

Boolean - true and false
Boolean function - Boolean(value), convert value to boolean.
returns false for falsy values and true for truthy values.
Here are the falsy values - false, null, undefined, "", 0 , NaN
All other values are truthy, including all objects even "0" and "false"(as string values)

null- value that is nothing.
undefined - default value of variable.

EVERYTHIN ELSE IN JS IS OBJECTS.

Friday, September 21, 2012

JavaScript Tips and Tricks-8

Importance of constructor in javascript-
Check the following code -
        function Circle(radius){
            this.radius = radius;
            this.area = function(){
                return this.radius * this.radius * Math.PI;
            }
        }
       var c1 = new Circle(5);
        var c2 = {};
        Circle.call(c2,5);
       alert(c1 instanceof Circle); //true --1
        alert(c2 instanceof Circle); //false --2
        alert(c1.constructor == Circle); //true --3
        alert(c2.constructor == Circle); // false --4
Above code depict the difference between using "new" operator and calling call method on class to create new object. As you can check the output of statement 1,2,3 and 4.
"new" is equivalent to following 4 statements -
        var c2 = {};
        c2.constructor = Circle;
        c2.__proto__ = Circle.prototype;
        Circle.apply(c2,[5]);
Thus if we use "new" statement to create new object we get proper inheritance.

__proto__ Vs prototype-
__proto__ - Runtime uses to look at the parent object to resolve the properties, we can say it to be runtime reference to the parent object. All the object has __proto__ property.
prototype - It is special property of function and function only, to which "new" operator uses to copy onto the __proto__. It can be considered as template. All the function has prototype.


Function as return value-
Its always possible to return function as an object. lets see what happens in following example -
        function func1(param1){
            var counter = 0;
            return function(param2){
                return param2 + '-' + param1;
            }
        }
        var myvar1 = func1('firstcall');
        var myvar2 = func1('firstcall');;
        alert(myvar2 === myvar1); // false
If we assign the same returned function to myvar1 and myvar2, still its not equal because its 2 different instances of function.

Importance of non-blocking calls in JavaScript

In javascript there is only one thread. The same thread is responsible for running your code as well as updating the UI. Think about a server call which takes around 5 sec to come back. If we make such server call and wait for its response then the UI will be stuck for 5 sec. In order to avoid such circumstances we generally use callback methods. lets take the following example -

         function Greeter(s){
               this.salutation = s;
         }
         function Server(){}
              Server.prototype.getUser = function(fn){
              // Make a service call and fetch the user details
              fn.apply(this,['user']);
        }
        Greeter.prototype.greet = function(name){
            alert(this.salutation + '-' + name);
        }
        var greeter = new Greeter('Salutation');
        var server = new Server();

        server.getUser(greeter.greet); // undefined - User ----1
        server.getUser(
                function(name){
                    greeter.greet(name); // Salutation - User ----2
                }
        );
In the above example we are making a server call and passing a callback method, once the call is complete we want to greet the user. With the 1st attempt of passing the call back function it alerts 'undefined - User', that is because the 'this' got changes. In this 1st case once we call greet, it gets call on window not on greet, thus it try to get this.salutation(which becomes window.salutation) and returns undefined.  It happens because we are not calling the function in this line -  server.getUser(greeter.greet); there is no parenthesis here, we are just passing a variable name here, which is pointing at a function. The actual call is made from fn.apply (inside Server.getUser), where this becomes window and thus gives unexpected result.
In the 2nd case we are passing a function which eventually calls  greeter.greet() function, here this object is greeter which is never lost because we are actually calling it here. and thus we get expected result.

The above code is not very much scalable, Which means we will need to do the same thing for every callback function. We can make this code more generic like this -

function bind(funcThis,fn){
        return function(){
            return fn.apply(funcThis,arguments);
        }
    }
and then use this to bind greeter with greet -server.getUser(bind(greeter,greeter.greet));

Browser has a queue of events/tasks that needs to be done ordered by timestamp. If we have a call to server and an associated call back function with it, then the callback event/function actually get en-queued into the browser queue at the head of the queue. In other words the callback function takes the priority in the queue.
Here is the pseudo code which shows how browser behaves -
while(true){
   var event = waitForEvent();
   try{
        event();
   }catch(e){}
   redrawDOM();
}

Browser keeps waiting until next event comes and once it comes, it executes it.

Sunday, September 16, 2012

JavaScript Tips and Tricks - 7

Avoid eval in javascript -
var string1 = "var num1 = 1; alert(num1);";
var string2 = "var num2 = 2; alert(num2);";
var string3 = "var num3 = 3; alert(num3);";
eval(string1);//--1
new Function(string2)(); // --2
(function(){
    eval(string3); // --3
}());
alert(typeof num1); //--4
alert(typeof num2); // --5
alert(typeof num3); // --6
Output-
(1) - 1
(2) - 2
(3) - 3
(4) - number
(5) - undefined
(6) - undefined
NOTE - eval interfere with the scope chain,if the scope where eval is called, is global then it will make the variable Global. To overcome such problem we can wrap eval in an immediate function.eval can also access and modify a variable in its outer scope,whereas function cannot.

Arrays - use [] instead of new Array() -
var a = [3];
alert(a.length); // --1
alert(a[0]); // --2
//---
var b = new Array(3);
alert(b.length); // --3
alert(b[0]); // --4
 //--
var c = [2.34]
alert(c[0]); // -- 5

output -
 (1) -1
 (2) - 3
 (3) - 3
 (4) - undefined
 (5) - 2.34
If we use new Array() to construct a new array and pass a integer number to it, it takes 1st parameter as its length, in every other case it behaves differently. Thus its always recommended to avoid new Array and use [] to construct an Array.

Wrapper Objects -
In javascript for primitive types number,string and boolean we have wrapper objects Number(), String() and Boolean() available.
example -
var a = 100;
typeof(a); --> number
var objA = new Number(100);
typeof(objA); --> object
There are few methods available on object, but if we execute them on primitive as well, it works -
var s = "hello";
s.toUpperCase();
It is because of primitive can act as an object when needed(similar to auto boxing).But it does not mean that primitive variable will itself converted into object and will remain object. For that particular function/method it will get convert to object and then back to primitive. Here is example -
var s = "hello";
alert(s.toUpperCase()); -- > HELLO
s.newmethod = function() {
    alert('new method');
}
s.newmethod(); --> ERROR


JavaScript Aptitude Test


Ques - Write partial function in javascript. Here is the expected behavior of that function -
function add(param1,param2){
    return param1 + param2;
}
add.apply(null,[5,4]); // returns 9

now modify the add function so that we can pass the parameter 1 by 1, i.e.-
add(5)(4) ; // 9

Ans -
function add(x,y){
     if(typeof(x) === 'undefined'){
           return function(y){
                return x+y;
           }
     }
     return x + y;
}

Ques - Write a function namespace() which can create a namespace hierarchy for you-
MYAPP.namspace('module1,module2,module3'); should create a namespace named as MYAPP.module1.module2.module3.
Ans -
Generally we can directly create namespace like this -
MYAPP = {};
the issue is, whats if this name was already exist, then by writing this statement, we will override the existing function. So here is the right statement -
MYAPP = MYAPP || {};
Here is small code which creates a namespace -

namespace = function (ns_string){
    var parts = ns_string.split('.');
    var root = {};
    if(parts.length>0){
        root = this[parts[0]] || this;
    }
    for(var i=0;i        if(typeof (root[parts[i]]) === 'undefined') {
            root[parts[i]] = {};
        }
            root = root[parts[i]];       
    }
    return root;
}
namespace('global.MSSB.WebFramework.Coreservice');
alert(global.MSSB.WebFramework.Coreservice);



Ques - What will be the output of following function-
var myvar = function() {
    alert('my old var');
    myvar= function() {
        alert('my new var');
    }
}
var anotherVar = myvar;
anotherVar(); // --1
anotherVar();// --2
myvar();// --3
myvar();// --4
anotherVar();// --5
anotherVar();// --6
Ans -myvar defines a function, which while execution define the myvar again, and thus overrides the original definition of myvar. But while assignment of myvar to myanotherVar, the old definition only gets copied, and every time the old function get executed. Lets understand it by looking at the output -
(1) - my old var
(2) - my old var
(3) - my new var
(4) - my new var
(5) - my old var
(6) - my old var
 If you check, anotherVar alerts the old definition whereas myvar alerts the new definition, because once the myvar got executed, its original definition got overwritten by the new definition.


Encapsulation in JavaScript

Public Memebers -
 Lets see the following example -
 function Person(){
    this.name = 'name1';  
}

var p = new Person();
alert(p.name);

Private memeber -
Lets see the following example -
function Person(){
    var name = 'name1';
    this.getname = function(){
        return name;
    }
}
var p = new Person();
alert(p.getname()); // name1
alert(p.name); // undefined
Here the property name is private and the method getname is public, we also call it a Privileged Method, which means a public method to access private variables.

Lets see little complex example -
function Person(){
    var name = 'name1';
    this.getname = function(){
        return name;
    }
    var detail = {
        salary:1000,
        address : 'abcd',
        company:'Company1'
    }
    this.getdetails = function() {
        return detail;
    }
}
var p = new Person();
var detail = p.getdetails();
detail.company = 'new company';
In the above example even if the detail is private, but still because of getdetail method, the original object of detail get return. In order to avoid such circumstances, create a copy of the object and then return.
Or else create another object with only required detail, for example if you dont want to give the detail of salary, create another object with address and company detail in it. This is also known is Principle Of Least Authority(POLA).

JavaScript Tips and Tricks - 6

Implicit Vs Explicit Global Variable-
We all know that if we don't write var keyword, JavaScript will define the variable globally.
var myglobalVar = '';
(function (){
   anotherGlobalVar = '';
})();
typeof(myglobalVar); // string
typeof(anotherGlobalVar); // string
In the above example both myglobalVar and anotherGlobalVar are global and thus are available in the whole javascript.The "anotherGlobalVar" is also called as implied global variable.
The implied global variables are technically not real variables, the are properties of global object. Properties can be deleted with delete operator whereas variables can not and that is why we can delete the peoperty anotherGlobalVar but not myglobalVar.
which means -
delete myglobalVar; // false
delete anotherGlobalVar; //true

There are other ways where we can create implied global variables, one of them is chain of assignment.
Here is example -
function(){
    var a = b = 0;
}
In the above example variable a is local, whereas b is global.

Variable Hoisting -
JavaScript enables you to have multiple var statements anywhere in a function, and they all act as if the variables were declared at the top of the function. This behavior is known as hoisting. Sometimes it creates problem. lets take an example -
var myglobalVar = 'global';
(function (){
    alert(myglobalVar); //--1
  var myglobalVar = 'local';
  alert(myglobalVar); // --2
})();
In the above example what do you think the output will be? 1- global and 2- local, right? -- NO
the output is undefined and local. myglobalVar is declared locally. Even if it is declared after alert, then also JavaScript consider this as local and for this scope of the function it will be local. Thus the first alert gives undefined and another one gives local as output.

Function Hoisting  -
When using function declaration, the definition of the function is also get hoisted, not only its declaration. The function can be defined either by function declaration or by function expression.
function expression -
function a() {};
function declaration -
var a = function (){};

Both of these will show different behaviors because of hoisting. Consider following example-
function func1(){
    alert('global func1');
}
function func2(){
    alert('global func2');
}
function func3(){
    alert(typeof(func1)); // function
    alert(typeof(func2)); //undefined
    func1(); //local func1
    func2(); // Error - func2 undefined

    function func1(){
        alert('local func1');
    }
    var func2 = function(){
        alert('local func2');
    }
}
func3();

In the given example func1 get hoisted along with its definition, but func2, its just declaration which get hoisted.

Function Invocation -
There are four ways to call a function:
Function form - Value of "this" is global object.
functionObject(arguments)

Method form- Value of "this" is set to "thisObject", object which this method defined.
thisObject.methodName(arguments)
thisObject["methodName"](arguments)

Constructor form- A new object is created and assigned to "this".
new FunctionValue(arguments)

Apply form- Value of "this" object will be "thisObject", an explicitly passed value.
functionObject.apply(thisObject,[arguments])
functionObject.call(thisObject,arguments)

Sunday, September 9, 2012

Method Overloading in JavaScript

We are all aware of method overloading as a concept, Which states we can have same function name with different arguments. Lets see how can we achieve it in JavaScript.
Before starting on overloading , lets see how length property works on function, because we will need to use that property while building overloading -
function myfunc1(){}
function myfunc2(arg1){}
function myfunc3(arg1,arg2){}
alert(myfunc1.length); --> 0
alert(myfunc2.length); --> 1
alert(myfunc3.length); --> 2

using length property we can identify how many arguments are passed to the function.

Now let try to implement overloading
function addMethod(object,name,fn){
    var old = object[name];
    object[name] = function() {
        if(fn.length == arguments.length) {
            fn.apply(object, arguments);
        }
        else if(typeof(old) == 'function') {
            old.apply(object,arguments);
        }
    }
}
Just to clarify addMethod is not inbuilt method in JavaScript. We are writing our own method to achieve overloading.
If we see this method it take 3 arguments- object, name and fn.
object - the object on which we want to execute this method.
name - name of the function we want to overload.
fn - definition of function.

addMethod if you notice check the number of arguments and depending upon that it will identify if you have any method with the given name and same number of arguments, then it execute it.
To understand it more lets try to use it -
 function Person(){
    addMethod(this,'find',function(){
        alert('hi 0');
    });
    addMethod(this,'find',function(arg1){
        alert('hi 1')
    });
    addMethod(this,'find',function(arg1,arg2){
        alert('hi 2');
    })
}

var p = new Person();
p.find();
p.find('a');
p.find('a','b');

In above code once we create Person object, we are adding 3 new properties to Person, all has name find, but have different signature. In the addMethod, it appends these properties to person object. Once i call p.find(), it will try to find if Person has any function with name find and have 0 arguments in it. It will loop in that object until it finds it. If the function does not exist, it will exit.
If you attach a debugger and check the addMethod while execution you will find the first run we find argument.length as 0 and fn.length as 2(which is 3rd function), then it execute old.apply again and get the other find object, where it gets fn.length as 1 and finally as 0. Once it get the match it execute the find function.
Here we can not use call instead of apply, as the arguments are passed in the format of array.

Here is the whole code which executes different find methods in Person object-
function addMethod(object,name,fn){
    var old = object[name];
    object[name] = function() {
        if(fn.length == arguments.length) {
            fn.apply(object, arguments);
        }
        else if(typeof(old) == 'function') {
            old.apply(object,arguments);
        }
    }
}

function Person(){
    addMethod(this,'find',function(){
        alert('hi 0');
    });
    addMethod(this,'find',function(arg1){
        alert('hi 1')
    });
    addMethod(this,'find',function(arg1,arg2){
        alert('hi 2');
    })
}

var p = new Person();
p.find();
p.find('a');
p.find('a','b');

Saturday, September 8, 2012

Function/Variable Scope in JavaScript

Try to find the output of the following function -
function A(){
    this.myvar = 'a';
}
A();
alert(myvar);
var B = {
    myvar: 'B',
    C:function(){
        this.myvar = 'C';
    }
};
B.C();
alert(B.myvar);
alert(myvar);
Ans - a,C,a

once you declare this.myvar in function A, then actually we are creating a global variable. but when we are setting same value in function C within B, then actually its local value. In other words it is property of object, thus the value is set within object.
So actually function C is modifying the value of local variable named as myvar.
If we want to modify the global variable myvar within function C, then remove "this" before myvar, and directly set myvar = "C", it will modify the global variable.
To summarize- When it's an object property, the value is set within the object.

Now think about the output of this function -
function func(){
    return this;
}
alert(func()); ---- (1)

var myvar = {
    myfunc:func
}
alert(myvar.myfunc());-----(2)
In a function called directly without an explicit owner object, like case (1) causes the value of this to be the default object. case (1) is equivalent to calling window.myfunc().
In case 2 the calling object is myvar, thus the "this" object is actually myvar not window.
To Summarize - Function is a standard data type in JavaScript, an object indeed; you can pass them around and copy them. It's as if the entire function with argument list and body was copied and assigned.
In a function called using the method invocation syntax, like myvar.myfunc() or obj['myfunc'](), causes the value of this to be obj.
That's why although we declared function 'func' as global, instead of returning "window" as a value of "this" everytime, it returns it depending upon who calls it.

What if i don't want to declare the function inside this new variable, but still want to use it. Or else consider a case where a function need to be invoked on different objects. In above case , we will need to declare that function in each and every type of definition.
To overcome such situation we have "call" and "apply" method available.
We will simulate same example mentioned above to explore call and apply method.
function func(){
    return this;
}
alert(func());
var myvar = {
    name:'myname'
}
alert(func.call(myvar));
alert(func.apply(myvar));

The difference between these 2 methods comes when we pass some arguments. in case of call, we can directly pass the comma separated arguments, but in case of apply we need to pass these arguments in form of array. Here is the sample code -

function func(arg1,arg2){
    return [this,arg1,arg2];
}
var myvar = {
    name:'myname'
}
alert(func.call(myvar,'one','two'));
alert(func.apply(myvar,['one','two']));

To summarize- If we want to override the value of "this" without copying the function to another object, we can use "apply" or "call" and pass the required object in it.
NOTE- if we pass first parameter as null, then it is considered as global in javascript.

Lets try to understand Binding in JavaScript. Check the following code -
var Button = {
  click: function(){
    this.buttonclicked = true;
  }
};
var elem = document.createElement("li");
elem.onclick = Button.click;
elem.onclick();
alert(elem.buttonclicked); --> alerts true
alert(Button.buttonclicked); --> Alerts undefined

In the above example if you see, the 'buttonclicked' is the property of Button no element but still i see its available in element as well(of course accidentally).
In order to get the correct behavior we bind the Click property with Button. Check out the following code -
function bind(context, name){
  return function(){
    return context[name].apply(context, arguments);
  };
}
var Button = {
  click: function(){
    this.buttonclicked = true;
  }
};
var elem = document.createElement("li");
elem.innerHTML = "Click me!";
elem.onclick = bind(Button, "click");
elem.onclick();
alert(elem.buttonclicked); --> undefined
alert( Button.buttonclicked); --> true
in the above code we have bind the buttonclicked property with button.

To make it more generic its always possible to attach this bind property with function class itself.
If we define this on top of the page -
Function.prototype.bind = function(object){
  var fn = this;
  return function(){
    return fn.apply(object, arguments);
  };
};
then we can directly call - elem.onclick = Button.click.bind(Button);
because now every function has bind property associated with it.

Importance of new operator in JavaSCript-
Consider following example -
function A(){
    var name = "A";
}
var b = A();
var c = new A();
alert(typeof(b)); ----(1)
alert(typeof(c));-----(2)
In the above code b is undefined and type of c is object. In javascript new operator is used to create new object. Whenever we use "new" keyword, java script run time provides a new value of "this" object.

Thursday, September 6, 2012

JavaScript Tips and Tricks -5

1) Here are different ways in which you can define a JavaScript function -
a)
    function func(x){
    alert(x);}
    func('myName');
b)
    var func = function(x){
    alert(x);}
    func('myName');
c)
    var func = new Function("x" ,"alert(x);");
    func('myName');
d)
    window.func= function(x){ alert(x); };
    func('myName');

2) Sometimes in JavaScript the order of function definition does not matter. Here is the example -
if(typeof (func) == "undefined")
    alert('func is undefined');
else
    alert('func is not undefined');
function func(){ return true; }
The above alerts - func is not undefined.
But this statement is not true for any kind of assignment. Which includes the function assignment as well.
Which means if we defined function in any one of these format,it wont be possible to use them before assigning it. -
 window.func= function(x){ alert(x); };
 var func = new Function("x" ,"alert(x);");
 var func = function(x){alert(x);}
Which means following code will give output as "func is undefined" -
if(typeof (func) == "undefined")
    alert('func is undefined');
else
    alert('func is not undefined');   
var func = function(x){alert(x);}

3) We can always define functions below return statement. For example -
 function TestFunc(){
  alert(func());
  return func();
  function func(){ return true; }
}
TestFunc();
Above function will return as true.

4) Its always possible to have recursive calls in Java Script functions. Here is example-
function factorial(num){
    if(num == 0 || num == 1)
        return 1;
    else return num*factorial(num - 1);
}
alert(factorial(4));

5) How to implement Cache in JavaScript -
 var getSquare = function(num) {   
    if(getSquare.cache[num] == null)
        getSquare.cache[num] = num * num;
       
    return getSquare.cache[num];
}
getSquare.cache = {};

alert(getSquare(3));
alert(getSquare.cache[3]);

Saturday, September 1, 2012

SynhronizationContext

Que-Why do we need synchronization context?
Ans-The idea behind synchronization context is that a "source" thread can queue a delegate(piece of work) to the target thread. Generally in STA model(like UI components) we can't have multiple threads modifying the same component. Thus its required that only a single thread, dedicated to update UI, will do this job. In order to achieve this kind of design, Synchronization context was introduced. In other words is does the following-
1) provide synchronization(by allowing only one operation by s single thread at a time)
2) Queuing a unit of work from one thread to another.

Que-Is Synchronization context only for UI element?
Ans-The original purpose of synchronization context is to update the UI elements only. We can have its use to pass any unit of work to other non-ui threads as well. (Yet to get more info).

Que-What is the different between send and post?
Ans- Send/post are 2 ways by which we can marshal the code from one thread to another. The difference is send is a synchronous call  whereas post is an Async call. Send will wait till the operation is completed and then will come back. The calling thread will be blocked until it returns.

Que- When we marshal a code to UI thread and that code throws exception, then who is responsible to catch that exception?
Ans -
In case of send method - It is caught at calling thread not on the UI thread.
in case of post - it is on ui thread only.

Here is the example-
This code is executed in a form application.
 public void Run(Object state)
        {
            Debug.WriteLine("Run Thread Id - " + Thread.CurrentThread.ManagedThreadId);
            SynchronizationContext context = state as SynchronizationContext;
            try
            {
                context.Send(UpdateUI,null);  
            }
            catch (Exception ex) {
                Debug.WriteLine(ex.ToString());
            }
        }

        public void UpdateUI(object state) {
            throw new Exception();
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
            Debug.WriteLine("Main Thread Id - " + Thread.CurrentThread.ManagedThreadId);
            SynchronizationContext uiContext = SynchronizationContext.Current;

            Thread t1 = new Thread(Run);
            t1.Start(uiContext);
        }

Que- What will be the ThreadId of DoWork? Same as Run thread or main thread?
static void Main(string[] args)
        {
            Console.WriteLine("Main thread is " + Thread.CurrentThread.ManagedThreadId);
            SynchronizationContext context = new SynchronizationContext();           
            SynchronizationContext.SetSynchronizationContext(context);
            Thread t1 = new Thread(Run);
            t1.Start(SynchronizationContext.Current);
            Console.ReadLine();
        }

        static void Run(object state)
        {
            Console.WriteLine("Run Thread ID: " + Thread.CurrentThread.ManagedThreadId);
            var context = state as SynchronizationContext;
            context.Send(DoWork, null);
            while (true)
                Thread.Sleep(10000000);
        }
        static void DoWork(object state)
        {
            Console.WriteLine("DoWork Thread ID:" + Thread.CurrentThread.ManagedThreadId);
        }
Ans- It will be same as Run Thread. As We can't use Synchronization context in this way. Actually the Synchronization Context provided by .NET does have it message pump. context pushes the messages to this message pump then UI thread picks these messages from this queue or message pump. In the above case the message pump us missing. If we want to achieve similar behavior, then we will have to implement our own queue, and will have to read items on UI thread using that queue.

Que- What is message pump?
Ans - A message loop is a small piece of code that exists in any native Windows program. It roughly looks like this:
while(GetMessage(&msg, NULL, 0, 0))
{
   TranslateMessage(&msg);
   DispatchMessage(&msg);
}
The GetMessage() Win32 API retrieves a message from Windows.TranslateMessage() is a helper function that translates keyboard messages. DispatchMessage() ensures that the window procedure is called with the message.
In the recent version of windows the order of messages is maintained.