fix: tolerate minor typos in longer exercise search words
This commit is contained in:
1 parent
a68a88d2da
commit
8b75ae9b30
2 files changed
+43
-1
No files matched your search
@@ -191,11 +191,27 @@ function corpusOf(e) {
|
||||
return s
|
||||
}
|
||||
|
||||
// Allow one missing, extra or substituted character, or an adjacent transposition, in long
|
||||
// query tokens. Short tokens stay exact/substring-only: words such as "row" and "curl" are too
|
||||
// common for fuzzy matching to be useful.
|
||||
function nearWord(a, b) {
|
||||
if (a.length < 5 || Math.abs(a.length - b.length) > 1) return false
|
||||
let i = 0
|
||||
while (i < a.length && a[i] === b[i]) i++
|
||||
if (i === a.length) return b.length - i <= 1
|
||||
if (a.length === b.length) {
|
||||
return a.slice(i + 1) === b.slice(i + 1) ||
|
||||
(a[i] === b[i + 1] && a[i + 1] === b[i] && a.slice(i + 2) === b.slice(i + 2))
|
||||
}
|
||||
return a.length > b.length ? a.slice(i + 1) === b.slice(i) : a.slice(i) === b.slice(i + 1)
|
||||
}
|
||||
|
||||
export function matchExercise(e, query) {
|
||||
if (!query) return true
|
||||
const tokens = normalizeStr(query).split(/\s+/).filter(Boolean)
|
||||
if (!tokens.length) return true
|
||||
if (!e || typeof e !== 'object') return false
|
||||
const corpus = corpusOf(e)
|
||||
return tokens.every(tok => corpus.includes(tok))
|
||||
const words = corpus.split(/\s+/)
|
||||
return tokens.every(tok => corpus.includes(tok) || words.some(word => nearWord(tok, word)))
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import { matchExercise } from './exercises.js'
|
||||
|
||||
const benchPress = {
|
||||
n: 'dumbbell bench press', bp: 'chest', tg: 'pectorals', eq: 'dumbbell',
|
||||
sm: ['triceps', 'deltoids'], desc: 'Classic chest exercise using a barbell on a flat bench.',
|
||||
}
|
||||
|
||||
it('allows one edit or adjacent transposition in long query tokens', () => {
|
||||
for (const query of ['dumbell bench', 'dumbbel bench', 'dummbell bench', 'bnech press', 'presss bench']) {
|
||||
expect(matchExercise(benchPress, query), query).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps short tokens and multiple edits out of fuzzy matching', () => {
|
||||
const squat = { n: 'barbell squat', bp: 'legs', eq: 'barbell' }
|
||||
for (const [exercise, query] of [[squat, 'sqat'], [squat, 'roww'], [benchPress, 'dunbell'], [benchPress, 'dumbell unrelated'], [benchPress, 'bn ech']]) {
|
||||
expect(matchExercise(exercise, query), query).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps existing exact substring and all-token behavior', () => {
|
||||
expect(matchExercise(benchPress, 'bench pres')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'press bench')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'bench squat')).toBe(false)
|
||||
})
|
||||
Reference in new issue
Block a user