Wednesday 18 June 2014

Inheritance in oopJs

//PARENT class

    function Parent()
    {
        var name =  "devesh"; //private variables
        this.pass = "123"; //public variables
        _protected = "protected";
        pro = "new proc";
       
        // private methods are declared within the scope of constructor   
        var privateMethod = function(){
        //var self =this
        // self.walk(); //accessing public methods in private method
        return console.log(name);
        }
        // privileged methods are methods that are public and same time have access to privated properties/methods   
        this.privilegedMethod = function(){
        return privateMethod();
        }

    }
    Parent.fixed = 3;
    // public methods   
    Parent.prototype.walk = function(){
    console.log("i am walking via public method");
    }

    Parent.prototype.sayHello = function(){
    console.log("say hello from parent");
    }

    //define child class
    function Child(){
    Parent.call(this) //call constructor of parent class
    }
    //var parentObj = new Parent({name:"devesh",pass: "1234", protect:"protected varibale"});
    Child.prototype = new Parent();  //Inherit parent class

    Child.prototype.constructor = Child // Correct constrcutor pointer as it was pointing to parent class

    Child.prototype.sayHello = function(){
    console.log("say hello from child");
    Parent.prototype.sayHello.call(this);
    console.log(self._protected);
    console.log(self.pro);
    console.log(self.name);
   
    //Parent.prototype.sayHello.call(this); way to call parent call method in child class....
    }

    Child.prototype.sayGoodBye = function(){
    console.log("good bye");
    }


    var childObj = new Child();   // Child.prototype = Object.create(Parent.protoype);

    childObj.sayHello();
    childObj.privilegedMethod();
    childObj.walk();
    console.log(childObj.fixed);
   

function Person(){
  if(Person.count == undefined){
    Person.count = 1;
  }
  else{
    Person.count ++;
  }
  console.log(Person.count);
}

var p1 = new Person();
var p2 = new Person();
var p3 = new Person();



//. In object oriented programing polymorphism is used to call the same method on different objects to have them respond in their own way.
function mainfuncone()
{
this.prop_1 =27;

}

mainfuncone.prototype.polyfuncname=function()
{
this.prop_1 += 10;
}

function mainfunctwo()
{
this.prop_11 =30;

}

mainfunctwo.prototype.polyfuncname=function()
{
this.prop_11 +=10;

}

obj1=new mainfuncone;
obj2=new mainfunctwo;

//call functions
obj1.polyfuncname();
obj2.polyfuncname();

//access properties values by using polymorphism
alert(obj1.prop_1);
alert(obj2.prop_11)

Design patterns implementation in oops JS + fibonocci series/ prime numbers using JS

// SINGLETON PATTERN ****************************

var Foo = function () {
    "use strict";
    if (Foo._instance) {
        //this allows the constructor to be called multiple times
        //and refer to the same instance. Another option is to
        //throw an error.
        return Foo._instance;
    }
    Foo._instance = this;
    //Foo initialization code
};
Foo.getInstance = function () {
    "use strict";
    return Foo._instance || new Foo();
}
   
    var obj1 = Foo.getInstance();
    var obj2 = Foo.getInstance();
   
    console.log( obj1 === obj2);
   
    // SINGLETON PATTERN ****************************
   
    var Foo2 = (function () {
    "use strict";
    var instance; //prevent modification of "instance" variable
    function Singleton() {
        if (instance) {
            return instance;
        }
        instance = this;
        //Singleton initialization code
    }
    //instance accessor
    Singleton.getInstance = function () {
        return instance || new Singleton();
    }
    return Singleton;
}());

    var obj21 = Foo2.getInstance();
    var obj22 = Foo2.getInstance();
   
    console.log( obj21 === obj22);
   
    // MODULE PATTERN ****************************
   
   
   
    var foo23 = (function () {
   
    "use strict";
    var instance;
    function aPrivateFunction() { console.log("i m private method");}
    return {
        foo23: function(){
            return instance = this
        },
        aPublicFunction: function () {
            aPrivateFunction();
            console.log("i m public method");
            }
        };
})();
//var myObj = new foo23();
foo23.customMethod =  function(){console.log("m custom method");};
foo23.aPublicFunction();
//foo23.aPrivateFunction(); //error
foo23.customMethod();

// A function that generates a new function for adding numbers

function addGenerator(num) {
    // Return a simple function for adding two numbers
    // with the first number borrowed from the generator
    return function (toAdd) {
        return num + toAdd
    };
}
// addFive now contains a function that takes one argument,
// adds five to it, and returns the resulting number
var addFive = addGenerator(5);
// We can see here that the result of the addFive function is 9,
// when passed an argument of 4
console.log(addFive(4));   // Which return true




var EmployeeModule = (function () {
    var employeeList = [];
    var allEmployee = function () {
        return employeeList;
    };
    var add = function (employee) {
        employeeList.push(employee);
    };
    var totalCount = function() {
        return employeeList.length;
    };
    return {
        add: add,
        getAll: allEmployee,
        totalCount: totalCount
    };
} ());






function Animal() {

  var walked = false

  function walk() {
    console.log('walking...')
    walked = true
  }

  function hasBeenWalked() {
    console.log(walked);
  }

  return {
    walk: walk
  , hasBeenWalked: hasBeenWalked
  }
}




function Cat() {
  var cat = {}
  var walked = false

  cat.__proto__ = Animal();

  cat.pat = function pat() {
    console.log('being patted')
  }

  cat.lasagna = function lasagna() {
    console.log('Lasagna!')
    walked = true
  }

  return cat
}
var garfield = Cat();
garfield.hasBeenWalked();
 garfield.walk();
 garfield.hasBeenWalked();


 function fibo(n) {
  var f = [];
  for (var c = 0; c < n; ++c) {
    f.push((c < 2) ? c : f[c-1] + f[c-2]);
  }
  console.log(f);
}
fibo(5);
function isPrime(i) {
  for (var c = 2; c <= Math.sqrt(i); ++c)
    if (i % c === 0) return false;
  return true;
}
function primeList(N) {
  var list = [];
   for (var i = 2; i != N; ++i)
     if (isPrime(i)) list.push(i);
  console.log(list);
}
primeList(10);

function MySingletonClass() {

  if ( arguments.callee._singletonInstance )
    return arguments.callee._singletonInstance;
  arguments.callee._singletonInstance = this;

  this.Foo = function() {
    // ...
  }
}

var a = new MySingletonClass()
var b = MySingletonClass()
console.log( a === b ); // prints: true



var foo = {x: 10};

var bar = {
  x: 20,
  test: function () {

    console.log(this === bar); // true
    console.log(this.x); // 20
   
    //this = foo; // error, can't change this value

    console.log(this.x); // if there wasn't an error, then would be 10, not 20

  }

};
bar.test();
foo.test = bar.test;
foo.test();

var a = {
  x: 10,
  calculate: function (z) {
    console.log( this.x + this.y + z);
  }
};

var b = {
  y: 20,
 
  __proto__: a
};

var c = {
  y: 30,
  __proto__: a
};

// call the inherited method
b.calculate(30); // 60
c.calculate(40); // 80


var x = 10;

(function foo() {
  var y = 20;
  (function bar() {
    var z = 30;
    // "x" and "y" are "free variables"
    // and are found in the next (after
    // bar's activation object) object
    // of the bar's scope chain
    console.log(x + y + z);
  })();
})();

Different ways to declare a function in Javascript

1)function A(){};             // function declaration
2) var B = function(){};       // function expression
3) var C = (function(){});     // function expression with grouping operators
4) var D = function foo(){};   // named function expression
5) var E = (function(){        // immediately-invoked function expression (IIFE) that returns a function
  return function(){}
})();
6) var F = new Function();     // Function constructor
7) var G = new function(){};   // special case: object constructor

Tuesday 8 April 2014

JQuery Validation for Array of Input Elements

1) Add validation rule as :-


$().ready(function() {
// validate the comment form when it is submitted
$("#signupForm").validate({
rules: {
"category[]": "required"
},
messages: {
"category[]": "Please select category",
}
});
});
2) Find the checkform function in jquery.validation.js and replace with below code:-
checkForm: function() {
this.prepareForm();
for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
if (this.findByName( elements[i].name ).length != undefined && this.findByName( elements[i].name ).length > 1) {
for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
this.check( this.findByName( elements[i].name )[cnt] );
}
} else {
this.check( elements[i] );
}
}
return this.valid();
}
if wants to makes it work specific to a form not globally just add below code to specific file:-
$.validator.prototype.checkForm = function () {
//overriden in a specific page
this.prepareForm();
for (var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++) {
if (this.findByName(elements[i].name).length != undefined && this.findByName(elements[i].name).length > 1) {
for (var cnt = 0; cnt < this.findByName(elements[i].name).length; cnt++) {
this.check(this.findByName(elements[i].name)[cnt]);
}
} else {
this.check(elements[i]);
}
}
return this.valid();
}

Monday 7 April 2014

Javascript OOPS Questions

Javascript (40 questions)
  1. How would you randomly pick an element from an array named myNumbers?

  2. Which of the following is not a Javascript operator?

  3. A cookie is set using the below Javascript statement. When will it expire?

    document.cookie = "foo=bar;secure";
  4. What is Firebug?

  5. Which of the following is not a popular Javascript framework?

  6. Which of the below can be used to perform an asynchronous request to the web server?

  7. What's computed by this code?

    (function(n){return (n && n*arguments.callee(n-1)) || 1;})(10);
  8. How do you remove a property prop from an object obj?

  9. Assuming a refers to a function, how would you execute a after a delay of one second?

  10. What is JSON?

  11. The below script has some troubles getting the numbers right. What could be wrong?

    var fruitSaladRecipe = "2 apples, papaya, coconut, 5 oranges, apple, banana",
        ingredients = fruitSaladRecipe.split(/,\s+/),
        ingredientHash = {},
        num = 0; // Total number of fruits
    for (var i=0 ; i<ingredients.length ; i++) {
        var ingredient = ingredients[i],
            fruitType = ingredient.match(/(\w+)$/)[1].replace(/s$/, ""),
            numPieces;
        if (/^\d+/.test(ingredient)) {
            var num = ingredient.match(/^(\d+)/)[1];
            numPieces = parseInt(num, 10);
        }else{
            numPieces = 1;
        }
        if (/^(?:banana)$/.test(fruitType)) {
            // Speaking of bananas, let's add some more! Those things are delicious!
            numPieces *= 2;
        }
        num += numPieces;
        if (fruitType in ingredientHash) {
            numPieces += ingredientHash[fruitType];
        }
        ingredientHash[fruitType] = numPieces;
    }
    var message = num + " fruit(s) in total:";
    for (var ingredient in ingredientHash) {
        if (ingredientHash.hasOwnProperty(ingredient)) {
            message += "  " + ingredientHash[ingredient] + " " + ingredient + "(s)";
        }
    }
    alert(message);
  12. What is the return value of setInterval?

  13. Why doesn't the below code open an alert box with the text "foo"?

    function wrapInObject(value) {
        return
        {
            value: value
        };
    }
    alert(wrapInObject("foo").value);
  14. Why doesn't the below code open an alert box with the text "foobar"?

    var a = "foo",
        b = a;
    b += "bar";
    alert(a);
  15. What does the function f do?

    function f(a) {
        return function(b) {
            return a + b;
        };
    }
  16. Why doesn't this work as intended?

    function makeNumberSequenceGenerator(nextValue) {
        return function() {
            return nextValue++;
        };
    }
    alert(makeNumberSequenceGenerator(10).nextValue().nextValue());
  17. Complete the return statement in the function below:

    function isFalseBooleanValue(bool) {
        // return...
    }
  18. What's accomplished by using this construct:

    (function() {
        for (var i=0 ; i<10 ; i++) {
            alert(i);
        }
    })();

    instead of just:

    for (var i=0 ; i<10 ; i++) {
        alert(i);
    }
  19. The below code is added to an existing website (in an external Javascript file), causing some unexpected effects. What's the problem?

    window.onload = function() {
        document.write("Hello, world!");
    };
  20. The below code doesn't work as expected. What could be wrong?

    for (var i=0 ; i<10 ; i++) {
        var button = document.createElement("button");
        button.onclick = function() {
            alert("You clicked button number "+i);
        };
        document.body.appendChild(button).appendChild(document.createTextNode("Button "+i));
    }
  21. The below code doesn't work as expected. What could be wrong? (Assuming that elements with a class of 'button' receive a suitable styling)

    for (var i=0 ; i<10 ; i++) {
        document.body.innerHTML += "<div class='button' id='button"+i+"'></div>";
        document.getElementById("button"+i).onclick = function() {
            alert("You clicked button number "+this.id.replace(/^button/, ""));
        };
    }
  22. How can this function be improved?

    function removeLeadingAndTrailingWhitespaceFromString(str) {
        return str.replace(/(^\s+)|(\s+$)/ig, "");
    }
  23. What seems to be the problem with the below code?

    function StateMachine(initialState) {
        this.state = initialState || 'foo';
        return {
            transition: function() {
                this.state = {foo:'bar', bar:'quux', quux:'foo'}[this.state];
                return this;
            }
        };
    }
    var sm = new StateMachine();
    alert(sm.transition().transition().state);
  24. Why doesn't the below code work as expected? (Assuming Javascript 1.6 support)

    var isOdd = function(n) {return n&1;},
        isDivisibleByThree = function(n) {return !(n%3);},
        addOne = function(n) {return n+1;};
    alert([1,2,3,4,5,6,7].map(addOne).filter(isOdd && isDivisibleByThree).length);
  25. Why doesn't the below code alert "foobar" as expected?

    function StringBuffer(initialStr) {
        this.append(initialStr);
    }
    StringBuffer.prototype = {
        items: [],
        append: function(str) {
            this.items[this.items.length] = str instanceof StringBuffer ? str.toString() : str;
            return this;
        },
        toString: function() {
            return this.items.join("");
        }
    };
    alert(new StringBuffer("foo").append(new StringBuffer("bar")).toString());
  26. Rename f , a , and b to something more suitable:

    function f(a, b) {
        return function() {
            return a.apply(b, arguments);
        };
    }
  27. Why doesn't the below function work as expected?

    var isUndefinedOrNull = function(obj) {
        return /^(?:undefined|null)$/.test(typeof obj);
    };
  28. Why doesn't the following function work?

    function printZeroToNinetyNine() {
        for (var i = 0; i < 100; i += 1) {
            setTimeout(function () {
                console.log(i);
            }, 0);
        }
    }
  29. What is the output of the following function?

    function delayedPrint() {
        for (var i = 0; i < 100; i += 1) {
            (function (value) {
                setTimeout(function () {
                    console.log(i);
                }, 1000 * value);
            }(i));
        }
    }
  30. What is the output of the following piece of code?

    function createObject(name, value) {
        var returnObject = {};
        returnObject[name] = value;
        returnObject['addTo' + name] = function () {
            return value += 1;
        };
        return returnObject;
    }
    var obj = createObject('Property', 100);
    console.log(obj.Property);
    console.log(obj.addToProperty());
    console.log(obj.Property);
  31. Which of the following regular expressions can be used to find all occurrences of two-letter words in a string?

  32. Why doesn't the following regular expression work?

    function hasANumber(value) {
        return /^.*[0-9]*.*$/.test(value);
    }
  33. What does it mean when a function or feature is referred to as "asynchronous"?

  34. How can one ensure that a series of asynchronous calls are invoked in the correct order?

  35. Below is a function for executing asynchronous tasks in parallel. Why doesn't it work as expected?

    function doInParallel(tasks, cb) {
        var numTasks = tasks.length;
        tasks.forEach(function (task) {
            task();
            numTasks -= 1;
            if (numTasks === 0) {
                cb();
            }
        });
    }
    doInParallel([...], function () {
        // Execute only when tasks are complete
    });
  36. What does the `new` operator do when used in conjunction with a function call?

  37. Given the below piece of code, what should `obj.value` be set to in order for the if-condition to be true?

    var obj = {};
    
    obj.value = ???;
    
    if (obj.value === obj.value.value.value) {
    }
  38. Given the below code, which of the following is true:

    var a = '',
        b = '',
        c = {value1: a, value2: b},
        d = {value2: b, value1: a};
  39. Which of the following can set the background color of a DOM element to red?

    var element = document.getElementById('my-element');

  40. Which of the following is an acceptable way to add a click event handler to a DOM element?

    var element = document.getElementById('my-element');

