-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interface.js
49 lines (39 loc) · 1.49 KB
/
Interface.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* @author Patrick Wolleb
*/
/**
* Class Interface
*
* Emulates Interface that is known from classic languages such as Java, C++, C#
*
* Usage:
*
* var Foo = new Interface('Foo', ['method1' , 'method2']);
*
* var objectImplementingFoo = new ObjectImplementingFoo();
* Interface.check(objectImplementingFoo, Foo);
*
*/
var Interface = function(name, methods) {
if(arguments.length != 2) throw new Error('Interface::constructor -- Incorrect number of arguments: Expected 2 received ' + arguments.length);
this.name = name;
this.methods = [];
for(var i = 0, l = methods.length, m = null; i < l; ++i) {
m = methods[i];
if(typeof m !== 'string') throw new Error('Interface::constructor -- Methods expected to be passed as strings');
this.methods.push(m);
}
}
Interface.check = function(object) {
if(arguments.length < 2) throw new Error('Interface::check -- Incorrect number of arguments: Expected at least 2 received ' + arguments.length);
var interFace, m;
for(var i=1, l = arguments.length; i < l; ++i) {
console.log(i , arguments[i]);
interFace = arguments[i];
if(interFace.constructor != Interface) throw new Error('Interface::check -- Arguments 2 and above expected to be of type Interface');
for(var j=0, l=interFace.methods.length; j < l; ++j) {
m = interFace.methods[j];
if(!object[m] || typeof object[m] !== 'function') throw new Error('Interface::check: object does not implement ' + interFace.name + 'Method ' + m + ' was not found.');
}
}
}