Created
August 16, 2016 10:54
-
-
Save gouxlord/26ca96c3c888a3ae250ccc75f078d75c to your computer and use it in GitHub Desktop.
Interface by decorator implementation test
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
// thx to David Walsh blog | |
function getArgs(func) { | |
var args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1]; | |
return args.split(',').map(function(arg) { | |
return arg.replace(/\/\*.*\*\//, '').trim(); | |
}).filter(function(arg) { | |
return arg; | |
}); | |
} | |
function createInterface(classObject){ | |
return function(target){ | |
let interfaceMethodNames = Object.getOwnPropertyNames(classObject.prototype) | |
interfaceMethodNames.map((methodName) => { | |
if(!target.prototype[methodName]) throw 'Wrong interface implementation on method: ' + methodName | |
if (typeof classObject.prototype[methodName] === "function") { | |
if(typeof target.prototype[methodName] !== "function") throw 'Wrong interface implementation on method: ' + methodName | |
getArgs(classObject.prototype[methodName]).map((argName) => { | |
if(getArgs(target.prototype[methodName]).indexOf(argName) === -1) throw 'Wrong interface implementation on method argument: ' + methodName + ',' + argName | |
}) | |
} | |
}) | |
} | |
} | |
class interfaceClass { | |
methodOnefunction(){} | |
methodTwo (arg1, arg2){} | |
} | |
const interfaceTest = createInterface(interfaceClass) | |
@interfaceTest | |
class goodClass { | |
methodOnefunction(){} | |
methodTwo (arg1, arg2){} | |
} | |
@interfaceTest | |
class wrongClass { | |
methodOnefunction(){} | |
methodTwo (arg1){} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment