1 | var fs = require('fs')
|
2 | var leven = require('leven')
|
3 | var wordListPath = require('@pg3dmodule/word-list')
|
4 |
|
5 | var readDictionary = function(path) {
|
6 | path || (path = wordListPath)
|
7 | return fs.readFileSync(path).toString().trim().split('\n')
|
8 | }
|
9 |
|
10 | var autocorrect = function(options) {
|
11 | options || (options = {})
|
12 | var dictionary = options.words || readDictionary(options.dictionary)
|
13 | var len = dictionary.length
|
14 |
|
15 | return function(str) {
|
16 | var distance, bestWord, i, word, min
|
17 |
|
18 | for (i = 0; i < len; i++) {
|
19 | word = dictionary[i]
|
20 | distance = leven(str, word)
|
21 |
|
22 | if (distance === 0) {
|
23 | return word
|
24 | } else if (min === undefined || distance < min) {
|
25 | min = distance
|
26 | bestWord = word
|
27 | }
|
28 | }
|
29 |
|
30 | return bestWord
|
31 | }
|
32 | }
|
33 |
|
34 | module.exports = autocorrect
|