Monday, March 28, 2016

TypeScripting AngularJS 1.x - Define module

As we know developing and maintaining a large application in pure JavaScript is really tough. One of the reason is its dynamic typing or its not TypeSafe. If we want to change a variable or function name that's it. There is no way to identify where all it used until we run. Of course we can do text search. But its difficult from the tooling perspective. So people going to TypeScript to develop JavaScript applications.

AngularJS is a JavaScript framework for developing enormous apps. If we use TypeScript there, we get more advantage. Since any valid JavaScript is valid TypeScript, people tend to write JavaScript inside TypeScript files without leveraging TypeScript features. But it works. It will definitely give difficulties in long term when maintaining the code.This series is aimed at how we can leverage TypeScript to code AngularJS application in the TypeSafe (compile time) way

Defining module 

It is easy.to define an Angular module via JavaScript.
var app = angular.module("<moduleName>", []);

But lets see how can we do it via TypeScript. Please note this require TypeDefinitions for AngularJS. If we are using Visual Studio, this can be installed via 'angularjs.TypeScript.DefinitelyTyped' package
var app: ng.IModule = angular.module("<moduleName>", []);

Then we can register controllers, services and directives to it. by calling app.controller(), service(), directive() respectively. But is that an object oriented way? Absolutely not. We need to wrap it inside a class. Lets see one sample below.
module CountryApplication {
    "use strict";
    export class CountryModule {
        private static _constructor = (() => {
            var countryApp: CountryModule = new CountryModule();
            countryApp.setup();
        })();
        app: ng.IModule;
        constructor() {
            this.app = angular.module("CountryApp", []);
        }
        setup() {
            var app1: ng.IModule = angular.module("<moduleName>", []);
            this.setupServices();
            this.setupControllers();
            this.setupDirectives();
            this.setupRoutes();
        }
        private setupServices(): void {
            this.app.service("CountryMetaDataService", ["$http",'$q',CountryMetaDataService]);
        }
        private setupControllers(): void {
            this.app.controller("CountryController",
                ['$scope', '$http','CountryMetaDataService', CountryController]);
        }
        private setupDirectives(): void {
            this.app.directive
        }
        private setupRoutes(): void {
        }
    }
}
We can see the things we were doing in Angular with JavaScript. But here we are just organizing, as a class. This gives us one view about our services, directives, controllers and how they are related each other.

The downside of this is every time a developer adds a new controller or service they need to modify this file.

Links

Tuesday, March 22, 2016

Caution JavaScript Ahead - toString(2) is not returning right output always

Introduction

There is Number.toString() method in JavaScript. Passing 2 to this function convert number to binary string. But is it returning right value always?

Background

This require electronics or computer science background as its talking more about internal of computing machine such as 2's complement. But people who do programming without that background can also have a try reading this article.

Converting positive numbers toString(2)

Look at the below code which convert number to string by passing 2 as argument to get binary string representation.

var binary= (6).toString(2); 
alert(binary);

Output
110

This works perfect.

Converting negative numbers toString(2)

Lets convert a negative number to binary using the same technique.

var binary= (-6).toString(2); 
alert(binary);

Output
-110

This looks simple as we are getting the binary digits which is equal to absolute value(value without sign) of number. This is easy to understand for a person who don't have computer science of electronics background. But are we getting right binary representation of -6? No. Its wrong.

2's complement representation

In computer, it stores the data including numbers in binary as it knows only 2 states. On or Off or 1 or 0 respectively. We can store signed numbers as well as unsigned numbers. For signed numbers it require one bit to denote the sign. If the number variable has maximum 4 bits to store, it can store up to -8 to +7 in case, it needs to support -ve numbers. If it is unsigned data type, it can store from 0-15 ie 0 to 24 -1.

Another point to note is the storage mechanism of -ve numbers. One bit is not just kept for sign. Instead it stores as 2's complement. It does so to do add operation easily. Lets see how its represented by taking 4 bit number data type for easy understanding

6 - 0110 - a positive number
-6 - 1010 - Representing -6 in 2's complement

But look at the out put which showed -110 earlier for -6. Ideally the output should be the 2's complement (1010) based on the data type length.

Finding 2's complement

The steps are simple. Find the 1's complement by inverting bits. Then add 1 to the result. Lets see how -5 can be written in 2's complement way. Here first write the binary representation of 5 without sign.

0101 - Leading 0 is required as the data type length we took here is 4.
1010 - Just replace 0s with 1s and 1s with 0s.This is 2s complement.
1011 - Added 1 to get 2s compliment.

Hope its clear and we can easily calculate it for any number. There are online tools available to convert. Try those to learn faster.

Trouble of showing (-binaryNumber) in toString(2)

Normally there is no problem when the negative number is converted as shown in the above sample. -110 for -6 instead of 1010. But it gets complicated when we deal with bit-wise operations such as shifting bits in -ve number and convert to string. Look at the below snippet.


var binary= (6>>1).toString(2); 
alert(binary);
binary= (-6>>1).toString(2); 
alert(binary);

Output - 
11
-11

This gives an impression that the number is just converted to binary regardless of sign and shift the bits right once.

00000000 00000000 00000000 00000110 - Binary of 6
00000000 00000000 00000000 00000011 - After shifting bits one time to right

Added zeros as JavaScript does bit wise operations using 32 bit.

Now check the below example

var binary= (7>>1).toString(2); 
console.log(binary);
binary= (-7>>1).toString(2); 
console.log(binary);

Output - 
11
-100

We could see that the +ve number 7 is simply shifted right and -7 is not. This is because we are expecting just -11 which is nothing but adding -ve sign to  11. 

00000000 00000000 00000000 00000111 - Binary of 6
00000000 00000000 00000000 00000011 - After shifting bits one time to right

We may think that -100 is wrong only because we have understanding that the computer is handling -7 as just 7 with a sign in front of it. In reality, it stores 2's complement which is not what we are seeing when we displayed it using toString(2). Lets see how we got -100

11111111 11111111 11111111 11111001 - 2's complement of -7
11111111 11111111 11111111 11111100 - After shifting bits one time to right

Finding the number from 2's complement 

Its the simple 'reverse process in order' what we did for finding 2's complement.
11111111 11111111 11111111 11111011 - Subtracted one
00000000 00000000 00000000 00000100 - Inverted bits (replace 0s with 1s and viceversa)

This is why we are seeing -100 when we converted to binary using toString(2) after shifting. Try how its working for -6 to get same -11 for +3 and -3.

Conclusion

Number.toString(2) is not showing the 2's complement representation of number which is used internally. But the bit wise operations work on 2's complement.

If we don't understand the 2's complement and we do shifting business with -ve numbers thinking they just have additional sign. Sometime we will see its working (see the case of +6 & -6). But it may fail for other numbers.

Points of Interest

If (-7).toString(2) returned 11111111 11111111 11111111 11111001 it would have been easier to understand how the numbers are stored inside computers. But in the other hand this makes it difficult to understand for common people. Now it is not advisable to change the behavior as there are so many apps written on the current working of toString(2). Those may fail because of correction. May be another overload will help.

There are improvement done in JavaScript which does in new ways to fix issues in old implementation. == and === is the famous example.

Tuesday, March 15, 2016

TypeScript - Some bascis & setting up the environment

Introduction to series

TypeScript is relatively new language from Microsoft to write JavaScript in structured way with class and interfaces. It transpiles to JavaScript to execute in browser. Means no TypeScript runtime is required. Its open source and leverage features which are going to come in future JavaScript versions. Currently it transpiles to ES 5 version of JavaScript. Since its converted to JavaScript, we can get rid of it anytime and continue using the generated JavaScript. More details in their home page.

Basics

According to me its just another language with it's own syntax. But the interesting thing is TypeScript is super set of JavaScript. All the valid JavaScript programs are valid TypeScript programs. So to starting ts is easy as rename .js files to .ts.

Importance

There is no meaning in going behind some buzzwords and wasting the time. AngularJS team is writing Angular 2 in TypeScript. But they are telling we can write our ng2 apps in JavaScript. So that should not be the reason for us to invest in TS.

Lets see why we need to learn TypeScript for surviving.

JavaScript is dynamic typed.

Developing in JavaScript is very difficult. Especially when its a big project. I have started a series "Caution JavaScript Ahead" on the same. It doesn't tell what will break if we do refactor. There are tools like JSLint and JSHint. But still its a problem.

Any time your method might get a new definition. The below code execution will stop console.log writing to the browser console for all the subsequent calls.

console.log= function(msg){alert('I do nothing');}

May be TS cannot solve all the shortcomings of JS. But many things will be easy when using TypeScript

Structured JavaScript

We can have/workaround namespaces in JavaScript. But its difficult. TS makes it very much easy. We can write namespace the same way of Java/C#.

We can have inheritance in pure JavaScript. But its little difficult for a normal OOP developer. TypeScript makes it easy with the class keyword. In fact ES 6 has the class keyword.

Setting up environment

It can be done with notepad of course but requires the TypeScript compiler to convert to JavaScript. At the time of writing this post the latest released version is TS 1.6 and there are plans will TS 1.8. The TypeScript installer which includes the compiler can be downloaded from their home page.

Visual Studio is perfect editor when combining with web essentials extension. Then we get a split view where we can see the TS in left and corresponding JS in right. Each save will compile and right side will be refreshed.

The location of tsc.exe the compiler is C:\Program Files (x86)\Microsoft SDKs\TypeScript\<version> on windows machine

NPM

If the development environment is different with support for node npm, TS can be installed using 

npm install -g typescript

Learning TypeScript

Microsoft provided an online playground for TS. We can learn the language features there without installing anything in our computer. The home page itself gives pretty good documentation without going to MSDN.

Working TS and JS together 

The obvious question when moving to TypeScript is what to do with the pure JavaScript libraries. Can I use jQuery library from TypeScript? Yes we can via the type definition files. They bridge the gap and make the JavaScript libraries available to TS. More details on how to write type definition files later.

Debugging TypeScript

Debugging support is essential for any language. If TypeScript is compiled to JavaScript it can be debugged via F12 developer tools in browser. IE helps to debug the code as TypeScript itself. Visual Studio also gives us the debugging support.

Tuesday, March 8, 2016

Caution JavaScript Ahead - Is length good to loop arrays?

This is not to prove one particular method as the best method. But just to understand different behaviors. It can be considered as an extension to below post about same.

http://joymonscode.blogspot.com/2015/08/multiple-ways-to-iterate-array-in.html

Looping using array.length

Look at the below code

var arr = [];

function addElementTo100thPosition() {
    arr[100] = "Hundred"
    console.log("Added element to 100th position. Length of array:" + arr.length);
}
function printArrayByLoopingLength() {
    for (var i = 0; i < arr.length; i++) {
        console.log("Element at " + i + " is "+ arr[i]);
    }
}

What it will display if the printArrayByLoopingLength() is called after addElementTo100thPosition() is executed? First of all, will there be any error if we directly add element to 100th position?

There won't be any confusion on adding item to 100th position directly. Its possible. If that is possible we should be able to iterate till that element. So it should iterate 100 times. For that length must be 100. Yes all is right. The output will be like below

Element at 0 is undefined
Element at 1 is undefined
Element at 2 is undefined
Element at 3 is undefined
Element at 4 is undefined
Element at 5 is undefined
Element at 6 is undefined
.....
Element at 100 is Hundred


This is because the length means the highest integer index + 1. Not the number of elements. of.If we display the array via JSON it will look as follows everything converted to null.

function printArray(){
    console.log(JSON.stringify(arr,null,2));
}
[ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, "Hundred" ]

Is this a good behavior? We can say it depends. If we have an algorithm which fills data into an array randomly, we can use it. But if we think of iterating the elements, this is not the right way. Lets see another way in next post.

Here lets see one more scenario.

Adding elements to array with non integer index

What it one element is indexed with string not like numbered.

function addElementWithStringIndex(){
    arr["name"] = "Joy"
    console.log("Added element to 10th position. Length of array:" + arr.length);
}

If we call the printArrayByLoopingLength() after calling the above function, what we will get.

It will be same as above. Try to call printArray() which uses JSON.stringify(). Its still the same output. It don't get the element indexed with string key.

What happened to the element "Joy" we added to the array. Lets display using arr.name

function printArrOfName(){
    console.log("arr['name'] is " +arr["name"]);
}

It displays the value.
arr['name'] is Joy

What does it mean. The string indexed element became a property. Try the below

function printArrDotName(){
    console.log("arr.name = " +arr.name);
}

The output will be

arr.name = Joy

Array.push

One more scenario. What will happen if we using push() method instead of directly putting into the array?

function pushToArray(){
    arr.push("Pushed element");
}

Now call the methods in below order
  • addElementTo100thPosition
  • pushToArray()
  • printArrayByLoopingLength
The output will be
Added element to 10oth position. Length of array:101 Element at 0 is undefined Element at 1 is undefined Element at 2 is undefined Element at 3 is undefined Element at 4 is undefined Element at 5 is undefined ... ... Element at 100 is Hundred Element at 101 is Pushed element

push insert the element to the end of the array. It looks for length and insert after that. It uses integer index. Even if we call printArray() the JSON string will be correct with the pushed element.

Moral of the story

  • Do not index using string if its really going to be an array. Use integer to index array.
  • Use push to insert into array.
  • Do not iterate using length because it depends on last element's index not real no of elements.
What the best practice? Lets see in coming posts.

Tuesday, March 1, 2016

npm install karma in windows 8 ends with error TRK0005: Failed to locate: "CL.exe"

I was recently working with Travis-CI to setup CI & CD for a pure browser app/static web site. Details are there in a previous post. Karma is the one decided to use as test runner. Things were good till the time I start installing Karma into local node folder using --user-dev. The error I got is as follows when installing Karma.

Building the projects in this solution one at a time. To enable parallel build,
please add the "/m" switch.
TRACKER : error TRK0005: Failed to locate: "CL.exe". The system cannot find the
 file specified. [C:\Users\<user name>\AppData\Roaming\npm\node_modules\karma\node_mod
ules\bufferutil\build\bufferutil.vcxproj]

gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe` fail
ed with exit code: 1

It turns out though it says NPM module its using lot of C++ inside. Karma cannot be built without C++ compiler. When I googled most of the people are saying it never tested in Windows machines. I was not in a situation to go to a Linux machine for this. After spending more time with google, I could see that it requires VS 2015 with Visual C++ language support.

Reinstalled VS 2015 with C++ features and it worked.

Moral of the story - Open source is still mainly for Linux developers :)