Created
September 8, 2012 17:06
-
-
Save buschtoens/3677258 to your computer and use it in GitHub Desktop.
Argument sanitization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Module dependencies | |
var sanitize = require("./sanitize.js"); | |
// function createConnection(String host, Number port, Object credentials, Array data) | |
function createConnection(host, port, credentials, data) { | |
sanitize(arguments, [String, Number, Object, Array]); | |
console.log(host, port, credentials, data); | |
} | |
// Test it | |
// port, data, host, credentials -> host, port, credentials, data | |
createConnection(80, ["send this", "and this"], "localhost", { user: "silvinci", password: "secret" }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Expose sanitize | |
module.exports = exports = sanitize; | |
exports.typeOf = typeOf; | |
exports.nameOf = nameOf; | |
// Type check helpers | |
function typeOf(o) { | |
return Object.prototype.toString.call(o).match(/(\w+)\]/)[1]; | |
} | |
function nameOf(o) { | |
return typeOf(o) == "Function" | |
? Function.prototype.toString.call(o).match(/function (\w+)/)[1] | |
: false; | |
} | |
// Sanitize arguments | |
function sanitize(args, order) { | |
Array.prototype.slice.call(args).forEach(function(arg, oldIndex) { | |
order.forEach(function(type, newIndex) { | |
if(typeOf(arg) == nameOf(type)) args[newIndex] = arg; | |
}); | |
}); | |
return args; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When using strict mode, you'll have to work with the returned array, since manipulating
arguments
is forbidden.