Created
November 20, 2012 01:28
-
-
Save egonelbre/4115360 to your computer and use it in GitHub Desktop.
go2js Interface pesudo implementation
This file contains hidden or 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
function Interface(decl){ | |
this.decl = decl; | |
this.impl = {}; // map funcname -> type | |
} | |
Interface.prototype = { | |
check : function(typedef){ | |
if(typedef.uuid === undefined){ | |
typedef.uuid = GenerateGloballyUniqueId(); | |
} | |
if(this.impl[typedef.uuid] !== undefined) | |
return this.impl[typedef.uuid]; | |
var matches = true, | |
proto = typedef.prototype; | |
for(var fn in this.decl){ | |
var typefn = proto[fn]; | |
if(typefn === undefined){ | |
// doesn't contain fn | |
matches = false; | |
break; | |
} | |
var signature = this.decl[fn]; | |
if(!sameSignature(typefn.signature, signature){ | |
matches = false; | |
break; | |
} | |
} | |
this.impl[typedef.uuid] = matches; | |
}, | |
assert : function(elem){ | |
if(this.check(elem.constructor)) | |
return elem | |
else | |
throw "Does Not Implement"; | |
} | |
} | |
SomeInterface = new Interface({ | |
someFn : {arg : [Boolean], ret: [Boolean]} | |
}) | |
function someStruct(val){ | |
this.value = val; | |
} | |
someStruct.uuid = "main/someStruct"; | |
someStruct.prototype.someFn = function(val) { | |
return val || (this.value == 5); | |
} | |
someStruct.prototype.someFn.signature = { | |
name : "main.someStruct/someFn", // useful for debugging | |
arg : [Boolean], ret: [Boolean]}; | |
// in the code it would look | |
var value = new someStruct(5); | |
// the type assertion | |
var xxx = SomeInterface.assert(value); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment