-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interface.js
98 lines (75 loc) · 2.69 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
function Interface (interfaceName, methodNames, propertyNames) {
if (typeof interfaceName !== 'string') {
throw new Error('Unexpected type');
}
this.interfaceName = interfaceName;
methodNames = methodNames || [];
propertyNames = propertyNames || [];
this.methodNames = methodNames.map(function (methodName) {
if (typeof methodName !== 'string') {
throw new Error('Unexpected method type');
}
return methodName;
});
this.propertyNames = propertyNames.map(function (propertyName) {
if (typeof propertyName !== 'string') {
throw new Error('Unexpected property type');
}
return propertyName;
});
}
Interface.prototype.isImplemented = function (obj) {
if (obj === null || obj === undefined) {
return false;
}
var notImplMethodNames = this.checkMethods(obj);
var notImplPropertyNames = this.checkProperties(obj);
if (notImplMethodNames.length > 0 || notImplPropertyNames.length > 0) {
return false;
}
return true;
};
Interface.prototype.ensureImplemented = function (obj) {
if (obj === null || obj === undefined) {
throw new Error('Obj has to be sth');
}
var notImplMethodNames = this.checkMethods(obj);
var notImplPropertyNames = this.checkProperties(obj);
var errorMessage = createErrorMessage(notImplMethodNames, notImplPropertyNames, this.interfaceName);
if (errorMessage.length > 0) {
throw new Error(errorMessage);
}
function createErrorMessage (notImplMethodNames, notImplPropertyNames, interfaceName) {
var errorMessage = '';
if (notImplMethodNames.length > 0 || notImplPropertyNames.length > 0) {
errorMessage += 'Object does not implement ' + interfaceName + ' interface.\n';
}
if (notImplMethodNames.length > 0) {
errorMessage += 'Missing methods: ' + notImplMethodNames.join(', ') + '.';
}
if (notImplPropertyNames.length > 0) {
errorMessage += notImplMethodNames.length > 0 ? '\n' : '';
errorMessage += 'Missing properties: ' + notImplPropertyNames.join(', ') + '.';
}
return errorMessage;
}
};
Interface.prototype.checkMethods = function (obj) {
var notImplementedMethodNames = [];
this.methodNames.forEach(function (methodName) {
if (!obj[methodName] || typeof obj[methodName] !== 'function') {
notImplementedMethodNames.push(methodName);
}
});
return notImplementedMethodNames;
};
Interface.prototype.checkProperties = function (obj) {
var notImplementedPropertyNames = [];
this.propertyNames.forEach(function (propertyName) {
if (!obj[propertyName] || typeof obj[propertyName] === 'function') {
notImplementedPropertyNames.push(propertyName);
}
});
return notImplementedPropertyNames;
};
module.exports = Interface;