Skip to content

Instantly share code, notes, and snippets.

@bramblex
Last active October 7, 2016 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bramblex/493bfb60786afe1d6bfef17dba58dfb9 to your computer and use it in GitHub Desktop.
Save bramblex/493bfb60786afe1d6bfef17dba58dfb9 to your computer and use it in GitHub Desktop.
function ncr(router){
var path = process.argv.slice(2);
var current, i;
var next = router;
for(i=0; i<path.length; i++){
current = next;
next = next[path[i]];
if (typeof next === 'object') continue; else break;
}
if (typeof next === 'function'){
var args_needed = next.toString().match(/^(function|)\s*\S*\s*\((.*?)\)/)[2]
.split(',').filter(function(item){return item.trim() !== ''});
var args = path.slice(i+1);
if (args_needed.length !== 0 && args.length !== args_needed.length ){
throw new Error('Command "'+path[i]+'" need agruments: '+args_needed.map(function(item){return '<'+item+'>'}).join(' '));
} else {
return next.apply(current, args);
}
} else if (typeof next === 'object'){
if (typeof next['?'] === 'function') return next['?'].apply(next, path.slice(i+1));
throw new Error('Need more arguments, like '+JSON.stringify(Object.keys(next).filter(function(item){return item !== '?'})))
} else {
throw new Error('Command "'+path[i]+'" not found. Do you mean '+JSON.stringify(Object.keys(current).filter(function(item){return item !== '?'})))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment