Skip to content
Draft
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
13 changes: 13 additions & 0 deletions packages/shared/src/searchRanking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,19 @@ describe("scoreQueryMatch", () => {
});
});

describe("scoreQueryMatch typo tolerance", () => {
const match = (value: string, query: string) =>
scoreQueryMatch({ value, query, exactBase: 0, prefixBase: 10, fuzzyBase: 50 });

it("recovers a single adjacent transposition without accepting arbitrary edits", () => {
expect(match("search", "serach")).toBe(51);
expect(match("search", "search")).toBe(0);
expect(match("search", "searxh")).toBeNull();
expect(match("cat", "cta")).toBeNull();
expect(match("search", "serahc")).toBeNull();
});
});

describe("scoreSubsequenceMatch", () => {
it("scores tighter subsequences ahead of looser ones", () => {
const compact = scoreSubsequenceMatch("ghfixci", "gfc");
Expand Down
13 changes: 13 additions & 0 deletions packages/shared/src/searchRanking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,16 @@ export function scoreSubsequenceMatch(
return null;
}

/** A single adjacent-key ordering mistake, without broad edit-distance matches. */
function isAdjacentTransposition(value: string, query: string): boolean {
if (query.length < 4 || value.length !== query.length) return false;
let first = 0;
while (first < query.length && value[first] === query[first]) first += 1;
if (first >= query.length - 1) return false;
if (value[first] !== query[first + 1] || value[first + 1] !== query[first]) return false;
return value.slice(first + 2) === query.slice(first + 2);
}

function lengthPenalty(value: string, query: string): number {
return Math.min(64, Math.max(0, value.length - query.length));
}
Expand Down Expand Up @@ -135,6 +145,9 @@ export function scoreQueryMatch(input: {
if (fuzzyScore !== null) {
return input.fuzzyBase + fuzzyScore;
}
if (isAdjacentTransposition(value, query)) {
return input.fuzzyBase + 1;
}
}

return null;
Expand Down
Loading