From 9e7cc42f687b479d96d222b61f76b2a30c7e6507 Mon Sep 17 00:00:00 2001 From: jamesgeorge007 Date: Sat, 28 Mar 2020 13:51:34 +0530 Subject: [PATCH] chore: migrate to leven Credit: @jamesgeorge007 PR-URL: https://github.com/npm/cli/pull/1071 Close: #1071 Reviewed-By: @isaacs EDIT(@isaacs): changed dependency in a separate commit --- lib/utils/did-you-mean.js | 21 ++++++++------------- test/lib/utils/did-you-mean.js | 7 +++++++ 2 files changed, 15 insertions(+), 13 deletions(-) create mode 100644 test/lib/utils/did-you-mean.js diff --git a/lib/utils/did-you-mean.js b/lib/utils/did-you-mean.js index 479f04755d7db..c2bdf159dd118 100644 --- a/lib/utils/did-you-mean.js +++ b/lib/utils/did-you-mean.js @@ -1,17 +1,12 @@ -var meant = require('meant') +const leven = require('leven') -function didYouMean (scmd, commands) { - var bestSimilarity = meant(scmd, commands).map(function (str) { - return ' ' + str - }) - - if (bestSimilarity.length === 0) return '' - if (bestSimilarity.length === 1) { - return '\nDid you mean this?\n' + bestSimilarity[0] - } else { - return ['\nDid you mean one of these?'] - .concat(bestSimilarity.slice(0, 3)).join('\n') - } +const didYouMean = (scmd, commands) => { + const best = commands + .filter(cmd => leven(scmd, cmd) < scmd.length * 0.4) + .map(str => ` ${str}`) + return best.length === 0 ? '' + : best.length === 1 ? `\nDid you mean this?\n${best[0]}` + : `\nDid you mean one of these?\n${best.slice(0, 3).join('\n')}` } module.exports = didYouMean diff --git a/test/lib/utils/did-you-mean.js b/test/lib/utils/did-you-mean.js new file mode 100644 index 0000000000000..0c9c95c7f9e60 --- /dev/null +++ b/test/lib/utils/did-you-mean.js @@ -0,0 +1,7 @@ +const t = require('tap') +const dym = require('../../../lib/utils/did-you-mean.js') +t.equal(dym('asdfa', ['asdf', 'asfd', 'adfs', 'safd', 'foobarbaz', 'foobar']), + '\nDid you mean this?\n asdf') +t.equal(dym('asdfa', ['asdf', 'sdfa', 'foo', 'bar', 'fdsa']), + '\nDid you mean one of these?\n asdf\n sdfa') +t.equal(dym('asdfa', ['install', 'list', 'test']), '')