-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
getCommandSuggestion.js
37 lines (32 loc) · 1.08 KB
/
getCommandSuggestion.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
'use strict';
const _ = require('lodash');
const levenshtein = require('fast-levenshtein');
const getCollectCommandWords = (commandObject, commandWordsArray) => {
let wordsArray =
Array.isArray(commandWordsArray) && commandWordsArray.length ? commandWordsArray : [];
_.forEach(commandObject, (commandChildObject, commandChildName) => {
wordsArray.push(commandChildName);
if (commandChildObject.commands) {
wordsArray = getCollectCommandWords(commandChildObject.commands, wordsArray);
}
});
return _.uniq(wordsArray);
};
const getCommandSuggestion = (inputCommand, allCommandsObject) => {
let suggestion;
const commandWordsArray = getCollectCommandWords(allCommandsObject);
let minValue = 0;
commandWordsArray.forEach(correctCommand => {
const distance = levenshtein.get(inputCommand, correctCommand);
if (minValue === 0) {
suggestion = correctCommand;
minValue = distance;
}
if (minValue > distance) {
suggestion = correctCommand;
minValue = distance;
}
});
return suggestion;
};
module.exports = getCommandSuggestion;