-
Notifications
You must be signed in to change notification settings - Fork 469
feat: suggest close matches using Levenshtein distance [POC] #836
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
371923b
implement close-matches api
dougbacelar 5dac03a
implement closest matches suggestions on testId query
dougbacelar 788dbc2
remove empty lines
dougbacelar e69fd6b
add extra test
dougbacelar b12cb29
simplify conditional
dougbacelar cd54847
add computeCloseMatches config option
dougbacelar 8ee261f
remove custom implementatin of levenshtein
dougbacelar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
import { | ||
calculateLevenshteinDistance, | ||
getCloseMatchesByAttribute, | ||
} from '../close-matches' | ||
import {render} from './helpers/test-utils' | ||
|
||
describe('calculateLevenshteinDistance', () => { | ||
test.each([ | ||
['', '', 0], | ||
['hello', 'hello', 0], | ||
['greeting', 'greeting', 0], | ||
['react testing library', 'react testing library', 0], | ||
['hello', 'hellow', 1], | ||
['greetimg', 'greeting', 1], | ||
['submit', 'sbmit', 1], | ||
['cance', 'cancel', 1], | ||
['doug', 'dog', 1], | ||
['dogs and cats', 'dogs and cat', 1], | ||
['uncool-div', '12cool-div', 2], | ||
['dogs and cats', 'dogs, cats', 4], | ||
['greeting', 'greetings traveler', 10], | ||
['react testing library', '', 21], | ||
['react testing library', 'y', 20], | ||
['react testing library', 'ty', 19], | ||
['react testing library', 'tary', 17], | ||
['react testing library', 'trary', 16], | ||
['react testing library', 'tlibrary', 13], | ||
['react testing library', 'react testing', 8], | ||
['library', 'testing', 7], | ||
['react library', 'react testing', 7], | ||
[ | ||
'The more your tests resemble the way your software is used, the more confidence they can give you.', | ||
'The less your tests resemble the way your software is used, the less confidence they can give you.', | ||
8, | ||
], | ||
])('distance between "%s" and "%s" is %i', (text1, text2, expected) => { | ||
expect(calculateLevenshteinDistance(text1, text2)).toBe(expected) | ||
}) | ||
}) | ||
|
||
describe('getCloseMatchesByAttribute', () => { | ||
test('should return all closest matches', () => { | ||
const {container} = render(` | ||
<div data-testid="The slow brown fox jumps over the lazy dog"></div> | ||
<div data-testid="The rapid brown fox jumps over the lazy dog"></div> | ||
<div data-testid="The quick black fox jumps over the lazy dog"></div> | ||
<div data-testid="The quick brown meerkat jumps over the lazy dog"></div> | ||
<div data-testid="The quick brown fox flies over the lazy dog"></div> | ||
`) | ||
expect( | ||
getCloseMatchesByAttribute( | ||
'data-testid', | ||
container, | ||
'The quick brown fox jumps over the lazy dog', | ||
), | ||
).toEqual([ | ||
'The quick black fox jumps over the lazy dog', | ||
'The quick brown fox flies over the lazy dog', | ||
]) | ||
}) | ||
|
||
test('should ignore matches that are too distant', () => { | ||
const {container} = render(` | ||
<div data-testid="very-cool-div"></div> | ||
<div data-testid="too-diferent-to-match"></div> | ||
<div data-testid="not-even-close"></div> | ||
`) | ||
expect( | ||
getCloseMatchesByAttribute('data-testid', container, 'normal-div'), | ||
).toEqual([]) | ||
}) | ||
|
||
test('should ignore duplicated matches', () => { | ||
const {container} = render(` | ||
<div data-testid="lazy dog"></div> | ||
<div data-testid="lazy dog"></div> | ||
<div data-testid="lazy dog"></div> | ||
<div data-testid="energetic dog"></div> | ||
`) | ||
expect( | ||
getCloseMatchesByAttribute('data-testid', container, 'happy dog'), | ||
).toEqual(['lazy dog']) | ||
}) | ||
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
import {makeNormalizer} from './matches' | ||
|
||
const initializeDpTable = (rows, columns) => { | ||
const dp = Array(rows + 1) | ||
.fill() | ||
.map(() => Array(columns + 1).fill()) | ||
|
||
// fill rows | ||
for (let i = 0; i <= rows; i++) { | ||
dp[i][0] = i | ||
} | ||
|
||
// fill columns | ||
for (let i = 0; i <= columns; i++) { | ||
dp[0][i] = i | ||
} | ||
return dp | ||
} | ||
|
||
export const calculateLevenshteinDistance = (text1, text2) => { | ||
const dp = initializeDpTable(text1.length, text2.length) | ||
|
||
for (let row = 1; row < dp.length; row++) { | ||
for (let column = 1; column < dp[row].length; column++) { | ||
if (text1[row - 1] === text2[column - 1]) { | ||
dp[row][column] = dp[row - 1][column - 1] | ||
} else { | ||
dp[row][column] = | ||
Math.min( | ||
dp[row - 1][column - 1], | ||
dp[row][column - 1], | ||
dp[row - 1][column], | ||
) + 1 | ||
} | ||
} | ||
} | ||
return dp[text1.length][text2.length] | ||
} | ||
|
||
const MAX_LEVENSHTEIN_DISTANCE = 4 | ||
|
||
export const getCloseMatchesByAttribute = ( | ||
attribute, | ||
container, | ||
searchText, | ||
{collapseWhitespace, trim, normalizer} = {}, | ||
) => { | ||
const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer}) | ||
const allElements = Array.from(container.querySelectorAll(`[${attribute}]`)) | ||
const allNormalizedValues = new Set( | ||
allElements.map(element => | ||
matchNormalizer(element.getAttribute(attribute) || ''), | ||
), | ||
) | ||
const iterator = allNormalizedValues.values() | ||
const lowerCaseSearch = searchText.toLowerCase() | ||
let lastClosestDistance = MAX_LEVENSHTEIN_DISTANCE | ||
let closestValues = [] | ||
|
||
for (let normalizedText; (normalizedText = iterator.next().value); ) { | ||
if ( | ||
Math.abs(normalizedText.length - searchText.length) > lastClosestDistance | ||
) { | ||
// the distance cannot be closer than what we have already found | ||
// eslint-disable-next-line no-continue | ||
continue | ||
} | ||
|
||
const distance = calculateLevenshteinDistance( | ||
normalizedText.toLowerCase(), | ||
lowerCaseSearch, | ||
) | ||
|
||
if (distance > lastClosestDistance) { | ||
// eslint-disable-next-line no-continue | ||
continue | ||
} | ||
|
||
if (distance < lastClosestDistance) { | ||
lastClosestDistance = distance | ||
closestValues = [] | ||
} | ||
closestValues.push(normalizedText) | ||
} | ||
return closestValues | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.