Cracking a problem with TypeScript

Last week Microsoft announced TypeScript. A new JavaScript superset which adds static typing annotations as well as language support for classes and modules to the JavaScript language. As a C# developer since the .net 1.0 beta days, you can imagine I am pretty comfortable in a static languages and while that is fine most of the time the trend is for more apps to run in the browser. This normally involves me dusting off my JavaScript skills and entering back into the wild work of dynamic scripting.

It is this wild world of the future where HTML5 apps which run in the browser is where TypeScript should offer a lot of help to application developers. The concept of making coding in the browser easier is not a new one and languages such as CoffeeScript and Dart are showing that devs have an appetite for it. Both of the aforementioned languages have tried to tackle the problem in different ways, but what I like about TypeScript is that it is not trying to abandon JavaScript but instead apply a level or rigor to it that hopefully will become standards compliant in the future.

With all that in mind, I decided to build a little sample app to test out some of the features. Before you get started you will want to download the Visual Studio plugin to help with the development of your app. Also I recommend having a read through the TypeScript spec which has a wealth of information on what features the language offers. The app I decided to build was a little code cracker which is based on a Genetic Algorithm. This is not a very advanced implementation of GA as the fitness function and mutations are not very sophisticated. However is does give me the level of complexity I needed to test the language out.

The problem

In my app I wanted a simple ui where someone could enter a numeric code of 50 chars which I would then attempt to crack. Using a population of random keys to start with, each key’s fitness needs to be tested against the crack key, the strongest key based on fitness is the only survivor and its DNA becomes the basis for the next generation. Each generation has a mutation factor of 10% which ensures that the key should evolve over time an eventually the 50 char crack key will be found. Below is an example of my UI and my typescript code to run the algorithm.

$(Document).ready(() =>
{
    var decryper = new System.Crytography.Genetics.Decrypter();
    var crackButton = $("#crackCodeButton");
    $("#inputCodeBox").val(decryper.GenerateRandomKey());

    crackButton.click(() =>
    {
        var code = $("#inputCodeBox").val();
        var processingStatusElement = document.getElementById("processingStatus");
        var decryper = new System.Crytography.Genetics.Decrypter();

        decryper.Decrypt(code, processingStatusElement);
    });
});

Importing Libraries

This first thing you can see in this code is that I am using the JQuery library from within TypeScript. This is a fundamental design decision from the TypeScript team, in that any JavaScript library can be consumed within typescript with no changes required. What is also cool is that any JavaScript library currently out there can have an additional typing annotations file (think C++ header file) which a developer can import into their TypeScript project and start to work with the library in type safe way. This static typing on the api is one of the major benefits of using TypeScript IMHO.

Currently if a JavaScript library makes breaking changes to its api these changes can be very difficult to pick up in your code using tests alone. TypeScript will make this positively easy. A further benefit is that none of this typing information is outputted or checked in your JavaScript code which makes the resulting JS closely match your TypeScript. This I believe is an advantage over CoffeeScript and Dart for example which the resulting code can be vastly different from your source.

Namespaces, Classes and Interfaces

Next up I wanted to see how in TypeScript we can build hierarchical api’s with all the richness that we get in .net. Again I am no l33t JavaScript programmer so how you go about building hierarchical apis currently I am not sure but my hunch is that it cannot be done. I see a lot of people simulating OOP concepts like inheritance using protypes etc but all of these to me feel like hacks.

In TypeScript the designers have set about designing a language that they hope will fall inline with the emerging ECMAScript 6 standards. While there are no guarantees, I think this is a good strategy and one that shows their willingness to make TypeScript the most open of all the higher level browser languages. To support hierarchical namespaces in the language developers can use modules which allow classes and interfaces to be grouped under a logical area. In my sample I created a fake namespace using dot notation which TypeScript supports. One cool thing to note about modules is that you can define them across files, and the TypeScript compiler is smart enough to locate them all and show all your classes in the visual studio intellisense.

module System.Crytography.Genetics {

    interface IDecrypter {
        Decrypt(code: string, statusElement: HTMLElement);
        GenerateRandomKey(): string;
    }

    export class Decrypter implements IDecrypter {

        public Decrypt(code: string, drawingPanel: HTMLElement) {
        }

        private GenerateKey() {
        }

        private CheckFitness() {
        }

        private CreatePopulation() {
        }

        private GenerateMutatedKey(currentkey: string): string {
        }

        public GenerateRandomKey(): string {
        }
    }

}

