Skip to content

Instantly share code, notes, and snippets.

@FrankGrimm
Created July 29, 2010 23:47
Show Gist options
  • Save FrankGrimm/499534 to your computer and use it in GitHub Desktop.
Save FrankGrimm/499534 to your computer and use it in GitHub Desktop.
Abbreviation for command line parameters in node.js
// Example code for node-abbrev
var abbrevlib = require("node-abbrev");
var sys = require("sys");
// valid run modes for the imaginary tool
var validModes = ["help", "start", "stop", "status"];
// create Abbreviate instance for the modes
// second parameter (case sensitivity) optional, defaults to false
var abbrev = new abbrevlib.Abbreviate(validModes);
// .expand() the first command line parameter
var choice = abbrev.expand(process.argv[2]);
if (!choice.length) {
// the given parameter did not match anything
// expanding an empty string will return all modes
console.log('Please provide a valid mode (' + abbrev.expand('').join(', ') + ').');
} else if (choice.length == 1) {
console.log('Active mode: ' + choice[0]);
} else {
console.log('Mode parameter was ambiguous, matches: ' + choice.join(', '));
}
/*
* Abbreviation lookup helper for small amounts of terms.
* Inspired by http://search.cpan.org/~pinyan/Text-Abbreviate-0.01/
*
* @version 0.1.0
* @author Frank Grimm (http://frankgrimm.net)
*
*/
/*
// Example for node-abbrev:
var sys = require("sys");
var abbrevlib = require("node-abbrev");
var abbrev = new abbrevlib.Abbreviate(["help", "start", "stop"], false);
console.log(sys.inspect(abbrev.expand("he"))); // [ 'help' ]
console.log(sys.inspect(abbrev.expand("start"))); // [ 'start' ]
console.log(sys.inspect(abbrev.expand("started"))); // []
console.log(sys.inspect(abbrev.expand("st"))); // [ 'start', 'stop' ]
console.log(sys.inspect(abbrev.expand(""))); // [ 'help', 'start', 'stop' ]
*/
var Abbreviate = function(wordList, actCaseSensitive) {
var wordList = wordList || [];
var caseSensitive = actCaseSensitive || false;
this.__defineGetter__("caseSensitive", function(){
return caseSensitive;
});
this.__defineSetter__("caseSensitive", function(val){
caseSensitive = val;
});
this.containsWord = function(theWord) {
return this.wordList.some(function(element) {
// oder function(element, index, array) {}
return this.caseSensitive ? element == theWord : element.toLowerCase() == theWord.toLowerCase();
// theWord.toLowerCase could most likely be done upfront
});
}
this.addWord = function(theWord) {
if (!containsWord(theWord))
wordList.push(theWord);
}
this.expand = function(lookupWord) {
var testRegExp = new RegExp("^" + lookupWord, "");
testRegExp.ignoreCase = this.caseSensitive;
return wordList.filter(function(currentWord) {
return currentWord.match(testRegExp);
});
}
}
exports.Abbreviate = Abbreviate;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment