Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade Levenshtein to Damerau-Levenshtein #1973

Merged
merged 12 commits into from Jul 12, 2021
24 changes: 17 additions & 7 deletions lib/utils/levenshtein.ts
Expand Up @@ -21,6 +21,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

// levenshtein distance algorithm, pulled from Andrei Mackenzie's MIT licensed.
// gist, which can be found here: https://gist.github.com/andrei-m/982927
// extended to compute damerau-levenshtein distance

// Compute the edit distance between the two given strings
export function levenshtein(a: string, b: string) {
Expand All @@ -47,13 +48,22 @@ export function levenshtein(a: string, b: string) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j - 1] + 1, // substitution
Math.min(
matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j] + 1
)
); // deletion
if (
i > 1 &&
j > 1 &&
b.charAt(i - 2) === a.charAt(j - 1) &&
b.charAt(i - 1) === a.charAt(j - 2)
) {
matrix[i][j] = matrix[i - 2][j - 2] + 1; // transposition
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j - 1] + 1, // substitution
Math.min(
matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j] + 1
)
); // deletion
}
}
}
}
Expand Down
12 changes: 12 additions & 0 deletions test/yargs.cjs
Expand Up @@ -423,6 +423,18 @@ describe('yargs dsl tests', () => {
r.errors[2].should.match(/Did you mean goat/);
});

it('counts tranposition as one mistake', () => {
const r = checkOutput(() => {
yargs(['baot'])
.command('boat')
.command('bot')
.recommendCommands()
.parse();
});

r.errors[2].should.match(/Did you mean boat/);
});

// see: https://github.com/yargs/yargs/issues/822
it('does not print command recommendation if help message will be shown', done => {
const parser = yargs().command('goat').help().recommendCommands();
Expand Down