In the code above you can see that I have defined a simple module with and interface and class for my Decrypter. What’s great about this is that interfaces become a first class citizen within TypeScript which means you build the appropriate levels of abstractions and code to contracts. A lot of the semantics of defining classes and interfaces from c# translate well into TypeScript and other than a few naming issues I found creating interfaces, inheriting them and defining functions and constructors etc to be very familiar. Full TypeScript code below if you’re interested in the detail

module System.Crytography.Genetics {

    interface IDecrypter {
        Decrypt(code: string, statusElement: HTMLElement);
        GenerateRandomKey(): string;
    }

    export class Decrypter implements IDecrypter {
        private _code: string;
        private _keyGenerated = false;
        private _workingKey = "";
        private _fitnessLevel = 0;
        private _keySize = 50;
        private _population = new Array(5);
        private _mutationPercentage = 10;
        private _drawingPanel: HTMLElement;
        private _generations = 0;

        public Decrypt(code: string, drawingPanel: HTMLElement) {

            var start = new Date().getTime();
            this._code = code;
            this._drawingPanel = drawingPanel;

            while (!this._keyGenerated) {
                this.GenerateKey();

                this._keyGenerated = this._workingKey == this._code;
            }

            var time = new Date().getTime() - start;

            this._drawingPanel.textContent = "It took " +
                time / 1000 + " seconds to decrypt the key.  Generation Count: "
                + this._generations;
        }

        private GenerateKey() {
            this.CreatePopulation();

            this.CheckFitness();
        }

        private CheckFitness() {

            this._generations++;

            for (var i = 0; i < this._population.length ; i++) {
                var keyFitness = 0;
                var key = this._population[i]

                for (var j = 0; j < key.length ; j++) {                     if (key.charAt(j) == this._code.charAt(j)) {                         keyFitness++                     }                 }                 if (keyFitness > this._fitnessLevel) {
                    this._fitnessLevel = keyFitness;
                    this._workingKey = key;
                    this._drawingPanel.textContent = keyFitness
                        + " of " + this._keySize + "chars found";
                }
            }
        }

        private CreatePopulation() {
            for (var i = 0; i < this._population.length ; i++) {
                var key = "";
                if (this._workingKey.length == 0) {
                    key = this.GenerateRandomKey();
                }
                else {
                    //Ensure strongest candidate survives.
                    if (i == 0) {
                        key = this._workingKey;
                    }
                    else {
                        key = this.GenerateMutatedKey(this._workingKey);
                    }
                }

                this._population[i] = key;
            }
        }

        private GenerateMutatedKey(currentkey: string): string {
            var newKey = currentkey;
            var charChangeCount = (currentkey.length / 100) * this._mutationPercentage;

            for (var i = 0; i < charChangeCount ; i++) {
                var index = Math.floor(Math.random() * currentkey.length);
                var newChar = Math.floor(Math.random() * 10).toString();
                newKey = newKey.substr(0, index) + newChar + newKey.substr(index + 1);
            }

            return newKey;
        }

        public GenerateRandomKey(): string {
            var key = "";
            for (var i = 0; i < this._keySize ; i++) {
                key = key + Math.floor(Math.random() * 10).toString();
            }

            return key;
        }
    }

}

.Netters will feel very comfortable

The language often feels like a blend of C# and Visual Basic. Little things crop up as you work with the language such as the way the “var” keyword behaves, mimicking the c# one with type inference. Also it helps that all the curly braces are in all the right places which is what you would expect from a c-based language. “Implements” for example is the keyword you use to inherit an interface which can map back to Visual Basic. Best of all however is that “Fat Arrow” “() =>” is supported so you can avoid the verbosity of “function”. I wonder if the design team made a conscious effort to do this or if it just naturally fell out. That’s said however, there are obviously enough differences to make TypeScript distinctly separate from both C# & VB.

Conclusion

Overall I found using TypeScript extremely satisfying and I am excited as to what the future hold for the language. We already know that they intend to support Generics. But long term could we see statically typed versions of LINQ, RX etc. Also the tooling I can see coming on leaps and bounds. I have already heard mutterings on twitter of TypeScript support from JetBrains which would be awesome!

If you want to try the app you can find it here.  Two words of caution however,  I only tested on IE10 and also I block the UI thread while performing the computation.  Yeah yeah I know……………..shoot me! 🙂

Advertisements

Tagged:

4 thoughts on “Cracking a problem with TypeScript

  1. leeoades October 10, 2012 at 8:31 pm Reply

    Excellent stuff Dave. Thanks for taking the time to write it up so thoroughly.

    • lordhanson October 10, 2012 at 8:53 pm Reply

      Cheers man. Typescript is awesome. Try it if you haven’t.

  2. […] “Cracking a problem with TypeScript” […]

  3. […] my previous post where I tested out some of the features of the TypeScript language I built a small GA based […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: