-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
105 lines (96 loc) · 2.46 KB
/
index.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
99
100
101
102
103
104
105
var typeo = {};
typeo.dev = true;
typeo.types = {};
typeo.typesDef = {};
function checkType (typeName, value, typeObj) {
if (typeObj[typeName]) {
var type = typeObj[typeName];
return type.checkType(type.obj, value);
}
return false;
}
function isOfType (type, value) {
return typeof value === type;
}
function isInstanceOf (type, value) {
return value instanceof type;
}
function addTypeDef (typeDef, typeDefs, types) {
var name = typeDef.name;
if (!typeDef.checkType) {
if (typeDef.obj) {
switch (typeof typeDef.obj) {
case 'string':
typeDef.checkType = isOfType;
break;
case 'function':
typeDef.checkType = isInstanceOf;
break;
default:
typeDef.checkType = function noop () { return false; };
}
}
}
types[typeDef.name] = typeDef.name;
typeDefs[typeDef.name] = typeDef;
}
function init() {
if (!typeo.dev) {
return;
}
addTypeDef({
name: 'string',
obj: 'string'
}, typeo.typesDef, typeo.types);
addTypeDef({
name: 'number',
obj: 'number'
}, typeo.typesDef, typeo.types);
// any is any type but undefined and null
addTypeDef({
name: 'any',
checkType: function (type, value) {
if (value !== undefined && value !== null) {
return true;
}
return false;
}
}, typeo.typesDef, typeo.types);
addTypeDef({
name: 'function',
obj: 'function'
}, typeo.typesDef, typeo.types);
addTypeDef({
name: 'Date',
obj: Date
}, typeo.typesDef, typeo.types);
}
init();
typeo.declare = function (args, fn, context) {
if (!typeo.dev) {
return fn;
}
return function () {
var optionalArgsCount = 0;
for (var i = 0; i < args.length; i++) {
if (args[i].optional) {
optionalArgsCount++;
}
}
if (args.length === arguments.length || args.length - optionalArgsCount === arguments.length) {
for (var i = 0; i < arguments.length; i++) {
if (!checkType(args[i].type, arguments[i], typeo.typesDef)) {
var type = args[i].type;
throw new Error('type mismatch (arg ' + i + '), got: ' + typeof arguments[i] + ', expected: ' + type);
}
}
return fn.apply(context, arguments);
} else {
throw new Error('arguments length mismatch, got: ' + arguments.length + ', expected: ' + args.length);
}
}
}
typeo.addTypeDef = function (typeDef) {
return addTypeDef(typeDef, typeo.typesDef, typeo.types);
};
module.exports = typeo;