Skip to content

Instantly share code, notes, and snippets.

@stash
Created March 27, 2012 16:40
Show Gist options
  • Select an option

  • Save stash/2217776 to your computer and use it in GitHub Desktop.

Select an option

Save stash/2217776 to your computer and use it in GitHub Desktop.
optify.js - refactor long function parameters into "pass an opts object" style
/*
* optify.js - refactor long function parameters into "pass an opts object" style
*
* vim instructions:
* 1) Using shift-v, select `function (a,b,c,d,e,cb) {`
* 2) Type ":!node ~/optify"
* 3) Selection is replaced with:
* function (opts,cb) {
* var a = opts.a;
* var b = opts.b;
* ...
*/
var code = '';
stdin.on('data', function(chunk) { code += chunk.toString('utf8'); });
stdin.on('end', optify);
stdin.resume();
var FUNC = /^(\s*)(.*?function[^\)]+\()([^\)]*)(\)\s*\{)/;
var CB = /(?:^cb|^next|^callback|^continuation|(?:cb))$/i
function optify() {
var match = code.match(FUNC);
if (!match) {
stdout.write(code);
return;
}
var indent = match[1];
var declIndent = (indent !== undefined && indent.length) ? indent : ' ';
var funcDecl = match[2];
var rawParams = match[3];
var blockStart = match[4];
var leadIn = match.index > 0 ? code.substr(0, match.index) : '';
var leadOut = code.substr(match.index + match[0].length, code.length);
var params = rawParams.split(/\s*,\s*/);
var isCPS = CB.test(params[params.length-1]); // Continuation Passing Style
var newParams = 'opts';
if (isCPS) newParams += ', '+params.pop();
if (params.length === 1 && params[0] === '') params = [];
var newDecls = params.map(function(param) {
return "\n"+indent+declIndent+"var "+param+" = opts."+param+";"
}).join('');
stdout.write(leadIn + indent + funcDecl + newParams + blockStart + newDecls + leadOut);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment