Skip to content

Commit

Permalink
feat: update Levenshtein to Damerau-Levenshtein (#1973)
Browse files Browse the repository at this point in the history
  • Loading branch information
thrien committed Jul 12, 2021
1 parent c804f0d commit d2c121b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
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

0 comments on commit d2c121b

Please sign in to comment.