Wednesday, January 28, 2015

JavaScript "constants"

I did a bit of research about constants in JavaScript. Well guess what, there are no constants in JavaScript. :)

So how do you implement "constants" with JavaScript patterns and syntax?

Note: The next text might require more readings but if will help you learn lot of JavaScript basics. Probably you will never have to use this code, since existing JS librarires have already solved this issue somehow.

Constants are important concept of every programming language and definetelly you should use them whenever possible. For example let just say you have an error message that needs to be printed in the output field from several places in your code. How are you sure that each time you write that string of message is written without missing letters? Sometimes you are tired, sometimes you rush and therefore errors are inevitable. So to prevent this you create a constant that contain that string and use the constant instead of writing the string.

Example constant: CANNOT_DIVIDE_BY_ZERO = "Cannot divide by zero!";

I have been developing a practice application which you can access live here: http://jspractices-blueplayer.rhcloud.com/Calculator/ and the docs are here: http://jspractices-blueplayer.rhcloud.com/Calculator/docs
Also you may preview the HTML/JavaScript code here: https://github.com/bluePlayer/practices/tree/master/CalculatorJS.
The code also passes JSLint test, with only "jslint browser: true" option.

There are two important functions which you should check, Constants() and namespace().
Constants() is a constructor function and namespace() creates subobject of the main application object called window.APP.
Lets start with namespace() function. It recieves two parameters, first the name of the subobject that will be created and second is the configuration object which contains necessary properties and methods that will be contained in this new subobject. namespace() creates new subobject Constants using the new keyword, secondly creates constMap subobject which will contain accessible keys for each of the constants.

Example:

window.APP.namespace('Trigonometry', (function () {
    return {
        PI: 3.14,
        doSomeStuff: function () {

        }
    }
}()));

This example creates Trigonometry subobject of window.APP and Trigonometry contains two subobjects, Constants with methods, get(), set(), isDefined() and list() and constMap which has one key/value, PI: "PI" and ofcourse the function doSomeStuff() which does nothing.

So with my solution you can create immutable constants by just passing key/value pair (key must be all capitalized letters) and the code will create it for you. Well if we create a PI constant how do we get the value? The solution is straight forward but it looks very ugly and big.

Example:

console.log(window.APP.Trigonometry.Constants.get(window.APP.Trigonometry.constMap.PI));
// prints 3.14

Alternatively you can pass the name of the constant if you know it:

console.log(window.APP.Trigonometry.Constants.get("PI"));

hahah :D

To improve this solution a bit I created an application wide function in APP namespace called getConst(). You send the path of the constant in string format.

Example:  

console.log(window.APP.getConst('APP.Trigonometry.PI')); // prints 3.14

What happens in this function is parsing the string parameter and getting to the constant value trough the application tree. But this solution is against the "Constants" concept. Either I should be careful to write that string parameter properly or I should create a variable/property inside APP to contain that string and then use it in the above example, like so:

window.APP = window.APP || (function () {
    var TRIGONOMETRY_PI =  'APP.Trigonometry.PI';
    return { 
        getConst: function (constantPath) {
            // code
        },
        doSomeStuff: function () {
               console.log(this.getConst(TRIGONOMETRY_PI)); 
        }
    }
}()));

window.APP.doSomeStuff(); // prints 3.14


So this brings us to the best solution to the problem, and that is creating variables with capitalized letters in closure and then using capitalized accessor methods for them.

Example: I will create GRAVITY = 9.8 constant in new subobject of APP, called Physics.
window.APP.namespace('Physics', (function () {
    var GRAVITY = 9.8;
    return {
          GRAVITY: function () {
               return GRAVITY;
         }
    };
}()));

console.log(window.APP.Physics.GRAVITY()); // prints 9.8

This will create subobject Physics in window.APP and it will contain constMap object with one key/value pair, GRAVITY which is function(). I changed namespace() function to create function in constMap if the capitalized key contains value of a function instead of a value.  If I just send this key/value pair: GRAVITY: 9.8, the namespace() function would have created key/value pair in constMap, like so: GRAVITY: "GRAVITY" and you have to access constant's value using the long statement in the previous examples.

To clear things up, you don't even need to create Constants() constructor in your application, you can use variable with closure and accessor methods with capitalized names to represent constants. I created this constMap subobject just to separate constants from other properties/methods in a given object. You don't even need it.

Note: there are some rummors that ECMAScript 7 or was it 6, will contain const keyword. Until then you can use capitalized variable and methods with closure to represent "constants".

If you have any thoughts on the topic, let me know.


Thursday, January 8, 2015

JavaScript Patterns - practice application

Hello. In this post I will explain some JavaScript patters using a script I made.
I have being reading this book: JavaScript Patterns by Stoyan Stefanov, and I covered half by now.

 You can download the script from this link https://github.com/bluePlayer/practices/tree/master/CalculatorJS

I also wrote comments for each property/method/object/module in YuiDoc format and generated in Java style, documentation using YuiDoc Node.js extension. For more info check this link: http://yui.github.io/yuidoc/

So the name of my application is APPLICATION and it is written with capitalized letters because it is global variable. Some JS coding convetions say that you should write constants and globals with capitalized letters because it is easier to distingush from other properties/variables.

It is always good to initialize main application object if it doesn't exist, or prevent initiazlization if it already exist:

var APPLICATION = {};
if (typeof APPLICATION === "undefined") {
    var APPLICATION = {};
}
// shorter
var APPLICATION = APPLICATION || {};

While I was reading "JavaScript Patterns" it mentioned a general namespace function which enables you to create objects and subobjects by just sending dot notated string, like this: "my.new.object".
I made some improvements to this function and added it as a part of the application's namespace, like this:

APPLICATION.namespace = function (nsString, newObjectDefinition) {
    var parts = nsString.split('.'),
        parent = this,
        newObject = {};
       
    newObject.Constants = new this.Constants();
    newObject.constMap = {};
   
    if (parts[0] === this.getName()) {
        parts = parts.slice(1);
    }
   
    for (var i = 0; i < parts.length; i += 1) {
        if (typeof parent[parts[i]] === "undefined") {           
            for (var property in newObjectDefinition) {
                if (property === property.toUpperCase()) {
                    newObject.Constants.set(property, newObjectDefinition[property]);
                    newObject.constMap[property] = property;
                } else {
                    newObject[property] = newObjectDefinition[property];
                }
            }
            parent[parts[i]] = newObject;
        }
        parent = parent[parts[i]];
    }   
   
    return parent;
};


I added a second parameter which adds functionality to the last object created in the tree. So if the fisrt parameter is string: "my.new.object", the function will create three objects, my, new and object in the APPLICATION's tree and object will be initialized with properties and functions from the second parameter. I also added two more subobjects inside every newly created object, so my, new, object will have Contants and constMap objects. Constants is object which gets created with Constants() constructor (from APPLICATION) and it contains, set(), get(), isDefined(), list(). On the other hand constMap contains the keys for calling constants using the get() function. So to get a constant value you should do this:

var myVar = APP.subModule.Constants.get(APP.subModule.constMap.CONST_NAME);

Note: This looks quite clumsy and big. Lot of letters to write. Perhaps it will be easier to write in some JS IDE like WebStrom. Anyway, at the time of writing this code I realised there is a place for improvement. Maybe there should be one general get() function for constants in the application.

As you can see from the application I use namespace pattern. All constructors, methods, events, properties, submodules should be part of one general object. Also I have submodules like, Main, Trigonometry, EventFunctions  and all related properties or methods are kept in its own submodule. This is called module pattern.

What if I want to add static properties? Well you can do it easily by just adding a new property to a given object or subobject. You can also use prototype part of the object and it will be inherited.
example:

var MyObject = function () {};
MyObject.name = "TunePHP";
var newObject = new MyObject();
typeof newObject.name === "undefined" //true
MyObject.prototype.name = MyObject.name;
console.log(newObject.name); // "TunePHP";

It is always useful to have a main init() method for the whole application, where you will initialize all necessary objects/variables/properties after the page has loaded.

Here is the complete code I wrote. Let me know your thoughts.

var APPLICATION = APPLICATION || {
    name: "Calculator",
    version: "1.0.0",
    Constants: function () {},
    namespace: function () {},
    getName: function () {
        return name;
    },
   
    init: function (config) {
        try {
            this.Calculator.Main.currentState = this.Calculator.Main.Constants.get(this.Calculator.Main.constMap.STANDARD);
            this.Calculator.Trigonometry.currentAngleFormat = this.Calculator.Trigonometry.Constants.get(this.Calculator.Trigonometry.constMap.DEGREES);
            return this;
        } catch (error) {
            console.log(error.message);
            return false;
        }
    }
};

APPLICATION.Constants = function (constMapObject) {
    var constants = {},
        ownProp = Object.prototype.hasOwnProperty,
        allowed = {
            string: 1,
            number: 1,
            boolean: 1
        },
        prefix = (Math.random() + "_").slice(2);
       
    return {
   
        set: function (name, value) {
            if (this.isDefined(name)) {
                return false;
            }
            if (!ownProp.call(allowed, typeof value)) {
                return false;
            }
                   
            constants[prefix + name] = value;
            /**
             * @todo use constMapObject to create new constant key in the given constants map object.
             */
            return true;
        },

        isDefined: function (name) {
            return ownProp.call(constants, prefix + name);
        },
       
        get: function (name) {
            if (this.isDefined(name)) {
                return constants[prefix + name];
            }
            return null;
        },
       
        list: function () {
            var index = 0,
                newStr = "";
               
            for (constant in constants) {
                index = constant.indexOf('_');
                newStr = constant.substr(index + 1);
                console.log(newStr + ": " + constants[constant]);
            }
        }
    };
};

APPLICATION.namespace = function (nsString, newObjectDefinition) {
    var parts = nsString.split('.'),
        parent = this,
        newObject = {};
       
    newObject.Constants = new this.Constants();
    newObject.constMap = {};
   
    if (parts[0] === this.getName()) {
        parts = parts.slice(1);
    }
   
    for (var i = 0; i < parts.length; i += 1) {
        if (typeof parent[parts[i]] === "undefined") {           
            for (var property in newObjectDefinition) {
                if (property === property.toUpperCase()) {
                    newObject.Constants.set(property, newObjectDefinition[property]);
                    newObject.constMap[property] = property;
                } else {
                    newObject[property] = newObjectDefinition[property];
                }
            }
            parent[parts[i]] = newObject;
        }
        parent = parent[parts[i]];
    }   
   
    return parent;
};

 APPLICATION.namespace('Calculator', {
   
});

APPLICATION.namespace('Calculator.Main', {
   
    STANDARD: 1,

    SCIENTIFIC: 2,

    PROGRAMMER: 3,
   
    currentState: null,

    currentValue: 0,

    memoValue: 0,
   
    digitGrouping: false,
   
    historyPanel: false,
   
    unitConversionPanel: false,

    dateCalculationPanel: false,

    changeState: function (event) {
        /**
         * @todo currentState = event.newState;
         */
    },
       
    showHistoryPanel: function (event) {
        /**
         * @todo
         */
    },
       
    showUnitConversionPanel: function (event) {
        /**
         * @todo
         */
    },

    showDateCalculationPanel: function (event) {
        /**
         * @todo
         */
    }
});

APPLICATION.namespace('Calculator.Trigonometry', {

    DEGREES: "degrees",
   
    RADIANS: "radians",

    GRADS: "grads",
   
    currentAngleFormat: null
});

APPLICATION.namespace('Calculator.EventFunctions', {

    pressZero: function (event) {
   
    },

    pressOne: function (event) {
   
    },

    pressTwo: function (event) {
   
    },
   
    pressSum: function (event) {
   
    },

    pressSubtract: function (event) {
   
    },
   
    pressMultiply: function (event) {
   
    },

    pressDivide: function (event) {
   
    }
});

APPLICATION.init({});