Skip to content

Commit

Permalink
Fix support for caching nspell suggestions
Browse files Browse the repository at this point in the history
Closes GH-21.
Closes GH-22.

Reviewed-by: Titus Wormer <tituswormer@gmail.com>
  • Loading branch information
DeanGaffney committed Apr 12, 2021
1 parent 7802e43 commit 43810a4
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 7 deletions.
18 changes: 11 additions & 7 deletions index.js
Expand Up @@ -148,13 +148,14 @@ function all(tree, file, config) {
}

if (!correct) {
reason = quote(word, '`') + ' is misspelt'

// Suggestions are very slow, so cache them (spelling mistakes other than
// typos often occur multiple times).
if (own.call(cache, word)) {
reason = cache[word]
suggestions = cache[word]
reason = concatPrefixToSuggestions(reason, suggestions)
} else {
reason = quote(word, '`') + ' is misspelt'

if (config.count === config.max) {
file.message(
'Too many misspellings; no further spell suggestions are given',
Expand All @@ -169,13 +170,11 @@ function all(tree, file, config) {
suggestions = checker.suggest(word)

if (suggestions.length !== 0) {
reason +=
'; did you mean ' + quote(suggestions, '`').join(', ') + '?'
cache[word] = reason
reason = concatPrefixToSuggestions(reason, suggestions)
}
}

cache[word] = reason
cache[word] = suggestions || []
}

message = file.message(
Expand All @@ -188,6 +187,11 @@ function all(tree, file, config) {
}
}

// Concatenate the formatted suggestions to a given prefix
function concatPrefixToSuggestions(prefix, suggestions) {
return prefix + '; did you mean ' + quote(suggestions, '`').join(', ') + '?'
}

// Check if a word is irrelevant.
function irrelevant(word) {
return (
Expand Down
37 changes: 37 additions & 0 deletions test.js
Expand Up @@ -120,6 +120,43 @@ test('should warn for invalid words (coverage)', function (t) {
})
})

test('should cache suggestions', function (t) {
t.plan(2)

const retextSpell = retext().use(spell, enGb)

const numberOfChecks = 2

for (let i = 0; i < numberOfChecks; i += 1) {
retextSpell.process('color', function (_, file) {
t.deepEqual(
JSON.parse(JSON.stringify(file.messages)),
[
{
message:
'`color` is misspelt; did you mean `colon`, `colour`, `Colo`?',
name: '1:1-1:6',
reason:
'`color` is misspelt; did you mean `colon`, `colour`, `Colo`?',
line: 1,
column: 1,
location: {
start: {line: 1, column: 1, offset: 0},
end: {line: 1, column: 6, offset: 5}
},
source: 'retext-spell',
ruleId: 'color',
fatal: false,
actual: 'color',
expected: ['colon', 'colour', 'Colo']
}
],
'should emit messages'
)
})
}
})

test('should support `max`, for maximum suggestions', function (t) {
t.plan(1)

Expand Down

0 comments on commit 43810a4

Please sign in to comment.