Skip to content

Instantly share code, notes, and snippets.

@buschtoens
Created September 8, 2012 17:06
Show Gist options
  • Save buschtoens/3677258 to your computer and use it in GitHub Desktop.
Save buschtoens/3677258 to your computer and use it in GitHub Desktop.
Argument sanitization
// 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" });
// 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;
}
@buschtoens
Copy link
Author

When using strict mode, you'll have to work with the returned array, since manipulating arguments is forbidden.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment