Skip to content
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

feat: support finding data with typos #153

Merged
merged 1 commit into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/__tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ const tests: Record<string, TestCase> = {
'The Tail of Forty Cities', // match2
],
},
'matches data that has minor typos': {
input: [
['juptyer', 'juppyter', 'jopytar', 'jupytor', 'jepytur'],
'jupyter',
],
output: ['juppyter', 'juptyer', 'jupytor'],
},
'no match for single character inputs that are not equal': {
input: [['abc'], 'd'],
output: [],
Expand Down
29 changes: 18 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,6 @@ function getClosenessRanking(
stringToRank: string,
): Ranking {
let matchingInOrderCharCount = 0
let charNumber = 0
function findMatchingCharacter(
matchChar: string,
string: string,
Expand All @@ -279,23 +278,31 @@ function getClosenessRanking(
}
return -1
}
let skipped = 0
function getRanking(spread: number) {
const spreadPercentage = 1 / spread
const inOrderPercentage = matchingInOrderCharCount / stringToRank.length
const ranking = rankings.MATCHES + inOrderPercentage * spreadPercentage
const matchPercentage = (stringToRank.length - skipped) / stringToRank.length
const ranking = rankings.MATCHES + inOrderPercentage * spreadPercentage * matchPercentage
return ranking as Ranking
}
const firstIndex = findMatchingCharacter(stringToRank[0], testString, 0)
if (firstIndex < 0) {
return rankings.NO_MATCH
}
charNumber = firstIndex
for (let i = 1, I = stringToRank.length; i < I; i++) {
let firstIndex = 0
let charNumber = 0
let nextCharNumber = 0
for (let i = 0, I = stringToRank.length; i < I; i++) {
const matchChar = stringToRank[i]
charNumber = findMatchingCharacter(matchChar, testString, charNumber)
const found = charNumber > -1
if (!found) {
nextCharNumber = findMatchingCharacter(matchChar, testString, charNumber)
const found = nextCharNumber > -1
if (found) {
charNumber = nextCharNumber
if (i === 0) {
firstIndex = charNumber
}
} else if (skipped > 0 || stringToRank.length <= 3) {
// if search term is short, require finding all characters
return rankings.NO_MATCH
} else {
skipped += 1
}
}

Expand Down
Loading