Last active
August 29, 2015 13:56
-
-
Save danatcofo/9116918 to your computer and use it in GitHub Desktop.
turn your typescript modules into functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This is an example of how to turn your typescript modules into functions. | |
*/ | |
function Example(command: string, ...params: any[]): void; | |
function Example(command: string, ...params: any[]): any { | |
var isConstructor = false; | |
if (this instanceof Example && !this.__previouslyConstructedByExample) { | |
isConstructor = true; | |
this.__previouslyConstructedByExample = true; | |
} | |
switch (typeof (Example[command])) { | |
case "function": | |
if (isConstructor) { | |
return (function(cls, args){ | |
function F(): void { | |
return cls.apply(this, args); | |
} | |
F.prototype = cls.prototype; | |
return new F(); | |
})(Example[command], params); | |
} | |
return Example[command].apply(Example, params); | |
case "undefined": throw "unknown command call"; | |
default: | |
if (isConstructor) throw "unknown command call"; | |
return Example[command]; | |
} | |
} | |
module Example { | |
export function Func0(parm1:string): string { | |
var ret = "Func0 was called: parm1 = " + parm1; | |
console.debug(ret); | |
return ret; | |
} | |
export function Func1(parm1:string, parm2: string): string { | |
var ret = "Func1 was called: parm1 = " + parm1 + ", parm2 = " + parm2; | |
console.debug(ret); | |
return ret; | |
} | |
export class Test { | |
public ret: string; | |
constructor(parm1: string, parm2: string){ | |
this.ret = Func1(parm1, parm2); | |
} | |
} | |
} | |
var func0 = Example.Func0("hello world"); | |
var func0_fn = <any>Example("Func0", "hello world"); | |
console.assert(func0 == func0_fn, "single param example") | |
var func1 = Example.Func1("hello", "world"); | |
var func1_fn = <any>Example("Func1", "hello", "world"); | |
console.assert(func1 == func1_fn, "multi param example") | |
var test = new Example.Test("hello", "world"); | |
var test_fn = new Example("Test", "hello", "world"); | |
console.assert(test instanceof Example.Test, "class example"); | |
console.assert(test_fn instanceof Example.Test, "function class example"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment