/
sanitize.js
64 lines (54 loc) · 1.45 KB
/
sanitize.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
// Module dependencies
var typechecks = require("./typechecks")
, typeOf = typechecks.typeOf
, nameOf = typechecks.nameOf
, argsOf = typechecks.argsOf;
// Expose sanitize and typechecks
module.exports = exports = sanitize;
exports.typeOf = typeOf;
exports.nameOf = nameOf;
exports.argsOf = argsOf;
exports.argumentsOf = argsOf;
// Sanitize arguments
function sanitize(args, caller, order) {
var _args = [];
if (typeOf(caller) == "Array") {
order = caller;
caller = null;
} else {
var argNames = argsOf(caller)
, sanitized = {};
}
Array.prototype.slice.call(args).forEach(function(arg, oldIndex) {
order.some(function(type, newIndex) {
var found = false;
if (Array.isArray(type)) {
if (type.length == 1 && typeOf(type[0]) == typeOf(arg)) found = true;
else {
type.forEach(function(type) {
if (typeOf(type) == "Function" && typeOf(arg) == nameOf(type)) found = true;
});
}
} else if (typeOf(type) == "Function" && typeOf(arg) == nameOf(type)) {
found = true;
}
if (found) {
_args[newIndex] = arg;
if(caller) sanitized[argNames[newIndex]] = arg;
delete order[newIndex];
}
return found;
});
if (order.length) {
order.forEach(function(type, newIndex) {
var def;
if (Array.isArray(type)) {
def = type[type.length - 1];
_args[newIndex] = def;
if(caller) sanitized[argNames[newIndex]] = def;
}
});
}
});
return caller ? sanitized : _args;
}