Last active
April 21, 2016 02:14
-
-
Save seflless/80ca6cbc33232c438680 to your computer and use it in GitHub Desktop.
This file contains 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
// Regular commander.js logic up here. None of this | |
// logic is run if a subcommand match was found | |
var knownSubCommands = [ | |
"blah", | |
"ha", | |
"etc" | |
] | |
// Detect if the sub command was missspelled | |
var found; | |
knownSubCommands.forEach( function(subCommand) { | |
if(process.argv[2] === subCommand){ | |
found = true; | |
} | |
}); | |
// Not found, notify user of their miss spelling and suggest the closest match | |
// and how to find the list of commands | |
if(!found){ | |
var hamming = require( 'compute-hamming' ), | |
closestSubCommands = []; | |
// First try to find if any commands start with the letters of the arg | |
knownSubCommands.forEach( function(subCommand) { | |
if(subCommand.search(process.argv[2]) === 0){ | |
closestSubCommands.push(subCommand); | |
} | |
}); | |
if(closestSubCommands.length === 0){ | |
// Find the closest match | |
var closestDistance = Number.MAX_SAFE_INTEGER; | |
knownSubCommands.forEach( function(subCommand) { | |
// hamming() requires the commands to be of the same length. So we need to | |
// to clip the longer one and consider each clipped character to be one edit | |
var string1 = subCommand, | |
string2 = process.argv[2], | |
distance = 0; | |
if(string1.length < string2.length){ | |
distance = string2.length - string1.length; | |
string2 = string2.slice(0,string1.length); | |
} else if(string1.length > string2.length){ | |
distance = string1.length - string2.length; | |
string1 = string2.slice(0, string2.length); | |
} | |
distance += hamming(string1, string2); | |
if( distance < closestDistance){ | |
closestDistance = distance; | |
closestSubCommands = [subCommand]; | |
} | |
}); | |
} | |
console.log("jibo: '" + process.argv[2] + "' is not a jibo command. See 'jibo --help' for the list of commands."); | |
console.log(""); | |
if(closestSubCommands.length === 0){ | |
console.log("Did you mean this?"); | |
} else { | |
console.log("Did you mean one of these?"); | |
} | |
closestSubCommands.forEach( function(subCommand){ | |
console.log(" " + subCommand); | |
}); | |
} |
This file contains 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
{ | |
"dependencies": { | |
"compute-hamming": "^1.1.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment