Feb 27, 2013

JavaScript Coding Questions and Answers



Q. Can you write JavaScript Utils functions for the given scenarios?

Scenario 1: Generate random numbers to break cache in restful service calls? For example, the random numbers can be added as a query parameter to break cache.


function Utils() {

    this.cacheBreaker = function () {
            return ((new Date()).getTime() + '').substr(2,8);   // A string that is different every second
    };
}


Scenario 2: Convert Date format from "YYYYMMDD" to "DD/MM/YYYY". The following examples use regular expressions

function Utils() {

    //For example, from JSON data format YYYYMMDD to GUI display format DD/MM/YYYY. 
    this.dateConvertRestToUser = function (dateInput) {
        var m = dateInput.match(/^([1-9][0-9]{3})([0-9]{2})([0-9]{2})$/);
        if (m) {
            return m[3] + '/' + m[2] + '/' + m[1];
        }
      return null;
    };
 
 //For example, from GUI display format DD/MM/YYYY to JSON data format YYYYMMDD
 this.dateConvertUserToRest = function (dateInput) {
        var m = dateInput.match(/^ *([0-3]?[0-9])\/([0-1]?[0-9])\/([1-2][0-9][0-9][0-9]) *$/);
        if (m) {
            var day = m[1];
            var month = m[2];
            var year = m[3];

            if (day.length == 1) {
                day = '0' + day;
            }
            if (month.length == 1) {
                month = '0' + month;
            }
            return year + month + day;
        }
        return null;
    };
}



Scenario 3: Get the attribute value for a given HTML element and attribute.

function Utils() {

    this.getAttrString = function (attr, element) {
         var attrValue = element.attr(attr);
         if (attrValue && attrValue.length > 0) {
            return attrValue;
         }
        return null;
    };
}


Scenario 4: Extract HTML value form a given tag.

function Utils() {

    this.extractHTMLValue = function (html, tag) {
        var htmlValue = "";

        if (tag != null && html != null) {
            var beginTag = "<" + tag.toUpperCase() + ">";
            var endTag = "</" + tag.toUpperCase() + ">";

            html = html.toUpperCase();

            var beginIndex = html.indexOf(beginTag);
            var endIndex = html.indexOf(endTag);

           if (beginIndex > -1 && endIndex > -1 && endIndex > beginIndex) {
                htmlValue = html.substring(beginIndex + beginTag.length, endIndex);
            }
        }

        return htmlValue;
    };
 
}



Scenario 5: Logging from your JavaScriot at different log levels like debug, info, warn, and error.

function PortalLog(logLevel) {
     
        if (typeof console != 'object' || (typeof console.log != 'function' && typeof console.log != 'object')) {
            logLevel = 4;
        }

        function evalLog(type, args) {
            var evalLog = '';
            for (var i = 0; i < args.length; i++) {
                if (i > 0) {
                    evalLog += ',';
                }
                evalLog += 'args[' + i + ']';
            }
            return eval('console.' + type + '(' + evalLog + ');');
        }

        if (logLevel <= 0) {
            this.log = function () {
                return evalLog('log', arguments);
            }
            this.debug = this.log;
        } else {
            this.log = function () {};
            this.debug = function () {};
        }

        if (logLevel <= 1) {
            this.info = function () {
                return evalLog('info', arguments);
            }
        } else {
            this.info = function () {};
        }

        if (logLevel <= 2) {
            this.warn = function () {
                return evalLog('warn', arguments);
            }
        } else {
            this.warn = function () {};
        }

        if (logLevel <= 3) {
            this.error = function () {
                return evalLog('error', arguments);
            }
        } else {
            this.error = function () {};
        }

}



Q. What’s the difference between these two statements?

var x = 3;

x = 3;


A. The first statement puts the variable in the scope of whatever function it was defined. The second statement places the variable in global scope. Global scope can potentially cause collision with other variables with the same name. Therefore, the keyword var must be used when defining variables, and an anonymous function should be used as a closure if needed, encapsulating multiple functions which can share access to the same set of variables. That makes sure the variables stay sandboxed, accessible only by those functions which need them.

Q. What is the difference between the following 2 statements?

!!(obj1 && obj2);

(obj1 && obj2);



A. The first statement returns a “real” boolean value, because you first negate what is inside the parenthesis, but then immediately negate it again. So, this is like saying something is “not not” truth-a, making it true. The second example simply checks for the existence of the obj1 and obj2, but might not necessarily return a “real” boolean value, instead returning something that is either truth-a or false-a. This can be problematic, because false-a can be the number 0, or an empty string, etc. Simple existence can be truth-a. A “real” boolean will only be true or false.

1 comment:

  1. Time to share expertise, insights, tips, and tricks for using Java technology, leveraging the Java programming language, or extending the Java platform. Fingers crossed waiting for JavaOne India 2013 Hyderabad May 8th and 9th. Register here http://bit.ly/YMPeJ8 today and be part of JavaOne India.

    ReplyDelete