Monkey patching

Monkey patching is a technique that uses the flexibility of the JavaScript to modify any function/method behavior.

Performing monkey patching is simple and it can be done by the following steps.

  1. Store the original function in a variable
  2. Now modify the function behavior
  3. Call the original function using apply.

This can be useful when you want to change the argument values of the function. For example, consider we have the following class.

 


        var math = function () {
            this.a = 1;
            this.b = 2;
        };

        math.prototype = {
            sum: function (a, b) {
                return a + b;
            }
        }

Now we can modify the method sum using the monkey patching technique as follows.


        var original = math.prototype.sum;   Step 1

        math.prototype.sum = function (a, b) {
            a = a * 2, b = b * 2;    Step 2

            return original.apply(this, [a, b]);    Step 3
        }

On executing the above method, the result will as follows.


       var obj = new math();

        obj.sum(1, 2); //return 6;
        //Expected: 3, Actual : 6 due to monkey patch

Happy Scripting… 🙂

Using JSON parse and stringify methods

JSON plays vital role in JavaScript when comes with server interaction. But i noticed when people spoke about JSON they represent it as JSON object in Javascript which is incorrect. JSON is not a object it is just a string format which can be converted to object/array based on its language(Javascript, C#, C++ etc.)

JSON can be converted to JavaScript object using JSON.parse and JSON.stringify vice verse.

JSON.stringify

It is similar to the serialization of the object. The signature of the stringify method is as follows.

JSON.stringify(value[, replacer[, space]])

In the above the first argument is the object/array to be converted to JSON formatted string.

Controlling the stringify operation

Using replacer

The second argument of the stringify method is the replacer which can be an array or function and the value returned from the replacer will be stringify.

Example 1: using array

JSON.stringify({ a:1, b:2, c:null }, ["a","c"]);
//Output: "{"a":1,"c":null}"

Example 2: using function

JSON.stringify({a:1,b:2,c:null}, function(key, value) { return value != null ? value: undefined });
//Output: "{"a":1,"b":2}"
Using toJSON property

It is an another way of customizing the stringify operation. If an object contains a property named toJSON then the value returned from this function will be stringified instead of whole object.


var exFn = function() {
                      this.a=1;
                      this.b=2,
                      this._sum= function() { return this.a + this.b };
                      this.toJSON = function() {
                                             return {
                                                      a:this.a,
                                                      b: this.b,
                                                      sum: this._sum()
                                                     }
                                                }
                    }
//Output: JSON.stringify(new exFn())
"{"a":1,"b":2,"sum":3}"

JSON.parse

It is similar to the de-serialization of the object. The signature of the parse method is as follows.

JSON.parse(text[, reviver])

In the above the first argument is the JSON text input which has to be parsed to JavaScript object/array. For that the JSON string must abide the standards provided by the ECMA-404 The JSON Data Interchange Standard.

Controlling the parse operation

The parse operation can be controlled using the second argument of the parse method. It can be of type function. If the reviver is used then the parse will be done only based on the value returned by the reviver if reviver return undefined then that key will be excluded. The below will exclude the key with null values

var d = "{\"a\":1,\"b\":1,\"c\":null}"
JSON.parse(d, function(key, value){ if(value) return value; });
//Output: Object { a=1,  b=1}

Simple type casting in Javascript

This is my first blog for my very favorite language.

JavaScript is a very flexible language that would make to do many magical things. But the programming this language should be done careful since every browser is running in a single thread.

Type casting in JavaScript

Number

We all know the string or date can be converted to number using parseInt/parseFloat. But we can also use the “+” operator to do the same.

var d = +"43" //43

var d = +"4.3" //4.3

var d = +"4e" //NaN

var d = +new Date() //returns date value in milliseconds.

String

ToString method can be used to convert any number, boolean or date to string value. But it can be more simple by using the concatenating a “” at the end.

var d = 4 + "" //"4"

var d = new Date() + "" //"Wed Jul 22 2015 15:40:26 GMT+0530 (India Standard Time)"

String to Boolean

There is no simple way to cast from “true” string value to true boolean type. We have to do as follows.

var d = val == "true" ? true : val == "false" : false;