Category Archives: #Rx

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

Using And, Then & When in Reactive Extensions

When you look over the list of observable method’s on MSDN I can see that I use maybe 60% of them quite frequently.  I find that I’ll use Do’s or SelectMany etc almost every day and more involved operators like Publish and Merge at least once a week.

Today I wanted to cover 3 operators that I find aren’t used frequently but can be used together to provide powerful synchronization techniques.  The operators are “And”, “Then” and “When”.

The “And” operator

If we look on MSDN for the “And” operator we can see that documentation tells us this “Matches when both observable sequences have an available value.”. Well ok, that sounds pretty simple.  I reckon I can put some code together to show how this works.   I just need two streams which both produce a value. Let’s have a try.

Hmmm, well firstly that reads well.  I can see quite easily from reading this code what its intent is, but what I expected as a result of the “And” operator was another IObservable which I could then subscribe to.  So it seems on its own the “And” operator doesn’t work as I expected.  When I look at the return type for “And” I can see it returns something called a “Pattern” and the only operator I can apply to this seems to be a “Then”.

The “Then” Operator

So it seems I have been led to the “Then” operator by some clever design decisions from the Rx designers.  They obviously want me the use the then operator as its really the only thing available to me.  Therefore I better go back to msdn and see what it tells me “Observable.Then<TSource, TResult> Method – Matches when the observable sequence has an available value and projects the value.”.  Well this operator seems very familiar, its almost exactly the same as the “Select” operator.  The select operator takes the value that is pushed to it and transforms the pipeline by returning a different return type.  I can do that!!! lets implement “Then” and we are done right?

Uh oh!! Dead end.  Well this isn’t good.  The one thing that gets me through with LINQ and RX is that operators are discoverable and now I’ve got nowhere to go.  Digging a little deeper I can see that actually what I thought I would get back from “Then” an IObservable<T> what I’m  actually getting is a Plan<T>.  What the heck is a Plan? Why does it have no methods on it so I can do something with it? I’m going to have to do some research.

The “When” Operator

Back to msdn looking for a Plan<T> lets see what it tells us. “Represents an execution plan for join patterns.”  Well that makes sense as that’s essentially what I have been trying to do.  But unfortunately its not giving me the answers for how I actually get values from my stream.  Therefore it’s time to stretch my google-fu and see what I can find.  Turn’s out all the information I needed was actually at the same msdn page I had been looking at for other observable operators.   When I search the page for “Plan” I found that only 1 operator seems to be able to use this construct and thats the “When” operator.

This time I’m told that the “When” operator takes in a Plan<T> and returns a IObservable<T> “Joins together the results from several patterns.”. Yes! This looks like the final piece of the puzzle.  Lets finish the code.

As you can see from the code above, I now use the When operator on my plan so that we can actually gain access to the projected values. Then I write the values to the console window.  The slower stream is in essence the regulating stream in this scenario and therefore the stream only pumps once every 10 seconds.

Summary

As you can see the three operators “And”, “Then” and “When” working together provide some powerful synchronization primitives that we can use in our code to solve a number of different scenarios.  Discovery of these operators is a little trickier than the basic operators and I feel that a few extensions could have been added to make life easier (Why no “When” extension on a Plan<T> for example?).