javascript « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ javascript ’

Node.js: Unit Testing with Jasmine framework

Posted by on May 14th, 2013

Jasmine is a framework which is used for testing node.js code or javascript code.

Installation

To install the latest official version, use NPM:

npm install jasmine-node -g

Write the specifications for your code in *.js and *.coffee files in the spec/ directory

Execution

After installing the npm package, you can run it with:

jasmine-node spec/filename.js
jasmine-node spec/filename.coffee

For executing multiple test files you can provide multiple filenames as an argument to jasmine-node command.


Key features :

  1. Behavior driven.
  2. It does not require DOM for testing.
  3. Clean and obvious syntax.

Test Cases :

SUITES
Call to a global function ‘describe’ which takes arguments a String and function. The function is a block of code that implements the suite.The String describes the title for the suit.

SPECS
Call to global Jasmine function ‘it’, which like ‘describe’ takes a string and a function. The string is a title for this spec and the function is the spec, or test. A spec contains one or more expectations that examine the state of the code under test,their can be as many ‘it’ functions in describe block.

EXPECTATION
Expectation in jasmine is an assertion which results either true or false. Their can be as many assertions in a spec. Expectations are genrated with the function ‘expect’ which takes an argument which is the actual value. It is chained with a Matcher function, which takes the expected value.

MATCHERS

Each matcher implements the Boolean comparison between actual and expected value. Matchers are used to compare both the values and if all matchers matches or return true only then test is considered as passed else it is considered as failure. Some of the matchers functions are ‘toBe’, ‘toBeTruthy’ etc.
Some examples are as follows:

expect(x).toEqual(y); // compares objects or primitives x and y and passes if they are equivalent
expect(x).toBe(y); // compares objects or primitives x and y and passes if they are the same object
expect(x).toMatch(pattern); //compares x to string or regular expression pattern and passes if they match

beforeEach() and afterEach()

Function ‘beforeEach’ performs task that is to be performed before test begins and ‘afterEach’ performs task that is to be performed after test finished execution.

Sample test

describe("A suite", function() {
var a;

it("A spec", function() {
a = true;

expect(a).toBe(true);
expect(a).not.toBe(false);
});
});

Sahil Chitkara
Software Trainee
Intelligrape Software

How to Determine Average in MongoDB

Posted by on April 2nd, 2013

MongoDB provides several ways of computing the average value of a group in a collection. One of the simplest ways of determining average is using the method db.collection.group().

The method db.collection.group() bunches the documents of a collection on the basis of the keys mentioned and executes aggregation functions on them. This method can be used for performing several operations, including count and addition. In order words, the method performs functionality similar to that of the SQL’s Select-Group By combination.

The implementation and working of the method db.collection.group() for determining the average of a field in a collection is illustrated here using the example of a collection ‘userquestions’. The query, which can be used to find average, is as follows -


var reduceFunction = function(currentDocument, previousDocument) {
     previousDocument.totalRating += currentDocument.rating; previousDocument.count += 1
};

var finalizeFunction = function(currentDocument) {
     currentDocument.average = currentDocument.totalRating/currentDocument.count;
     delete currentDocument.totalRating;
     delete currentDocument.count;
};

db.userquestions.group({
     key: {'quesId': true},
     initial: {totalRating: 0, count:0},
     reduce: reduceFunction,
     finalize:finalizeFunction
});

In the present context, the value of the ‘key’ is the field ‘quesId’. Documents are grouped together on the basis of this key. The initial values for the parameters ‘count’ and ‘totalRating’ are set to zero. Besides these, two functions are declared and defined in the query. The function reduce totals the value of the ‘rating’ and saves it in ‘totalRating’. In addition to this, it also maintains the count of documents processed.

On the other hand, the function ‘finalize’ determines the average value of rating by dividing the value of ‘totalRating’ by the count.The execution of this query returns an array containing different ‘quesId’, which represents the different groups and the corresponding average rating for each of these groups.

Hope this will help. :-)

Thanks,
Sakshi Tyagi
sakshi@intelligrape.com

Posted in Database

Difference Between ‘null’ and ‘undefined’ in JavaScript

Posted by on March 1st, 2013

Most people using JavaScript misunderstand the difference between ‘null’ and ‘undefined’. An unclear distinction between these two entities can lead to grave issues when using ‘null’ and ‘undefined’ in test cases.

A variable is said to be ‘undefined’ if it has been declared, but no value has been given to it. Contrary to this, ‘null’ is a value that can be assigned to a variable and represents ‘no value’. Therefore, ‘undefined’ is a variable type whereas ‘null’ is an object value.

Null’ in JavaScript

‘Null’ is a keyword in JavaScript that signifies ‘no value’ or nonexistence of any value. If you wish to shred a variable off its assigned value, you can simply assign ‘null’ to it. Besides this, like any other object, it is never implicitly assigned to a variable by JavaScript.
An example of explicit null assignment is –

var some_item= null;
console.log(some_item)

Upon execution, the code will print null.

Undefined’ in JavaScript

‘Undefined’ is a global variable that JavaScript creates at run time. This global variable is assigned to an object in one of the following cases –

1. Declared but not defined –
JavaScript assigns ‘undefined’ to any object that has been declared but not initialized or defined. In other words, in a case where no value has been explicitly assigned to the variable, JavaScript calls it ‘undefined’.

2. Array index or object property that does not exist.

3. A function parameter that has not been supplied.

4. The return value of functions that have to but don’t return a value.

An illustration of this assignment is shown in the following –

var item;
console.log(item)

Upon execution, the code will print undefined.

Difference in Type –  

‘Null’ is an object with a valid value, no properties, is non-mutable, and only a single instance of the same exists in the system at all times. In case you wish to verify the object nature of ‘null’, you can use the ‘typeof’ operator. The use of the same will give the output as ‘object’. However, if you use the ‘typeof’ operator on an object that belongs to one of the points mentioned in the ‘undefined’ list, you will get the object type as ‘undefined’.

Conversion to Primitive Types - 

A major difference between ‘null’ and ‘undefined’ is in the way they are converted to primitive types. When you perform arithmetic conversion on ‘null’, the value determined is 0. This conversion can be verified using the following code snippet.

var v1= 5+ null;
console.log(v1)

Upon execution, this output of this code will print 5.
However, ‘undefined’ does not carry out any such conversion. If you try to add ‘undefined’ to a numeral, you will get NaN or Not-a-Number. The following code snippet illustrates this facet of ‘undefined’.

var v2= 5+ undefined;
console.log(v2)

Upon execution, the code will print NaN.

Hope this will help. :-)
Sakshi Tyagi
sakshi@intelligrape.com

How to implement Inheritance in js2

Posted by on February 18th, 2013

We are assuming that you have installed js2 in your system, in case if you have not installed js2, first install js2.

First of all create a InheritanceTest.js2 file in scr directory with the content given below:

class Person { // Parent class
    var firstName;
    var lastName;

    function initialize(firstName, lastName) { // Constructor
        this.firstName = firstName;
        this.lastName = lastName;
    }

    function toString() {
        return this.firstName + ' ' + this.lastName;
    }
}

class Employee extends Person { // Child class
    var companyName;

    function initialize(firstName, lastName, companyName) { // Constructor
        this.$super(firstName, lastName);
        this.companyName = companyName;
    }

    function toString() {
        return this.$super() + ', ' + this.companyName;
    }
}

To compile js2 file into js file in lib directory run the command given below:

js2-node compile -f=node ./src ./lib

Now create a js script named as inheritance.js in scr directory with following content:

var Person = require('../lib/InheritanceTest').Person;
var Employee = require('../lib/InheritanceTest').Employee;

var person = new Person("Amit", "Thakkar");
console.log(person.toString())
var employee = new Employee("Amit", "Kumar", "Intelligrape");
console.log(employee.toString())

Now run inheritance.js file with the command given below:

node src/hello.js
// Output
Amit Thakkar
Amit Kumar, Intelligrape

Amit Kumar
amit.kumar@intelligrape.com
in.linkedin.com/in/amitkumar0110
twitter.com/amit_kumar0110
More Blogs by Me

Getting started with js2

Posted by on February 16th, 2013

We are assuming that you have installed node.js in your system, in case if you have not installed node.js, first install node.js.
To install js2 run the command given below:

npm install js2

Let’s create a simple Hello World project, but first let’s create a project directory structure:

mkdir helloWorldJs2
cd helloWorldJs2
mkdir scr lib

Now create a HelloWorld.js2 file in scr directory with the content given below:

class HelloWorld {
  function sayHelloWorld() {
    console.log("Hello World");
  }
}

To compile js2 file into js file in lib directory run the command given below:

js2-node compile -f=node ./src ./lib

Above command will compile HellowWorld.js2 file and will generate HelloWorld.js file in lib directory. Now create a js script named as hello.js in scr directory with following content:

var HelloWorld = require('../lib/HelloWorld').HelloWorld;
var helloWorld = new HelloWorld();
helloWorld.sayHelloWorld();

Now run hello.js file with the command given below, And you will get Hello World printed at console.

node src/hello.js

Amit Kumar
amit.kumar@intelligrape.com
in.linkedin.com/in/amitkumar0110
twitter.com/amit_kumar0110
More Blogs by Me

Difference between call() and apply() method of JavaScript

Posted by on January 30th, 2013

Many people get confused with these two functions in JavaScript, most of the time people think that we can pass an object in apply() and access it with this which is not possible with the call() method. But that is not the case, let’s see an example which will make it more clear.

Using call() method:

(function sum(a,b,c) {
 var i, k=0;
 var num = arguments.length;
 for (i = 0; i < num; i++) {
 k+= arguments[i];
 }
 console.log(this.toString()); //prints body of the function passed i.e., test()
 console.log(k); //prints the sum in console
 this(); // this will call the test() function passed to sum
 return k; //returns sum

}).call(function test() {
 console.log(10); //prints 10 in console
 },10,100);

Using apply() method:

 (function sum(a,b) {
    var i, k=0;
    var num = arguments.length;
    for (i = 0; i<num; i++) {
        k+= arguments[i];
    }
    console.log(this.toString()); //prints body of the function passed i.e., test()
    console.log(k);               //prints the sum in console
    this();             // this will call the test() function passed to sum
    return k;           //returns sum

}).apply(function test() {
       console.log(10); //prints 10 in console
    },[10,100,200,200]);

Try it online at Node Console

So the basic difference between both the methods is that in call() method we have to pass comma separated arguments and in apply() method we have to pass an array. If you have any queries then do let me know in comments section below.

“this” keyword in JavaScript

Posted by on December 20th, 2012

There are four patterns of invocation in JavaScript:
1. The method invocation pattern.
2. The function invocation pattern.
3. The constructor invocation pattern.
4. The apply invocation pattern.

1. The Method Invocation Pattern:
When a function is stored as a property of an object, we call it a method. When a method is invoked, this is bound to that object.

var employee = { 
	salary: 25000, 
	increaseSalary: function(inc) { 
		this.salary += inc || 5000; 
	} 
}; 
employee.increaseSalary(); 
document.writeln(employee.salary);

2. The Function invocation Pattern:
When a function is not the property of an object, this is bound to the global object.

employee.setBonus = function () { 
	var that = this; 
	var countBonus = function (inc) { 
		that.salary += inc || that.salary*0.5; 
	}; 
	countBonus(); 
}; 
employee.setBonus(); 
document.writeln(employee.salary);

3. The Constructor Invocation Pattern:
If a function is invoked with a new prefix, then a new object will be created with a hidden link to the value of the function’s prototype member, and this will be bound to that new object. If the function was invoked with the new prefix and the return value is not an object, then this (the new object) is returned instead.

var Person = function (name) { 
	this.name = name; 
	this.getName = function () { 
		return this.name; 
	}; 
}; 
var newPerson = new Person("Amit Thakkar"); // this will refer to newly created Object.
document.writeln(newPerson.getName()); // Amit Thakkar

4. The Apply Invocation Pattern:
The apply method takes two parameters. The first is the value that should be bound to this. The second is an array of parameters.

var vigil = { 
	name:"Vigil" 
}; 
document.writeln(newPerson.getName.apply(vigil)); // Vigil

Here this is referring to vigil object and there will not be any run-time error even when the number of arguments and the number of parameters do not match. If there are too many argument values, the extra argument values will be ignored. If there are too less argument values, the undefined value will be substituted for the missing values. So here second parameter will be undefined.

Amit Kumar
amit.kumar@intelligrape.com
in.linkedin.com/in/amitkumar0110
twitter.com/amit_kumar0110
More Blogs by Me

Using Yahoo Query Language (YQL) to Monitor a Web Page

Posted by on October 27th, 2012

I keep on experimenting on new things. So this time I thought of experimenting on something which I can use in my daily routine. I regularly visit a deals webpage. So, I thought of making an android mobile app for my android device that can track the deals webpage and notifies me whenever a new deal is added.

The deals website does not provide any api or service by which I can accomplish this. The only way to accomplish this task was to scrap the deals page and monitor it for changes.(I know scraping of other’s webpage is illegal, but its OK if we are doing it for the purpose of learning.)

One possible solution was to use a server side script that scraps the web page and stores its hash. So, in subsequent scraps, if the hash changes, that means the web page content has been changed. If it is so, it returns true otherwise it returns false. We periodically call the script from the phonegap app using jquery ajax call. Thus, when true is returned, it notifies me of the change in web page content and hence I get to know that a new deal is posted. The only problem with this approach is, We need to have extra resources like a server of our own where our script is hosted.

The other solution is to use Yahoo Query Language(YQL). By this solution, we will neither need server of our own nor the script. We just need to write a Yahoo Query and pass it along with the url provided by Yahoo. It is executed on Yahoo server and result(which is the complete html of the page in json format) is returned. In my case, I have created Yahoo Query from the javascript code. The query returns the deals web page content in json format(we can configure it to return result in other formats like xml also). We can then calculate its hash using javascript and store it in phone’s local storage. In subsequent scraps we just need to compare the already stored hash with the newly calculated hash to know if the content has been changed or not. Quite Simple! Let’s see how to implement it in code.

        function poll(url) {
            var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + url + '"') + '&format=json&callback=?';
            jQuery.getJSON(yql, function (data) {
                if (data) {
                    var newHashCode = JSON.stringify(data.query.results.body).hashCode(); 
                    //implementation of hashCode method is shown later
                    var oldHashCode = window.localStorage.getItem("dataHash");
                    if (oldHashCode) {
                        if (!(oldHashCode == newHashCode)) {
                            alert(url + " changed!");
                        }
                    }
                    window.localStorage.setItem("dataHash", newHashCode);
                }
            });
        }

Here, we pass the url of the web page which we want to monitor to the poll() function.
The variable yql stores the entire url which contains the address of yahoo page which will be hit and our yahoo query containing the url of webpage which we want to monitor. YQL has a simple MySQL query like syntax.

'select * from html where url="' + url + '"'

means select the entire html page of specified url. We can be as specific as we want in selecting page content.

Here is the implementation of hashCode method. The following code will inject hashCode method to every string. You can find its explanation here.

String.prototype.hashCode = function () {
            var hash = 0;
            if (this.length == 0) return hash;
            for (i = 0; i < this.length; i++) {
                ch = this.charCodeAt(i);
                hash = ((hash << 5) - hash) + ch;
                hash = hash & hash;
            }
            return hash;
};

Final step is to call the poll() function periodically to test for changes in webpage.

$(function () {
            document.addEventListener("deviceready", onDeviceReady, true);
});

function onDeviceReady() {
            setInterval("poll('www.eample.com')", 300000);
}

Here we are calling the poll() function every 5 minutes and passing it the url to be monitored.
I just used one small query of YQL. It has a lot more to offer. You can explore it in more detail here.
You can see the content returned from a particular url by writing your query at YQL Console.

I found YQL quite interesting. Hope you will find it interesting too.

Regards

Raj Gupta
raj.gupta@intelligrape.com
@rajdgreat007

Getting started with knockout.js

Posted by on September 26th, 2012

Recently, I learnt something very new e.g. Knockout.js. It is quite a advanced form of javascript. It just simplifies the structure of the javascipt in your application. It basically follows MVVM pattern(Model View View Model). It is quite fast and easy to use as comparison to jquery.

Some of it’s key features are :-

1. Declarative bindings
2. Automatic UI refresh
3. Free, open source (MIT license)
4. Pure JavaScript — works with any web framework
5. Supports all mainstream browsers
6. Templating(Quickly generate sophisticated, nested UIs as a function of your model data)

I’ll be covering the very basics of it in this article. In this, you need to deal with KO’s (Knockout objects). These are used to bind data with your model objects.

For using it add knockout-x.y.z.js in your application. Now, Moving towards how to use it :-
For example, Declaring model as below :-
E.g

  var firstModel = {
    empName: 'Gaurav',
    empWeight: 72
};

Then we need to create view for this e.g.

 Weight of emp <span data-bind="text: empName"> is <span data-bind="text: empWeight"> kgs.

Here KO wil bind the model object to these data-bind attribute and you will get the required details. But, this will not display the data as such, You need to activate the KO’s for binding the data.
e.g

<script>
  ko.applyBindings(firstModel);
</script>

After this you will be having the desired results.e.g Weight of emp Gaurav is 72 kgs.

So, You can see the declarative data binding of knockout.js. It is having lot more features. I’ll come up with all those.
Just give it a try. :)

Thanks & Regards,
Robin Sharma,
Intelligrape.
@er.robinsharma

JavaScript: Currying in JavaScript

Posted by on September 25th, 2012

Hi,

 

Currying is a very simple and useful concept in JavaScript. Here we can set the context of the function to any object or variable.

 

So let us study this concept using the practical examples and code as follows:

//Let us first create a function "curry"
function curry(thisObject, func){
    return function(){
          return func.apply(thisObject, arguments);
   };
}

//Lets make a function in which we have delegated the this arg. Such that this function is executed in the context of some other object.
var myCurriedFunction = curry("This is a string object, it will be the 'this' object", function(){
    alert(this);
});

//Now lets call the function:
myCurriedFunction(); //will alert "This is a string object, it will be the 'this' object"

 

 

Hope it Helps!
Kushal Likhi