Thursday 3 April 2014

search a text in nested array dynamically in mongoDB nodeJs

db.collectionName.aggregate({"$unwind": "$rootColumn"}, {"$match": {"fieldToSearchOn": new RegExp(var)}}, {"$project": {"_id": 0, "fieldToSearchOn": 1}})

Wednesday 2 April 2014

Using LIKE on nested array in mongoDB using nodeJS

db.collectionName.aggregate({"$unwind": "$nestedRootColumn"}, {"$match": {"columnToSearchOn":/^text/i}}, {"$project": {"_id": 0, "columnToSearchOn": 1}})

find the sum in mongoDB using nodejs

 db.collectionName.aggregate([{$match: {whereColumn: value}}, {$group: {_id: "$fieldToGroup", "total_budget": {$sum: "$column.amount"}}}], function(err, sum) {
console.log(sum[0].total_budget);
});

find the average in nested collection in mongoDB using nodejs

db.collectionName.aggregate([{$match: {"whereColumn": whereCondition}}, {$unwind: '$NestedcolumnToWorkOn}, {$group: {_id: null, "avg": {$avg: "$NestedcolumnToWorkOn.fieldName"}}}], function(err, average) {
console.log(average[0].avg);
});

Monday 31 March 2014

how to get the specific record from nested array in mongoDB using nodeJS

db.collectionName.aggregate({"$unwind": "$nestedArrayColumnName"}, {"$match": {"columnWhereCond": arr[i]}}, {"$project": {"_id": 0, "columnToGet": 1}}, function(err2, rows) {
                for (var i = 0; i < rows.length; i++) {
                     var obj = rows[i];
                    for (var key in obj)
                    {
                        var attrName = key;
                        var attrValue = obj[key];
                        columnVal = attrValue['name'];
                    }
                }
});

Sunday 30 March 2014

get inserted objectId and find record w.r.t objectId in mongoDB using nodeJS

db.collectionName.insert(rows, function(err,docsInserted){
                    var pKey = new Array() 
                    for(var j=0; j<docsInserted.length; j++){
                       var objk = docsInserted[j];
                        for (var keys in objk)
                    {
                        var attrName = keys;
                        var attrValue = objk[keys];
                        if (attrName == "_id") {
                         pKey.push(attrValue);
                        }
                    }
                    }

db.collectionName.update({'_id': {"$in":pKey}}, {$set: {}},{multi:true}, function(err1, updated) {
                                if (err1 || !updated) {
                                    console.log("Not updated");
                                    console.log(err1);
                                } else {
                                    console.log("Updated");
                               }
});