Wednesday, March 9, 2016

TypeScript: Identity Combinator

My last post was about creating an identity combinator for JavaScript that could serve as a starting point for creating further combinators. Since I also mainly program in TypeScript I wanted to present the "TypeScript" way of doing this which looks more like a Java or C#.

class BasicDecorator {
    public static identitityDecorator(target, name, property) {
        var fn = property.value;
        property.value = function(...args) {
            var returnedValue = fn.apply(this,args);
            return returnedValue;
        }
    }
}

class Foo {
    @BasicDecorator.identitityDecorator
    myFunction(x:string,y:number,z:number): string {
        var a = y + z;
        return "hey "+x+" your sum is "+a;
    }
}

var foo = new Foo();
foo.myFunction("Will",5,8);

You could also do stuff with having state in your decorator class that is used by the decorators. You have to be careful with the meaning of this, but their are potential applications like building a generic caching mechanism.

No comments:

Post a Comment