-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathannotations.js
62 lines (52 loc) · 1.58 KB
/
annotations.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
/**
* Example how annotations can be easily added to JavaScript functions, however there is no need in this
* as unlike in statically typed languages in JavaScript it is already possible to add various fields to functions
*/
(function() {
if (Function.prototype._annotations) {
return;
}
function parseAnnotation(name, body) {
var annotation = {
name: name
};
return body ? body.split(',').reduce(function(acc, keyValue) {
keyValue = keyValue.split('=');
acc[keyValue[0]] = keyValue[1];
return acc;
}, annotation) : annotation;
}
function parseAnnotations(code) {
var annotations = [];
var regex = /\/\/@([a-zA-Z0-9_]+)(?:\((.*)\))?/g;
var match = regex.exec(code);
while (match) {
annotations.push(parseAnnotation(match[1], match[2]));
match = regex.exec(code);
}
return annotations;
}
Object.defineProperty(Function.prototype, '_annotations', {
get: function() {
return parseAnnotations(this.toString());
},
enumerable: true,
configurable: true
});
})();
/*
* Example of usage:
*/
function funcWithAnnotations(x, y) {
//@Annotation1(key1=value1,key2=value2,key3=value3)
//@Annotation2(key4=value4)
//@Annotation3
return x + y;
}
function funcWithoutAnnotations(x, y) {
return x - y;
}
//[{"name":"Annotation1","key1":"value1","key2":"value2","key3":"value3"},{"name":"Annotation2","key4":"value4"},{"name":"Annotation3"}]
console.log('funcWithAnnotations = ', funcWithAnnotations._annotations);
//[]
console.log('funcWithoutAnnotations = ', funcWithoutAnnotations._annotations);