forked from jsx-eslint/eslint-plugin-jsx-a11y
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
getSuggestion.js
24 lines (21 loc) · 800 Bytes
/
getSuggestion.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
import editDistance from 'damerau-levenshtein';
import fromEntries from 'object.fromentries';
// Minimum edit distance to be considered a good suggestion.
const THRESHOLD = 2;
/**
* Returns an array of suggestions given a word and a dictionary and limit of suggestions
* to return.
*/
export default function getSuggestion(word, dictionary = [], limit = 2) {
const distances = fromEntries(
dictionary.map((dictionaryWord) => {
const distance = editDistance(word.toUpperCase(), dictionaryWord.toUpperCase());
const { steps } = distance;
return [dictionaryWord, steps];
}),
);
return Object.keys(distances)
.filter((suggestion) => distances[suggestion] <= THRESHOLD)
.sort((a, b) => distances[a] - distances[b]) // Sort by distance
.slice(0, limit);
}